User Location in Headers

Is it possible to configure netlify to respond with assumed user location in response headers in the same way CloudFront can expose “CloudFront-Viewer-Country” property in headers?

Thank you!

Hi @kschaffter,

When you use netlify to proxy, our proxy will add a x-country header that you can use to get the country code for the client request IP address. Note that this is passed to Netlify functions as well since those requests pass through our proxy.

Hi @futuregerald

Do you think you could provide me with more details on implementing this?

Thank you

Hey @kschaffter,
Yes! I’ll try to elaborate on @futuregerald’s advice. The thing to keep in mind is that the x-country header is only added to requests that pass through our proxy, so in order to access it, you have to route your requests through our proxy and sort of… intercept their headers. It’s not as simple as checking a box in our UI somewhere, and there are two ways I know of to do it.

Use Netlify to proxy to a backend service.
You can see a demo of this by:

  1. Setting up a Netlify site
  2. Setting up a demo endpoint on a free service like RequestBin.com
  3. Creating a proxy rule in your _redirects file that routes requests to your Netlify site to the endpoint. Your _redirects file would look like:
    / https://requestbin.com/r/ENDPOINT 200!
    where ENDPOINT is whatever random string that’s assigned to you for a free RequestBin endpoint. More on our redirects and syntax here: Redirects and rewrites | Netlify Docs
  4. Navigating to your Netlify site in the browser (which will automatically route you to the endpoint, since you set up a forced redirect)
  5. Inspect the headers that accompany the proxied request. x-country will be there!

Use a Netlify Function as an endpoint.
Netlify Function calls pass through our proxy, and you can use a backend framework like Express.js inside a Netlify Function to grab the headers that are sent along the way. Here is an example where you can see x-country among the headers that are passed along:
https://examples.netlify.horse/withexpress

What this function/endpoint does is say “in the body of the html, render the headers that are passed from Netlify’s proxy to the endpoint.”

Hope this helps! Happy to answer any other questions on this or share code if that would be helpful.

2 Likes