Get Cloudflare's HTTP_CF_IPCOUNTRY header with javascript?

后端 未结 4 1079
再見小時候
再見小時候 2021-02-08 11:08

There are many SO questions how to get http headers with javascript, but for some reason they don\'t show up HTTP_CF_IPCOUNTRY header.

If I try to do with php echo

4条回答
  •  醉话见心
    2021-02-08 11:36

    Yes you have to hit the server - but it doesn't have to be YOUR server.

    I have a shopping cart where pretty much everything is cached by Cloudflare - so I felt it would be stupid to go to MY server to get just the countrycode.

    Instead I am using a webworker on Cloudflare (additional charges):

    addEventListener('fetch', event => {
      event.respondWith(handleRequest(event.request))
    })
    
    async function handleRequest(request) {
    
      var countryCode = request.headers.get('CF-IPCountry');
    
      return new Response(
    
        JSON.stringify({ countryCode }),
    
        { headers: {
          "Content-Type": "application/json"
        }});
    }
    

    You can map this script to a route such as /api/countrycode and then when your client makes an HTTP request it will return essentially instantly (for me it's about 10ms).

     /api/countrycode
     {
        "countryCode": "US"
     }
    

    Couple additional things:

    • You can't use webworkers on all service levels
    • It would be best to deploy an actual webservice on the same URL as a backup (if webworkers aren't enabled or supported or for during development)
    • There are charges but they should be neglibible
    • It seems like there's a new feature where you can map a single path to a single script. That's what I am doing here. I think this used to be an enterprise only feature but it's now available to me so that's great.
    • Don't forget that it may be T1 for TOR network

提交回复
热议问题