0
0
NextJSframework~15 mins

Redirect and rewrite in middleware in NextJS - Deep Dive

Choose your learning style9 modes available
Overview - Redirect and rewrite in middleware
What is it?
Redirect and rewrite in middleware are ways to change the URL or the response before it reaches the page in a Next.js app. Redirect sends the user to a different URL, while rewrite changes the URL internally without changing what the user sees. Middleware runs code on every request to decide if and how to redirect or rewrite URLs.
Why it matters
Without redirect and rewrite in middleware, apps would have to handle URL changes inside pages or servers, which can be slower and less flexible. Middleware lets you control routing early, improving performance and user experience by handling things like authentication redirects or URL cleanups before loading pages.
Where it fits
You should know basic Next.js routing and how middleware works before learning this. After this, you can explore advanced routing patterns, authentication flows, and edge functions that use middleware for fast, secure responses.
Mental Model
Core Idea
Middleware acts like a traffic controller that decides if a request should be sent to a new address (redirect) or quietly sent to a different place behind the scenes (rewrite) before reaching the final page.
Think of it like...
Imagine a mailroom clerk who checks every letter (request). If the letter is addressed incorrectly, they send it back with a new address (redirect). If the letter is fine but needs to be delivered to a different department without the sender knowing, they quietly move it there (rewrite).
┌─────────────┐
│ Incoming    │
│ Request URL │
└──────┬──────┘
       │
       ▼
┌─────────────┐
│ Middleware  │
│ Checks URL  │
│             │
│ ┌─────────┐ │
│ │Redirect │─┼─> Sends new URL to client
│ └─────────┘ │
│ ┌─────────┐ │
│ │Rewrite  │─┼─> Changes URL internally
│ └─────────┘ │
└──────┬──────┘
       │
       ▼
┌─────────────┐
│ Final Page  │
│ or Resource │
└─────────────┘
Build-Up - 7 Steps
1
FoundationWhat is Middleware in Next.js
🤔
Concept: Middleware is code that runs before a request reaches a page or API route in Next.js.
Middleware runs on the edge, meaning it executes close to the user before the main server handles the request. It can inspect the request URL, headers, or cookies and decide what to do next.
Result
You can run code on every request to control routing or add logic before loading pages.
Understanding middleware is key because it lets you control requests early, improving speed and flexibility.
2
FoundationDifference Between Redirect and Rewrite
🤔
Concept: Redirect changes the URL the user sees and sends them to a new page, while rewrite changes the URL internally without changing what the user sees.
Redirect example: User visits /old, middleware sends them to /new, browser URL changes. Rewrite example: User visits /blog, middleware rewrites to /api/blog-data internally, browser URL stays /blog.
Result
Redirect changes the browser address bar; rewrite does not.
Knowing this difference helps you choose the right tool for user experience or internal routing.
3
IntermediateImplementing Redirect in Middleware
🤔Before reading on: do you think redirect in middleware changes the URL visible to the user or only internally? Commit to your answer.
Concept: You can use NextResponse.redirect() in middleware to send users to a new URL with a status code.
Example: import { NextResponse } from 'next/server'; export function middleware(request) { if (request.nextUrl.pathname === '/old') { return NextResponse.redirect(new URL('/new', request.url)); } return NextResponse.next(); } This sends users from /old to /new, changing the browser URL.
Result
Users visiting /old see their browser URL change to /new and load that page.
Understanding how to trigger redirects in middleware lets you control user navigation early and efficiently.
4
IntermediateImplementing Rewrite in Middleware
🤔Before reading on: do you think rewrite in middleware changes the browser URL or only the internal request path? Commit to your answer.
Concept: You can use NextResponse.rewrite() to change the request path internally without changing the browser URL.
Example: import { NextResponse } from 'next/server'; export function middleware(request) { if (request.nextUrl.pathname === '/blog') { return NextResponse.rewrite(new URL('/api/blog-data', request.url)); } return NextResponse.next(); } This makes /blog load content from /api/blog-data but keeps the URL as /blog.
Result
Users see /blog in the browser but get content from /api/blog-data behind the scenes.
Knowing how to rewrite URLs lets you serve content flexibly without confusing users with URL changes.
5
IntermediateCombining Redirect and Rewrite Logic
🤔Before reading on: can middleware handle both redirect and rewrite in the same function? Commit to your answer.
Concept: Middleware can decide dynamically to redirect or rewrite based on request conditions.
Example: import { NextResponse } from 'next/server'; export function middleware(request) { const { pathname } = request.nextUrl; if (pathname === '/old') { return NextResponse.redirect(new URL('/new', request.url)); } if (pathname === '/blog') { return NextResponse.rewrite(new URL('/api/blog-data', request.url)); } return NextResponse.next(); } This handles both cases in one place.
Result
Requests to /old redirect to /new; requests to /blog rewrite internally; others proceed normally.
Combining both lets you centralize routing logic for cleaner, faster apps.
6
AdvancedHandling Edge Cases and Status Codes
🤔Before reading on: do you think you can customize HTTP status codes for redirects in middleware? Commit to your answer.
Concept: You can specify status codes like 301 or 302 for redirects and handle query strings or headers in middleware.
Example: return NextResponse.redirect(new URL('/new', request.url), 301); You can also preserve query parameters or add headers before redirecting or rewriting.
Result
Redirects behave as permanent or temporary based on status code; headers can control caching or security.
Controlling status codes and headers in middleware is crucial for SEO and security best practices.
7
ExpertPerformance and Security Implications of Middleware Redirects
🤔Before reading on: do you think middleware redirects always improve performance? Commit to your answer.
Concept: Middleware runs on the edge for speed but improper use of redirects can cause extra network hops or security risks.
Redirects add an extra HTTP request cycle, so overusing them can slow down user experience. Also, careless redirects can open security holes like open redirect attacks. Proper validation and minimal redirects improve performance and safety.
Result
Well-designed middleware redirects speed up routing and protect users; poor design harms both.
Understanding the tradeoffs helps build fast, secure apps that use middleware redirects wisely.
Under the Hood
Middleware in Next.js runs on the edge network before the request reaches the main server or page. It intercepts the request and can return a response early, such as a redirect or rewrite. Redirects send a 3xx HTTP status with a new Location header to the browser, causing it to request a new URL. Rewrites modify the request URL internally on the edge, so the server receives a different path but the browser URL stays the same. This happens without a full round trip to the origin server for routing decisions.
Why designed this way?
Next.js designed middleware to run on the edge to reduce latency by handling routing logic closer to users. Redirects and rewrites are separated to give developers control over user-visible URL changes versus internal routing. This design balances flexibility, performance, and user experience. Alternatives like handling redirects inside pages or servers add delay and complexity, so edge middleware is a modern solution.
┌───────────────┐
│ User Request  │
└───────┬───────┘
        │
        ▼
