JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsnextjs
PrevNext
nextjs
senior
middleware

How does Middleware work in Next.js and what are common use cases?

nextjs
middleware
edge
authentication
routing
geolocation
ab-testing
Quick Answer

Next.js Middleware runs before a request is completed, executing at the Edge for low latency. It can rewrite URLs, redirect users, modify headers, and implement authentication checks. Defined in `middleware.ts` at the project root, it runs on every matched route and is ideal for cross-cutting concerns.

Detailed Explanation

What is Middleware?

Middleware is code that runs before a request is completed. It:

  1. Runs at the Edge: Executes in edge locations near users (fast, globally distributed)
  2. Intercepts Requests: Runs before rendering or API routes
  3. Can Modify Response: Rewrite, redirect, add headers, or return early
  4. Is Lightweight: Uses a limited runtime (no Node.js APIs like fs)

File Location

project-root/
├── middleware.ts  // Must be at project root (same level as app/ or pages/)
├── app/
└── pages/

How It Works

  1. Request comes in
  2. Middleware executes
  3. Middleware can:
    • Continue: Pass request to route handler
    • Rewrite: Change destination URL (transparent to user)
    • Redirect: Send user to different URL
    • Return Response: Stop and send custom response

Edge Runtime Limitations

Middleware runs on Edge Runtime, which means:

  • No Node.js APIs (fs, path, etc.)
  • Limited to Web APIs (fetch, Request, Response)
  • Can't use npm packages that depend on Node.js
  • Maximum execution time (usually 30s, varies by platform)

Common Use Cases

  1. Authentication: Check tokens, redirect unauthenticated users
  2. Authorization: Role-based access control
  3. Geolocation: Redirect based on country
  4. A/B Testing: Route users to different variants
  5. Bot Protection: Block or challenge suspicious requests
  6. Feature Flags: Enable/disable features per user
  7. Internationalization: Detect locale, redirect to localized routes
  8. Rate Limiting: Basic request throttling
  9. Logging: Request logging and analytics

Matching Routes

Use config.matcher to specify which routes trigger middleware:

export const config = {
  matcher: [
    '/dashboard/:path*',  // All dashboard routes
    '/api/:path*',        // All API routes
    '/((?!_next/static|favicon.ico).*)', // All except static
  ],
};

Code Examples

Authentication Middleware
// middleware.ts
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
  const token = request.cookies.get('auth-token')?.value;
  const { pathname } = request.nextUrl;

  // Public routes that don't need auth
  const publicRoutes = ['/login', '/signup', '/forgot-password'];
  if (publicRoutes.includes(pathname)) {
    // If logged in, redirect away from auth pages
    if (token) {
      return NextResponse.redirect(new URL('/dashboard', request.url));
    }
    return NextResponse.next();
  }

  // Protected routes - require auth
  if (!token) {
    const loginUrl = new URL('/login', request.url);
    loginUrl.searchParams.set('callbackUrl', pathname);
    return NextResponse.redirect(loginUrl);
  }

  return NextResponse.next();
}

export const config = {
  matcher: [
    '/dashboard/:path*',
    '/settings/:path*',
    '/login',
    '/signup',
  ],
};

Resources

Middleware - Next.js Documentation

docs

Edge Runtime

docs

Related Questions

How do API routes work in Next.js?

mid
api

What is CORS, when do CORS errors occur, and how can they be resolved?

senior
web-apis
Previous
What are Server Actions in Next.js and how do they handle form submissions and mutations?
Next
What performance optimization techniques does Next.js provide?