0
0
NextjsHow-ToBeginner · 4 min read

How to Create Middleware in Next.js: Syntax and Example

In Next.js, create middleware by adding a middleware.js or middleware.ts file at the root or in the app directory. Export a middleware function that receives a request and returns a response or modifies the request flow.
📐

Syntax

The middleware file exports a middleware function that runs on every request matching its path. It receives a NextRequest object and returns a NextResponse or redirects.

  • middleware.js: The file where middleware code lives.
  • middleware(request): Function called on requests.
  • NextRequest: Object representing the incoming request.
  • NextResponse: Used to continue, rewrite, redirect, or respond.
javascript
import { NextResponse } from 'next/server';

export function middleware(request) {
  // Your code here
  return NextResponse.next();
}
💻

Example

This example middleware redirects users from /old-path to /new-path. It shows how to check the request URL and return a redirect response.

javascript
import { NextResponse } from 'next/server';

export function middleware(request) {
  const url = request.nextUrl.clone();
  if (url.pathname === '/old-path') {
    url.pathname = '/new-path';
    return NextResponse.redirect(url);
  }
  return NextResponse.next();
}
Output
When visiting /old-path, the browser is redirected to /new-path.
⚠️

Common Pitfalls

Common mistakes when creating middleware in Next.js include:

  • Not placing middleware.js in the root or app folder, so it doesn't run.
  • Forgetting to return NextResponse.next() to continue the request.
  • Using server-only APIs inside middleware, which runs at the edge.
  • Not cloning request.nextUrl before modifying it, causing errors.
javascript
import { NextResponse } from 'next/server';

/* Wrong: modifying request.nextUrl directly without cloning */
export function middleware(request) {
  if (request.nextUrl.pathname === '/old') {
    request.nextUrl.pathname = '/new'; // This causes an error
    return NextResponse.redirect(request.nextUrl);
  }
  return NextResponse.next();
}

/* Right: clone before modifying */
export function middleware(request) {
  const url = request.nextUrl.clone();
  if (url.pathname === '/old') {
    url.pathname = '/new';
    return NextResponse.redirect(url);
  }
  return NextResponse.next();
}
📊

Quick Reference

  • middleware.js: File to create middleware.
  • middleware(request): Function to handle requests.
  • NextRequest: Request object.
  • NextResponse.next(): Continue request.
  • NextResponse.redirect(url): Redirect request.
  • Clone request.nextUrl before changes.

Key Takeaways

Create middleware by exporting a middleware function in middleware.js at the root or app folder.
Use NextResponse.next() to continue requests and NextResponse.redirect() to redirect.
Always clone request.nextUrl before modifying it to avoid errors.
Middleware runs on the edge, so avoid server-only APIs inside it.
Middleware controls request flow before reaching pages or API routes.