┌───────────────┐
│ Edge Network  │
│ Runs Middleware│
│ ┌───────────┐ │
│ │Redirect?  │─┼─> Sends 3xx + Location to browser
│ └───────────┘ │
│ ┌───────────┐ │
│ │Rewrite?   │─┼─> Changes request URL internally
│ └───────────┘ │
└───────┬───────┘
        │
        ▼
┌───────────────┐
│ Origin Server │
│ or Page      │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does a rewrite in middleware change the URL shown in the browser? Commit to yes or no.
Common Belief:Rewrite changes the URL the user sees in the browser.
Tap to reveal reality
Reality:Rewrite only changes the internal request path; the browser URL stays the same.
Why it matters:Confusing rewrite with redirect can cause unexpected user experience issues, like users seeing URLs that don't match the content.
Quick: Do middleware redirects always make the app faster? Commit to yes or no.
Common Belief:Redirects in middleware always improve app performance.
Tap to reveal reality
Reality:Redirects add an extra HTTP request cycle, which can slow down the user experience if overused.
Why it matters:Overusing redirects can degrade performance, so they should be used thoughtfully.
Quick: Can middleware run after the page loads? Commit to yes or no.
Common Belief:Middleware runs after the page loads to modify content.
Tap to reveal reality
Reality:Middleware runs before the page loads, intercepting requests early on the edge.
Why it matters:Misunderstanding middleware timing can lead to wrong assumptions about where to put logic.
Quick: Is it safe to redirect to any URL from middleware without checks? Commit to yes or no.
Common Belief:You can redirect to any URL from middleware without validation.
Tap to reveal reality
Reality:Redirecting without validation can cause security risks like open redirect attacks.
Why it matters:Ignoring validation can expose users to phishing or malicious redirects.
Expert Zone
1
Middleware runs on the edge with cold starts; minimizing logic improves latency significantly.
2
Redirects with 301 status are cached by browsers and CDNs, so changing them later requires careful cache invalidation.
3
Rewrites can be chained or combined with headers to implement complex routing without user-visible URL changes.
When NOT to use
Avoid using middleware redirects for complex authentication flows that require server-side session checks; use API routes or server components instead. Also, do not use rewrites for large content transformations; use dedicated backend services.
Production Patterns
Common patterns include redirecting unauthenticated users to login pages, rewriting clean URLs to API endpoints, and handling locale-based routing with middleware for fast internationalization.
Connections
HTTP Status Codes
Redirects use specific HTTP status codes like 301 and 302 to tell browsers how to handle URL changes.
Understanding HTTP status codes helps you control browser caching and SEO behavior when redirecting.
Edge Computing
Middleware runs on edge servers close to users, leveraging edge computing principles for speed.
Knowing edge computing explains why middleware can intercept requests faster than traditional servers.
Mailroom Sorting Systems
Middleware's role in routing requests is like sorting mail to the right department or forwarding it.
Seeing middleware as a sorting system clarifies its role in directing traffic efficiently.
Common Pitfalls
#1Redirecting without preserving query parameters.
Wrong approach:return NextResponse.redirect(new URL('/new', request.url));
Correct approach:const url = request.nextUrl.clone(); url.pathname = '/new'; return NextResponse.redirect(url);
Root cause:Not cloning and modifying the URL causes query parameters to be lost, breaking expected behavior.
#2Using rewrite when a redirect is needed for SEO.
Wrong approach:return NextResponse.rewrite(new URL('/new', request.url));
Correct approach:return NextResponse.redirect(new URL('/new', request.url), 301);
Root cause:Misunderstanding rewrite vs redirect causes SEO issues because search engines see the wrong URL.
#3Redirecting to user-provided URLs without validation.
Wrong approach:return NextResponse.redirect(new URL(request.nextUrl.searchParams.get('redirect')));
Correct approach:const safeUrl = new URL(request.nextUrl.origin); const redirectPath = request.nextUrl.searchParams.get('redirect'); if (redirectPath && redirectPath.startsWith('/')) { safeUrl.pathname = redirectPath; return NextResponse.redirect(safeUrl); } return NextResponse.next();
Root cause:Not validating redirect targets opens security holes like open redirects.
Key Takeaways
Middleware in Next.js runs before pages load to control routing early and efficiently.
Redirect changes the browser URL and sends a new request; rewrite changes the request path internally without changing the URL shown.
Using redirect and rewrite properly improves user experience, SEO, and app performance.
Middleware runs on the edge, making routing decisions faster but requiring careful design to avoid extra network hops or security risks.
Understanding when and how to use redirect versus rewrite is essential for building flexible, secure Next.js applications.