0
0
NextjsHow-ToBeginner · 3 min read

How to Use Middleware for Redirect in Next.js

In Next.js, use the middleware file to intercept requests and perform redirects by returning a NextResponse.redirect(). This middleware runs before rendering pages, allowing you to redirect users based on URL, cookies, or headers.
📐

Syntax

The middleware function intercepts requests and can return a redirect response using NextResponse.redirect(). You import NextResponse from next/server and export a middleware function that receives a request object.

  • request: The incoming request object.
  • NextResponse.redirect(url): Redirects the user to the specified URL.
  • Return the redirect response to stop further processing.
javascript
import { NextResponse } from 'next/server';

export function middleware(request) {
  // Check condition
  if (/* condition */) {
    return NextResponse.redirect(new URL('/target-path', request.url));
  }
  // Continue normally
  return NextResponse.next();
}
💻

Example

This example redirects all users visiting /old-page to /new-page using middleware. 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-page') {
    url.pathname = '/new-page';
    return NextResponse.redirect(url);
  }

  return NextResponse.next();
}
Output
When visiting '/old-page', the browser is redirected to '/new-page'. Other paths load normally.
⚠️

Common Pitfalls

Common mistakes include:

  • Not returning NextResponse.next() to continue processing when no redirect is needed.
  • Using relative URLs in NextResponse.redirect() instead of absolute URLs or URL objects.
  • Placing middleware in the wrong folder or not naming the file middleware.js or middleware.ts.

Always clone request.nextUrl before modifying it to avoid errors.

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

// Wrong: returning nothing stops the request
export function middleware(request) {
  if (request.nextUrl.pathname === '/old') {
    return NextResponse.redirect(new URL('/new', request.url)); // Correct: use URL object with base
  }
  // Missing return NextResponse.next() causes request to hang
}

// Correct:
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

ConceptDescriptionExample
middleware functionIntercepts requests before page renderingexport function middleware(request) { ... }
NextResponse.redirect()Redirects user to a new URLreturn NextResponse.redirect(new URL('/new', request.url));
request.nextUrlURL object of the incoming requestconst url = request.nextUrl.clone();
NextResponse.next()Continue processing without redirectreturn NextResponse.next();
middleware file locationPlace middleware.js in project root or src/project-root/middleware.js

Key Takeaways

Use Next.js middleware to intercept requests and perform redirects before page rendering.
Always return NextResponse.redirect() with a full URL or URL object to redirect properly.
Return NextResponse.next() to continue normal request processing when no redirect is needed.
Place the middleware file named 'middleware.js' or 'middleware.ts' in the project root or src folder.
Clone request.nextUrl before modifying it to avoid errors.