Authentication in middleware helps check who a user is before they see a page. It keeps parts of your app safe by stopping strangers from getting in.
Authentication in middleware in NextJS
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
NextJS
import { NextResponse } from 'next/server'; export function middleware(request) { // Check user authentication here const token = request.cookies.get('token'); if (!token) { // Redirect to login if no token return NextResponse.redirect(new URL('/login', request.url)); } // Allow request if authenticated return NextResponse.next(); } export const config = { matcher: ['/protected/:path*'], };
The middleware function runs before the page loads.
Use NextResponse.redirect() to send users to login if not authenticated.
Examples
NextJS
export function middleware(request) { const token = request.cookies.get('token'); if (!token) { return NextResponse.redirect(new URL('/login', request.url)); } return NextResponse.next(); }
matcher.NextJS
export function middleware(request) { const token = request.cookies.get('token'); if (!token) { return NextResponse.redirect(new URL('/login', request.url)); } // You can add more checks here return NextResponse.next(); } export const config = { matcher: ['/dashboard/:path*', '/settings/:path*'], };
Sample Program
This middleware checks if a user has a 'token' cookie when they try to access any page under '/profile'. If no token is found, it sends them to the login page. Otherwise, it lets them continue.
NextJS
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(); } export const config = { matcher: ['/profile/:path*'], };
Important Notes
Middleware runs on the server before the page loads.
Cookies are a common way to store authentication tokens.
Use the matcher config to limit middleware to specific routes for better performance.
Summary
Middleware checks user identity before showing pages.
Redirect users to login if they are not authenticated.
Use matcher to protect only certain routes.
Practice
1. What is the main purpose of using middleware for authentication in Next.js?
easy
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]
Hint: Middleware runs before pages to check login [OK]
Common Mistakes:
- Thinking middleware styles pages
- Confusing middleware with data fetching
- Assuming middleware optimizes images
2. Which of the following is the correct way to import middleware in Next.js 14+ for authentication?
easy
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]
Hint: Middleware uses NextResponse from 'next/server' [OK]
Common Mistakes:
- Importing middleware from 'next/auth' which doesn't exist
- Using default import from 'next/middleware' which is invalid
- Trying to import hooks for middleware
3. Given this middleware code snippet, what happens when a user is not authenticated?
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();
}medium
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]
Hint: No token cookie triggers redirect to /login [OK]
Common Mistakes:
- Assuming user stays on page without token
- Thinking middleware throws error on missing token
- Confusing redirect to homepage instead of /login
4. Identify the error in this Next.js middleware code for authentication:
import { NextResponse } from 'next/server';
export function middleware(request) {
const token = request.cookies.token;
if (!token) {
return NextResponse.redirect('/login');
}
return NextResponse.next();
}medium
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]
Hint: Use cookies.get('token') to read cookies in middleware [OK]
Common Mistakes:
- Accessing cookies as properties instead of using get()
- Thinking redirect needs full URL always
- Assuming middleware must be async
- Confusing NextResponse.next() with continue()
5. You want to protect only the /dashboard and /profile pages using middleware authentication. Which matcher configuration correctly applies middleware only to these paths?
export const config = {
matcher: ???
};hard
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]
Hint: Use array with '*' wildcard for matcher paths [OK]
Common Mistakes:
- Using string with pipe '|' instead of array
- Omitting '*' wildcard to match subpaths
- Using comma-separated string instead of array
