0
0
NextJSframework~5 mins

Geolocation and edge logic in NextJS

Choose your learning style9 modes available
Introduction

Geolocation helps your app know where a user is. Edge logic runs code close to the user for faster responses.

Show local weather or news based on user location
Redirect users to region-specific pages or languages
Apply discounts or offers only in certain countries
Improve speed by running code on servers near the user
Control content access based on geographic rules
Syntax
NextJS
import { NextRequest, NextResponse } from 'next/server';

export function middleware(request: NextRequest) {
  const country = request.geo?.country || 'US';

  if (country === 'FR') {
    return NextResponse.redirect(new URL('/fr', request.url));
  }

  return NextResponse.next();
}

Use request.geo to get geolocation info like country, city, or latitude.

Middleware runs at the edge, close to users, for fast decisions.

Examples
Redirect users from the US to a US-specific page.
NextJS
import { NextResponse } from 'next/server';

export function middleware(request) {
  const country = request.geo?.country;
  if (country === 'US') {
    return NextResponse.redirect('/us');
  }
  return NextResponse.next();
}
Log the user's city for analytics or debugging.
NextJS
export function middleware(request) {
  const city = request.geo?.city || 'unknown';
  console.log(`User city: ${city}`);
  return NextResponse.next();
}
Rewrite the URL for users in Japan to a special page.
NextJS
import { NextResponse } from 'next/server';

export function middleware(request) {
  if (request.geo?.country === 'JP') {
    return NextResponse.rewrite('/jp-special');
  }
  return NextResponse.next();
}
Sample Program

This middleware checks the user's country. If the user is from Germany (DE), it redirects them to the German page /de. Otherwise, it lets the request continue normally.

NextJS
import { NextRequest, NextResponse } from 'next/server';

export function middleware(request: NextRequest) {
  const country = request.geo?.country || 'Unknown';

  if (country === 'DE') {
    return NextResponse.redirect(new URL('/de', request.url));
  }

  return NextResponse.next();
}
OutputSuccess
Important Notes

Geolocation data depends on the user's IP address and may not be 100% accurate.

Edge middleware runs before your app code, so use it for quick decisions like redirects.

Always provide a fallback if geolocation info is missing.

Summary

Geolocation lets your app know where users are from.

Edge logic runs code near users for faster responses.

Use middleware in Next.js to redirect or rewrite based on location.