Discover how one simple middleware function can save you hours of repetitive security checks!
Why Authentication 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 must log in to see their profile. You check their login status on every page by adding code inside each page component.
Manually adding login checks on every page is tiring and easy to forget. If you miss one, unauthorized users might see private info. It also makes your code messy and hard to update.
Authentication in middleware lets you check user login once before any page loads. This keeps your code clean and secure by handling access in one place automatically.
if (!user) { redirect('/login') } // repeated in every page
import { NextResponse } from 'next/server'; export function middleware(req) { const token = req.cookies.get('token'); if (!token) { return NextResponse.redirect(new URL('/login', req.url)); } }
You can protect your whole site easily and keep your code simple by centralizing login checks.
A social media app uses middleware to block guests from accessing user feeds, so only logged-in users see their personalized content.
Manual login checks on every page are repetitive and risky.
Middleware centralizes authentication before pages load.
This improves security and keeps code clean and maintainable.
Practice
Solution
Step 1: Understand middleware role
Middleware runs before page rendering to control access.Step 2: Identify authentication use
Middleware checks if user is logged in to allow or block access.Final Answer:
To check if a user is logged in before allowing access to certain pages -> Option BQuick Check:
Middleware controls access = C [OK]
- Thinking middleware styles pages
- Confusing middleware with data fetching
- Assuming middleware optimizes images
Solution
Step 1: Check Next.js middleware import
Next.js middleware uses 'next/server' for NextResponse and request handling.Step 2: Identify correct import
Only 'import { NextResponse } from "next/server";' is valid for middleware response.Final Answer:
import { NextResponse } from 'next/server'; -> Option AQuick Check:
Middleware uses NextResponse from next/server [OK]
- Importing middleware from 'next/auth' which doesn't exist
- Using default import from 'next/middleware' which is invalid
- Trying to import hooks for middleware
import { NextResponse } from 'next/server';
export function middleware(request) {
const token = request.cookies.get('token');
if (!token) {
return NextResponse.redirect(new URL('/login', request.url));
}
return NextResponse.next();
}Solution
Step 1: Check token presence
The code checks if 'token' cookie exists; if not, it redirects.Step 2: Understand redirect behavior
Without token, middleware returns redirect to '/login' URL.Final Answer:
The user is redirected to the /login page -> Option CQuick Check:
No token means redirect to /login [OK]
- Assuming user stays on page without token
- Thinking middleware throws error on missing token
- Confusing redirect to homepage instead of /login
import { NextResponse } from 'next/server';
export function middleware(request) {
const token = request.cookies.token;
if (!token) {
return NextResponse.redirect('/login');
}
return NextResponse.next();
}Solution
Step 1: Check cookie access method
In Next.js middleware, cookies are accessed with request.cookies.get('token'), not as a property.Step 2: Verify redirect argument
NextResponse.redirect accepts a URL object or string, but string '/login' is allowed; full URL preferred but not mandatory.Final Answer:
Accessing cookies should use request.cookies.get('token') instead of request.cookies.token -> Option AQuick Check:
Use cookies.get('token') to read cookie [OK]
- Accessing cookies as properties instead of using get()
- Thinking redirect needs full URL always
- Assuming middleware must be async
- Confusing NextResponse.next() with continue()
export const config = {
matcher: ???
};Solution
Step 1: Understand matcher syntax
Matcher accepts array of path patterns; '*' matches subpaths.Step 2: Choose correct pattern for pages
Using ['/dashboard*', '/profile*'] matches both exact and nested routes under these paths.Final Answer:
['/dashboard*', '/profile*'] -> Option DQuick Check:
Use array with wildcard for matcher [OK]
- Using string with pipe '|' instead of array
- Omitting '*' wildcard to match subpaths
- Using comma-separated string instead of array
