Discover how one simple middleware can save you hours of repetitive redirect headaches!
Why Redirect and rewrite in middleware in NextJS? - Purpose & Use Cases
Start learning this pattern below
Jump into concepts and practice - no test required
Imagine you have a website where users need to be sent to different pages based on their location or login status. You try to handle this by checking every page manually and writing code in each page to redirect users.
This manual approach is slow and messy. You have to repeat the same redirect logic on many pages, making your code hard to maintain. If you forget to add the redirect on one page, users might see wrong content or errors.
Using middleware for redirects and rewrites lets you handle these rules in one place. Middleware runs before your pages load, so you can send users to the right page automatically without repeating code everywhere.
if (!userLoggedIn) { window.location.href = '/login'; }
import { NextResponse } from 'next/server'; export function middleware(request) { if (!request.cookies.get('user')) { return NextResponse.redirect(new URL('/login', request.url)); } }
This lets you control user flow smoothly and securely, improving user experience and keeping your code clean and easy to update.
For example, an online store can redirect users from a general homepage to a country-specific page automatically, or send users to login if they try to access their account without signing in.
Manual redirects on every page cause repeated code and errors.
Middleware centralizes redirect and rewrite logic before pages load.
This improves site speed, security, and maintainability.
Practice
Solution
Step 1: Understand redirect behavior
A redirect sends the user to a new URL and updates the browser's address bar to that URL.Step 2: Understand rewrite behavior
A rewrite changes the content served without changing the URL shown in the browser.Final Answer:
Redirect changes the URL in the browser, rewrite does not. -> Option BQuick Check:
Redirect updates URL, rewrite keeps URL same [OK]
- Thinking rewrite changes browser URL
- Confusing redirect with rewrite
- Assuming both always change URL
Solution
Step 1: Check NextResponse.redirect syntax
The redirect method requires a full URL object, created with new URL(path, base).Step 2: Validate options
return NextResponse.redirect(new URL('/home', request.url)); correctly uses new URL with request.url as base. return NextResponse.redirect('/home'); incorrectly passes a string instead of URL object.Final Answer:
return NextResponse.redirect(new URL('/home', request.url)); -> Option DQuick Check:
Redirect needs URL object [OK]
- Passing string directly to redirect
- Using rewrite instead of redirect
- Missing base URL in new URL()
import { NextResponse } from 'next/server';
export function middleware(request) {
if (request.nextUrl.pathname === '/dashboard') {
return NextResponse.rewrite(new URL('/profile', request.url));
}
return NextResponse.next();
}Solution
Step 1: Analyze rewrite usage
The code uses NextResponse.rewrite to serve '/profile' content when URL is '/dashboard'.Step 2: Understand rewrite effect on URL
Rewrite changes content served but keeps the browser URL unchanged as '/dashboard'.Final Answer:
User sees content from '/profile' but URL stays '/dashboard'. -> Option AQuick Check:
Rewrite changes content, not URL [OK]
- Confusing rewrite with redirect
- Expecting URL to change on rewrite
- Assuming middleware throws error here
import { NextResponse } from 'next/server';
export function middleware(request) {
if (request.nextUrl.pathname === '/old') {
return NextResponse.redirect('/new');
}
return NextResponse.next();
}Solution
Step 1: Check redirect argument type
NextResponse.redirect expects a URL object, not a string path.Step 2: Validate other parts
Condition and NextResponse.next() usage are correct; async not required here.Final Answer:
Redirect requires a full URL object, not a string. -> Option CQuick Check:
Redirect needs URL object, not string [OK]
- Passing string directly to redirect
- Making middleware async unnecessarily
- Checking wrong request property
Solution
Step 1: Understand condition logic
We want to redirect if the path is NOT '/public' or '/login'. Using !includes checks this correctly.Step 2: Check each option's condition
if (!['/public', '/login'].includes(request.nextUrl.pathname)) { return NextResponse.redirect(new URL('/login', request.url)); } return NextResponse.next(); correctly uses negation with includes. if (['/public', '/login'].includes(request.nextUrl.pathname)) { return NextResponse.redirect(new URL('/login', request.url)); } return NextResponse.next(); redirects only on '/public' or '/login' which is wrong. Options C and D have logical errors in conditions.Final Answer:
Option A code correctly redirects except for '/public' and '/login'. -> Option AQuick Check:
Use !includes for exclusion check [OK]
- Using OR instead of AND in conditions
- Redirecting on allowed paths
- Incorrect logical negation
