Showing Vercel region to visitors

I wanted to add a note at the bottom of this site to say that it is hosted with Vercel. One of their main features is the edge network, meaning this website is served from multiple regions. I thought it would be interesting to also show the exact region each visitor is connecting to when visiting the website.

Implementing this was quite straightforward. Vercel adds the x-vercel-id header to the request, and the value happens to contain the list of regions the request passed through. For example, the value cdg1::4d5pt-1596130887188-b4b691cc02d3 means that the request went through the French CDG1 region. I wrote a simple serverless function which extracts the regions from the header and returns them as a JSON array.

module.exports = (req, res) => {
  const id = req.headers["x-vercel-id"];

  if (typeof id !== "string") {
    res.status(503).json({ error: "Region not available" });
    return;
  }

  const regions = id.split("::").slice(0, -1);
  res.json({ regions });
};

Then we can make a request on the client side, fetch the regions, pick one of them and show it to the visitor.

const Vercel = () => {
  const [regions, setRegions] = useState(null);

  useEffect(() => {
    fetch("/api/region")
      .then((response) => response.json())
      .then((data) => setRegions(data.regions));
  }, []);

  if (regions != null) {
    const first = regions[0].toUpperCase();
    return <span>Served by Vercel from {first}</span>;
  } else {
    return null;
  }
};