Skip to main content
Web Development

How to Use Next.js Middleware for Advanced SEO Redirects and Geotargeting

Learn how to leverage Next.js Middleware to handle enterprise-level 301 redirects, block bad bots, and implement edge-level geo-redirection.

TechSEO Editorial Team
TechSEO Editorial Team
Published: July 10, 2026Updated: July 10, 2026
Computer server diagram showing edge function request routing.

Key Takeaways

  • Next.js Middleware runs at the edge before a request is completed, lowering server response time.
  • You can execute redirect logic and rewrite URLs dynamically based on headers.
  • Geotargeting is managed at the network edge by reading geography headers from request metadata.

Managing URL redirects, localization rules, and client-routing logic at the origin server adds processing latency. By the time a traditional server processes request headers and issues a 301 Redirect header, valuable milliseconds have passed, increasing your Time to First Byte (TTFB).

Next.js Middleware resolves this by moving the routing logic to the network edge. Running in a lightweight V8 runtime rather than a full Node.js environment, middleware intercept incoming requests on CDN edge nodes before they reach your primary server. This enables edge-level URL rewrites, high-performance redirect maps, geotargeting, and bot filtering at near-zero latency.


1. Edge-Level Redirects at Scale

When migrating large enterprise websites, managing thousands of legacy URLs is a major challenge. Storing thousands of redirects in your next.config.js is not recommended, as it bloats the build process and is difficult to update.

With Edge Middleware, you can check incoming paths against a fast lookup map (or an external key-value database like Redis) and redirect the user instantly.

Here is a typical enterprise-grade implementation of middleware.ts:

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

// In production, this map can be imported from a JSON file or fetched from an Edge KV store.
const REDIRECT_MAP: Record<string, string> = {
  '/legacy-page': '/blog/modern-seo-guide',
  '/products/old-app': '/products/new-suite',
  '/company/about-us': '/about',
};

export function middleware(request: NextRequest) {
  const { pathname, search } = request.nextUrl;

  // 1. Check if the path matches a lookup rule
  if (REDIRECT_MAP[pathname]) {
    const targetUrl = new URL(REDIRECT_MAP[pathname], request.url);
    // Append any existing query parameters to the target URL
    targetUrl.search = search;
    return NextResponse.redirect(targetUrl, 301);
  }

  // 2. Fall through to the page renderer if no match
  return NextResponse.next();
}

// Restrict the middleware to only execute on page routes to protect asset latency
export const config = {
  matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - api (API routes)
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico (favicon file)
     */
    '/((?!api|_next/static|_next/image|favicon.ico).*)',
  ],
};

2. Geotargeting and Localization

Serving localized versions of your site (e.g., redirecting users to /us, /uk, or /in subdirectories) requires detecting the user's location.

Edge platforms like Vercel automatically attach geographic headers to incoming requests. You can read these headers in your middleware to route the user:

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
  const url = request.nextUrl.clone();
  
  // 1. Extract the country code provided by the Edge hosting platform
  const country = request.headers.get('x-vercel-ip-country') || 'us';
  
  // 2. Identify search engine crawlers (avoid redirecting Googlebot)
  const userAgent = request.headers.get('user-agent') || '';
  const isSearchBot = /Googlebot|bingbot|yandexbot/i.test(userAgent);

  // 3. Skip redirects for crawlers to ensure indexing of regional versions
  if (isSearchBot) {
    return NextResponse.next();
  }

  // 4. Redirect based on region if accessing the root path '/'
  if (url.pathname === '/') {
    if (country === 'gb') {
      url.pathname = '/uk';
      return NextResponse.redirect(url);
    } else if (country === 'in') {
      url.pathname = '/in';
      return NextResponse.redirect(url);
    }
  }

  return NextResponse.next();
}

3. Bot Detection and Spam Filtering

Malicious bots scraping content can overwhelm your application server and drive up database queries. You can use edge middleware to intercept these requests and block them instantly.

import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

const BLOCKED_BOT_REGEX = /dotbot|semrushbot|ahrefsbot|mj12bot|rogerbot/i;

export function middleware(request: NextRequest) {
  const userAgent = request.headers.get('user-agent') || '';

  if (BLOCKED_BOT_REGEX.test(userAgent)) {
    // Return a 403 Forbidden status code directly at the edge
    return new NextResponse('Access Denied: Scraper detected.', {
      status: 403,
      statusText: 'Forbidden',
    });
  }

  return NextResponse.next();
}

4. Best Practices for SEO Middleware

When implementing edge-level routing logic, keep these rules in mind:

  1. Exempt Static Assets: Always configure a strict matcher array in your middleware.ts configuration. Running routing scripts on JS, CSS, and image files slows down asset loading.
  2. Preserve Query Parameters: Ensure that redirect handlers forward URL query strings (such as utm_source or pagination variables) to the new destination.
  3. Avoid Redirect Loops: Verify that destination pages do not trigger secondary rules that point back to the source.
  4. Use correct status codes: Use 301 for permanent URL migrations and 302 for temporary redirects.

Official References

Frequently Asked Questions

When should I use Next.js Middleware instead of next.config.js redirects?

Use next.config.js for static redirects. Use Middleware when redirect rules are dynamic, require inspection of cookies or geo-location headers, or exceed the size limits of static config arrays.

Does Edge Middleware support database lookups?

Yes, but lookups should be cached or resolved via low-latency Edge databases (like Redis or Firestore) to avoid delaying the request response path.

Can Googlebot crawl pages behind country-based redirects?

Careful. If you redirect purely based on IP country, you might block Googlebot (which typically crawls from US IPs). Always exempt search bots from automated geotargeting redirects.

Does Next.js middleware increase page load latency?

Middleware runs at the Vercel Edge Network, meaning executions are under 50ms. As long as you avoid blocking database requests, the performance impact is negligible.

How can I bypass middleware for static assets?

Use a custom matcher in middleware.ts to exclude paths like /_next, /static, images, sitemaps, and robots.txt from middleware execution.

Is middleware compatible with Next.js App Router caching?

Yes, but dynamic middleware executions that modify headers or cookies can bypass static caching if not properly configured with page-level cache control rules.

TechSEO Editorial Team
TechSEO Editorial Team

Founder & Editor, TechSEO Insights

The TechSEO Editorial Team writes practical SEO, AI tools, and web development guides based on hands-on research, testing, and real website optimization work.

Subscribe to TechSEO Insights

Get the latest guides on technical SEO, Core Web Vitals, and content marketing delivered straight to your inbox.

Privacy Note: By subscribing, you agree to receive our newsletter (Lawful Basis: Consent). We retain your email address until you choose to unsubscribe. For more details, view our Privacy Policy.