typescriptadvanced
Middleware Geo-based Redirect
Redirect users based on their geographic location using Next.js edge middleware.
typescriptPress ⌘/Ctrl + Shift + C to copy
// middleware.ts
import { NextRequest, NextResponse } from 'next/server';
const COUNTRY_LOCALE_MAP: Record<string, string> = {
DE: '/de',
FR: '/fr',
ES: '/es',
JP: '/ja',
};
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
const locales = Object.values(COUNTRY_LOCALE_MAP);
if (locales.some((l) => pathname.startsWith(l))) {
return NextResponse.next();
}
if (pathname.startsWith('/api') || pathname.startsWith('/_next') || pathname.includes('.')) {
return NextResponse.next();
}
const country = request.geo?.country || 'US';
const localePath = COUNTRY_LOCALE_MAP[country];
if (localePath) {
const url = request.nextUrl.clone();
url.pathname = `${localePath}${pathname}`;
return NextResponse.redirect(url);
}
return NextResponse.next();
}
export const config = {
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
};Use Cases
- internationalization
- regional content
- multi-language sites
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptintermediate
Edge Middleware Geolocation
Use Vercel Edge geolocation headers to personalize content based on the visitor's country and city.
Best for: GDPR consent flows
#edge#geolocation
typescriptadvanced
Rate Limiter for Edge Functions
Implement sliding window rate limiting in Next.js middleware using in-memory or KV store.
Best for: API protection
#nextjs#rate-limiting
typescriptintermediate
Authentication Middleware Guard
Next.js middleware that checks auth tokens on protected routes and redirects unauthenticated users to login.
Best for: Dashboard access control
#middleware#authentication
typescriptbeginner
Protected Page with Server Redirect
Server Component that checks auth status and redirects unauthenticated users before rendering any content.
Best for: Dashboard pages
#auth#redirect