JavaScript Get Client IP Address using Pure JavaScript
Hi dev's, today I'll show you to how to get ip address using javascript. Sometimes we need to validate our application against ap ip or want to blacklist an ip so that they cannot access our application. So, today's tutorial was about how we get ip address easily using JavaScript.
Get Client IP Address
For getting client ip address we'll use an API of ipify.org which return the response in various way. Let's check the below source code.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>shouts.dev</h1>
<h3>IP Address of user is:</h3>
<p style="color: red;"><strong id="ip"></strong></p>
<script type="text/javascript">
fetch('https://api.ipify.org?format=json')
.then((response) => response.json())
.then((data) => document.getElementById('ip').innerHTML = data.ip);
</script>
</body>
</html>
So, we'll use javascript fetch() method to get the response in a json format. And after that using document.innerHtml we'll show in the p tag. Here's the output we get
That's it for today. I hope you've enjoyed this tutorial. Thanks for reading. ๐