Creating a dynamic map in the edge
A few months ago, Wes Bos tweeted "Really neat feature of the new SvelteKit website, this dynamic SVG is rendered on the edge and changes based on your location". I decided to port the code to Next.js:
Unless you are using a VPN, the image above should pin where you are.
Use a middleware
Middlewares were introduced in Next.js 12 and here a middleware is being used to identify where the user comes from. Middlewares can be also helpful for A/B testing, internationalization, bot protection and more.
Install a few dependencies
The map is plotted with the help the d3-geo, d3-geo-projection and topojson-client. The d3-geo
might take you back to the geography classes. Here is a different map with the same location info:
Create an endpoint to return a SVG
The endpoint to return a SVG is similar to the Vue implementation, however since this is Next.js I am using getServerSideProps
to get the location information and rendering the SVG with a handler
function. The endpoint file lives in the api
folder. I chose this folder instead of the regular pages
folder since Next.js expects React components instead of content with a different mimetype.
Create a redirect
This is kind of optional additional step, but I decided to add a redirect in my Next.js config to avoid
Final result
The whole implementation, including this post, is added to the website in this pull request.