IP address of the remote origin of the request



Hi, I’m testing the Workers in the Playground available to all users and it seems the Request object does not have information about the connection and socket object. What I need is the IP address of the remote origin of the request:

const ip = req.headers['x-forwarded-for'] || 
 req.connection.remoteAddress || 
 req.socket.remoteAddress ||
 (req.connection.socket ? req.connection.socket.remoteAddress : null);

Will this code work in the Beta and Production release of Workers? Or am I doing anything wrong and there is a different way to get the origin IP address?

Thank you!

Cloudflare Workers Beta Feedback

Hi @diego.parrilla.santa,

The original visitor’s IP address is available in the ‘CF-Connecting-IP’ header – you should find it available in both the Cloudflare Workers Playground, and via the editor in beta/production.

Note that Cloudflare Workers implements the Fetch API, meaning our Request and Headers objects have the same interface as those found in browsers, not Node’s HTTP module, which it looks like you may have expected. Specifically:

  • Headers are not stored as properties, so to access them you’ll need to call req.headers.get('header-name'). Note that will return null if no such header exists – to specifically test for the presence of a header, you can use req.headers.has('header-name').

  • To dump all the headers stored in a Headers object when you’re in the Playground, you can use the following trick: console.log(new Map(req.headers)).

  • Request (and Response) objects have no connection or socket properties.

You can read more about these topics at these links. Let me know if you have any questions!



Than you very much for the tip! Yes, I thought it was like AWS [email protected] and needed to code Node’s HTTP module. But thanks to your hints I have tested successfully the Cloudflare Workers with our API and it works like a charm!

You can find here a gist with the code: https://gist.github.com/diegoparrilla/d7996da7fecb0491c179c150009f565e

The code adds two new headers to the request: Apilityio-Badip and Apilityio-Elapsed-Time. Apilityio-Badip is a list of blacklist names of IP addresses that have included the IP address of the remote client, and Apilitio-Elapse-Time is the milliseconds it took to perform the request to our service endpoint (always below 80ms, awesome!).

My company Apility.io has an API for developers to know if an IP, domain or email could be used to ‘abuse’ of a service. I think that a solution like Cloudflare Workers working at the edge of the network is a very simple and elegant way to give this information to the application or service without the hassle of a code integration. In the coming weeks, we will probably write on our blog about it, because it’s really cool.

Again, thank you very much for the support!


Diego, I’m glad to help, and thank you for sharing the code you came up with!