0
0
NextJSframework~30 mins

Geolocation and edge logic in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Geolocation and Edge Logic with Next.js
📖 Scenario: You are building a Next.js app that shows a personalized greeting based on the user's location. The app uses edge logic to detect the user's country from the request headers and displays a message accordingly.
🎯 Goal: Create a Next.js edge component that reads the user's country from the request headers and renders a greeting message based on the country code.
📋 What You'll Learn
Use Next.js App Router with a server component
Use edge runtime for the page
Read the x-vercel-ip-country header from the request
Create a config variable for supported countries
Render a greeting message based on the country code
Fallback to a default message if the country is not supported
💡 Why This Matters
🌍 Real World
Many websites personalize content based on user location to improve user experience and comply with regional laws.
💼 Career
Understanding edge runtime and geolocation is valuable for building fast, personalized web apps in modern frameworks like Next.js.
Progress0 / 4 steps
1
Create the Next.js page component
Create a new file called page.tsx inside the app directory. Inside it, create a default exported async function called Page that returns a simple <div> with the text "Loading location...".
NextJS
Need a hint?

This is the basic structure of a Next.js server component page.

2
Add edge runtime and supported countries config
Add the line export const runtime = 'edge'; at the top of page.tsx to enable edge runtime. Then create a constant called supportedCountries as an array with the values 'US', 'CA', and 'GB'.
NextJS
Need a hint?

The runtime export tells Next.js to run this page at the edge.

3
Read country from request headers and apply logic
Inside the Page function, get the headers from the Request object by calling headers(). Then get the country code from the header 'x-vercel-ip-country' and store it in a variable called country. Use a conditional to check if country is included in supportedCountries. If yes, set a variable message to `Hello from ${country}!`. Otherwise, set message to 'Hello from somewhere!' . Finally, return a <div> that displays the message.
NextJS
Need a hint?

Use headers() from next/headers to access request headers in edge runtime.

4
Add accessibility and semantic HTML
Wrap the greeting message inside a <main> element with an aria-label attribute set to "User location greeting". Replace the <div> with this <main> element that contains the message inside a <p> tag.
NextJS
Need a hint?

Use semantic HTML and add aria-label for accessibility.