typescriptadvanced

Middleware Geo-based Redirect

Redirect users based on their geographic location using Next.js edge middleware.

typescript
// 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.