How to get current user IP Address in Cloudflare Workers
Published On
Sometimes there are security requirement to get the user ip address so let’s see how can we get user ip while using cloudflare workers.
Please note that IP address is considered personal data so please ensure to follow the data privacy laws.
Step 1: Setup
Let’s create a new cloudflare app
npm create cloudflare@latest
Now select the “Hello World” workers
Step 2: Getting User Ip
Now in the src/index.ts file we will try to access the user ip.
Cloudflare workers request has the header “CF-Connecting-IP”. We can access this header to get the user ip address.
export interface Env {}
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
return Response.json({ userIP: request.headers.get('CF-Connecting-IP') });
},
};
Now run the server in the remote mode. If you run the server without remote mode then you will not get the ip address.
If you’re using npm then add a new script in package.json
"dev:remote": "wrangler dev --remote",
npm run dev:remote
#or
pnpm run dev --remote
You will get the response
{"userIP": "xx.xx.xx.xx"}
Conclusion
So in this post we used cloudflare workers to get the user ip address.
If you have any queries we can discuss it on discord.