Comment by cloudfudge
3 days ago
As an old-timer who's not up on all the latest whiz-bang web stuff, I have to ask what is the astro/cloudflare/wrangler magic that allows the following to work:
const { latitude = "0", longitude = "0" } = Astro.locals.runtime.cf || {};
I gather you're using some cloudflare feature wrapped in astro to provide lat/long but I don't see the actual plumbing that gets it to you (and I did try to spelunk through a decent amount of documentation to find it). Can you elaborate?
There is no visible plumbing because it kinda is magic! Astro provides adapters for different server runtimes (e.g., Vercel, Cloudflare, Netlify), and it's basically just plug and play. The Cloudflare adapter exposes a bunch of bindings [1] through `Astro.locals.runtime`, which can be accessed during each request. The `cf` binding contains incoming request properties [2], including latitude and longitude.
These bindings (or at least some of them) are also mocked when developing locally, in a non-Cloudflare-Workers environment.
[1] https://developers.cloudflare.com/workers/wrangler/api/#supp...
[2] https://developers.cloudflare.com/workers/runtime-apis/reque...
Great explanation; thanks.
Any ideas on how to do this without the Cloud flare magic, so entirely in the client? Just based on time will suffice, with latitude approximated to somewhere such as London?
You can enable a feature in Cloudflare which will inject the approximate user's lat/lng (based on their IP (and other factors?)) as an HTTP header added to the original request:
https://developers.cloudflare.com/network/ip-geolocation/
"This Managed Transform adds HTTP request headers with location information for the visitor's IP address, such as city, country, continent, longitude, and latitude."