How to get current user IP Address in Deno
Published On
In this post we are going to see how to get user IP address in deno.
Please note that IP address is considered personal data so please ensure to follow the data privacy laws.
Step 1: Setup
Create a index.ts file and write hello world deno program
const port = 8080;
const handler = (request: Request): Response => {
return Response.json({ message: "hello world" });
};
Deno.serve({ port }, handler);
Now in terminal run the following command and go to http://localhost:8080
deno run --allow-net --watch index.ts
Step 2: Getting User Ip
Now to get ip address we will access the second arguement that would be info that contains the network information along with other informations
const port = 8080;
const handler = (request: Request, info: Deno.ServeHandlerInfo): Response => {
return Response.json({ userIP: info.remoteAddr.hostname });
};
Deno.serve({ port }, handler);
Now visit localhost again and you will see the output.
You will get the response
{"userIP": "127.0.0.1"}
This is not right, right? But don’t worry this will perfectly work in the deployed version.
To check go to deno playground (requires authentication) and paste the code and you will see the output
Conclusion
So in this post we used deno to get the current user ip address. Please note user ip is private info so you should follow the rule aroound this.
If you have any queries we can discuss it on discord channel.