How to get current user IP Address in Cloudflare Workers using Hono Framework

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

terminal
npm create cloudflare@latest

Now select the “Website or web app” and then select hono. For git and deploy choose on your preference.

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.

src/index.ts
import { Hono } from "hono";

const app = new Hono();

app.get("/", (c) =>
  c.json({ userIP: c.req.raw.headers.get("CF-Connecting-IP") })
);

export default app;

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

terminal
"dev:remote": "wrangler dev src/index.ts --remote",
terminal
npm run dev:remote
#or
pnpm run dev --remote 

You will get the response

terminal
{"userIP": "xx.xx.xx.xx"}

Conclusion

So in this post we used Hono framework running cloudflare workers to get the user ip address.

If you have any queries we can discuss it on discord channel.