0
0
NextJSframework~5 mins

Redirect and rewrite in middleware in NextJS

Choose your learning style9 modes available
Introduction

Redirects and rewrites help you send users to different pages or change the URL behind the scenes. Middleware lets you do this before the page loads.

Send users to a login page if they are not signed in.
Change old URLs to new ones without breaking links.
Redirect users based on their location or device type.
Rewrite URLs to hide complex query parameters.
Protect pages by redirecting unauthorized users.
Syntax
NextJS
import { NextResponse } from 'next/server';

export function middleware(request) {
  // Redirect example
  if (request.nextUrl.pathname === '/old-path') {
    return NextResponse.redirect(new URL('/new-path', request.url));
  }

  // Rewrite example
  if (request.nextUrl.pathname === '/about') {
    return NextResponse.rewrite(new URL('/company-info', request.url));
  }

  return NextResponse.next();
}

Use NextResponse.redirect() to send users to a different URL.

Use NextResponse.rewrite() to change the URL internally without changing what the user sees.

Examples
This sends the user to the login page.
NextJS
return NextResponse.redirect(new URL('/login', request.url));
This shows the dashboard page but keeps the original URL in the browser.
NextJS
return NextResponse.rewrite(new URL('/dashboard', request.url));
Redirects from '/old' to '/new'.
NextJS
if (request.nextUrl.pathname === '/old') {
  return NextResponse.redirect(new URL('/new', request.url));
}
Rewrites '/profile' to '/user/profile' internally.
NextJS
if (request.nextUrl.pathname === '/profile') {
  return NextResponse.rewrite(new URL('/user/profile', request.url));
}
Sample Program

This middleware redirects anyone visiting '/home' to '/dashboard'. It also rewrites '/info' to show the content of '/about-us' without changing the URL in the browser.

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

export function middleware(request) {
  const { pathname } = request.nextUrl;

  // Redirect users from /home to /dashboard
  if (pathname === '/home') {
    return NextResponse.redirect(new URL('/dashboard', request.url));
  }

  // Rewrite /info to /about-us internally
  if (pathname === '/info') {
    return NextResponse.rewrite(new URL('/about-us', request.url));
  }

  // Continue normally for other paths
  return NextResponse.next();
}
OutputSuccess
Important Notes

Redirect changes the URL the user sees and sends them to a new page.

Rewrite changes the page content behind the scenes but keeps the URL the same.

Middleware runs before the page loads, so it is good for quick checks and changes.

Summary

Use NextResponse.redirect() to send users to a new URL.

Use NextResponse.rewrite() to change the page content without changing the URL.

Middleware lets you control routing before the page loads.