What if you could stop repeating the same security checks everywhere and handle them all in one place?
Why middleware intercepts requests in NextJS - The Real Reasons
Start learning this pattern below
Jump into concepts and practice - no test required
Imagine you have a website where users must log in to see certain pages. Without middleware, you have to check the login status on every page manually, repeating the same code everywhere.
Manually adding login checks on every page is slow, error-prone, and easy to forget. If you miss one page, unauthorized users might see private info. It also makes your code messy and hard to maintain.
Middleware intercepts requests before they reach your pages. It lets you run code once to check login status, redirect users, or modify requests, keeping your app secure and clean.
if (!userLoggedIn) { redirect('/login') } // repeated in every page
import { NextResponse } from 'next/server'; export function middleware(request) { if (!request.cookies.get('token')) { return NextResponse.redirect(new URL('/login', request.url)); } }
Middleware makes it easy to control access and modify requests globally, improving security and code clarity.
Think of middleware like a security guard at a building entrance who checks everyone before they enter, so you don't have to check inside every room.
Manual checks on every page are repetitive and risky.
Middleware runs once per request to handle common tasks.
This keeps your app secure, clean, and easier to maintain.
Practice
Solution
Step 1: Understand middleware role
Middleware runs before the app processes requests, allowing inspection or modification.Step 2: Identify middleware purpose
It is used for tasks like login checks, redirects, or adding headers before the app handles the request.Final Answer:
To check or modify requests before they reach the app -> Option CQuick Check:
Middleware intercepts requests = B [OK]
- Thinking middleware renders UI components
- Assuming middleware updates databases directly
- Confusing middleware with CSS compilation
Solution
Step 1: Identify continuation method
Next.js middleware uses NextResponse.next() to continue processing the request.Step 2: Eliminate incorrect options
fetch() is for network calls, res.send() is Express.js syntax, render() is unrelated here.Final Answer:
return NextResponse.next() -> Option AQuick Check:
Continue middleware with NextResponse.next() = D [OK]
- Using Express.js methods like res.send()
- Trying to fetch inside middleware to continue
- Calling render() which is not middleware syntax
import { NextResponse } from 'next/server';
export function middleware(request) {
if (!request.cookies.get('token')) {
return NextResponse.redirect(new URL('/login', request.url));
}
return NextResponse.next();
}Solution
Step 1: Analyze cookie check
The middleware checks if the 'token' cookie exists in the request.Step 2: Determine behavior based on cookie
If no token cookie, it redirects to '/login'; otherwise, it continues processing.Final Answer:
The user is redirected to '/login' if no token cookie is found -> Option AQuick Check:
Missing token cookie triggers redirect = A [OK]
- Assuming request is blocked instead of redirected
- Thinking middleware crashes due to syntax
- Ignoring cookie check and assuming request proceeds
import { NextResponse } from 'next/server';
export function middleware(request) {
if (request.nextUrl.pathname === '/admin') {
NextResponse.redirect('/login');
}
return NextResponse.next();
}Solution
Step 1: Check redirect usage
NextResponse.redirect() must be returned to stop further processing.Step 2: Identify missing return
The code calls NextResponse.redirect() but does not return it, so middleware continues incorrectly.Final Answer:
Missing return before NextResponse.redirect() -> Option BQuick Check:
Always return redirect response in middleware = A [OK]
- Forgetting to return redirect response
- Confusing request.nextUrl with request.url
- Thinking NextResponse.next() is disallowed
Solution
Step 1: Define blocking condition
Check if the 'auth' cookie exists when the request is for '/secret'.Step 2: Apply redirect or continue
If no cookie, return a redirect response to '/login'; otherwise, call NextResponse.next() to continue.Final Answer:
Return NextResponse.redirect('/login') if no 'auth' cookie; else return NextResponse.next() -> Option DQuick Check:
Redirect missing auth, else continue = C [OK]
- Not returning redirect response
- Throwing errors instead of redirecting
- Modifying request without returning response
