Core Functions of Middleware

Middleware functions run before the server processes cached content or matches routes, giving them a strategic position to influence responses based on the request context.

Key Use Cases for Middleware

Limitations

While middleware offers extensive capabilities, it is not suited for:

Implementation

Middleware is defined in a middleware.ts or middleware.js file at the root of your project or inside the src directory if applicable.

Basic Example


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

export function middleware(request: NextRequest) {
  return NextResponse.redirect(new URL('/home', request.url));
}

export const config = {
  matcher: '/about/:path*',
};

Matching Paths

Middleware can be configured to apply to specific routes using matchers, which can precisely target or exclude routes. Matchers can be simple paths or complex patterns using regular expressions.