Redirect and Rewrite in Middleware with Next.js
📖 Scenario: You are building a Next.js website that needs to control user navigation based on the URL path. Sometimes users should be redirected to a new page, and sometimes the URL should be rewritten internally without changing the visible URL.This helps keep URLs clean and user-friendly while managing content behind the scenes.
🎯 Goal: Build a Next.js middleware file that redirects users from /old-home to /home and rewrites requests from /profile to /user/profile internally.This means users typing /old-home will be sent to /home, and users typing /profile will see the profile page but keep the URL /profile in the browser.
📋 What You'll Learn
Create a middleware file named
middleware.js in the root of the Next.js projectUse the Next.js
NextResponse object to handle redirects and rewritesRedirect requests from
/old-home to /home with a 307 statusRewrite requests from
/profile to /user/profile without changing the URLExport a
middleware function that handles the request and returns the correct response💡 Why This Matters
🌍 Real World
Middleware in Next.js is used to manage user navigation, enforce rules, and keep URLs clean and user-friendly.
💼 Career
Understanding middleware redirects and rewrites is important for building professional web apps that handle routing and user experience smoothly.
Progress0 / 4 steps