Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Recall & Review
beginner
What is the purpose of middleware in Next.js when protecting routes?
Middleware in Next.js runs before a request reaches a route. It can check if a user is authenticated and redirect them if not, helping protect private pages.
Click to reveal answer
intermediate
How do you check if a user is authenticated inside Next.js middleware?
You typically check for a valid token or session cookie in the request headers or cookies. If missing or invalid, you redirect the user to a login page.
Click to reveal answer
beginner
What is the role of the NextResponse object in middleware?
NextResponse allows you to modify the response, like redirecting users or rewriting URLs before the request reaches the page or API route.
Click to reveal answer
intermediate
Why is middleware a better choice for protecting routes than client-side checks?
Middleware runs on the server before the page loads, so it prevents unauthorized users from even loading protected content, improving security and user experience.
Click to reveal answer
beginner
Give an example of a simple middleware redirecting unauthenticated users to '/login'.
Inside middleware, check if the request has a valid auth token. If not, return NextResponse.redirect(new URL('/login', request.url)). Otherwise, allow the request to continue.
Click to reveal answer
What does Next.js middleware run before?
AAfter the page is rendered
BOnly after user logs in
COnly on client-side navigation
DBefore the request reaches a route or API
✗ Incorrect
Middleware runs on the server before the request reaches the route or API handler.
Which object do you use to redirect users inside Next.js middleware?
ANextResponse
BNextRequest
CRouter
DResponse
✗ Incorrect
NextResponse lets you modify the response, including redirects.
What is a common way to identify an authenticated user in middleware?
ACheck the user's IP address
BCheck for a session cookie or token
CCheck the browser's local storage
DCheck the page URL
✗ Incorrect
Authentication is usually verified by checking cookies or tokens sent with the request.
Why is server-side middleware protection more secure than client-side checks?
ABecause it runs after the page loads
BBecause it uses JavaScript on the client
CBecause it prevents unauthorized content from loading at all
DBecause it only runs on mobile devices
✗ Incorrect
Middleware blocks unauthorized requests before the page loads, improving security.
Where do you place the middleware file in a Next.js project?
AIn the root directory as middleware.js or middleware.ts
BInside /public folder
CInside /components folder
DIn the /pages directory
✗ Incorrect
Middleware is placed at the root as middleware.js or middleware.ts to run on all routes or specific paths.
Explain how you would protect a Next.js route using middleware.
Think about checking user identity before the page loads.
You got /4 concepts.
Describe the benefits of using middleware for route protection compared to client-side checks.
Consider timing and security differences.
You got /4 concepts.
Practice
(1/5)
1. What is the main purpose of middleware in Next.js when protecting routes?
easy
A. To check user authentication before allowing access to certain pages
B. To style the pages dynamically based on user preferences
C. To preload images for faster page loading
D. To manage database connections automatically
Solution
Step 1: Understand middleware role
Middleware runs before a page loads to control access or modify requests.
Step 2: Identify protection purpose
In protected routes, middleware checks if a user is authenticated before allowing access.
Final Answer:
To check user authentication before allowing access to certain pages -> Option A
Quick Check:
Middleware protects routes by checking authentication [OK]
Hint: Middleware runs before page load to check user access [OK]
Common Mistakes:
Thinking middleware styles pages
Confusing middleware with database management
Assuming middleware preloads images
2. Which of the following is the correct way to export middleware in Next.js to protect routes?
easy
A. export function middleware() { /* code */ }
B. function middleware() { /* code */ } export middleware
C. export middleware = () => { /* code */ }
D. export default function middleware(req) { /* code */ }
Solution
Step 1: Recall Next.js middleware export syntax
Middleware must be exported as the default export function named middleware.
Step 2: Check options for correct syntax
Only export default function middleware(req) { /* code */ } uses "export default function middleware(req)" which is valid syntax.
Final Answer:
export default function middleware(req) { /* code */ } -> Option D
Quick Check:
Middleware uses default export function [OK]
Hint: Middleware must be default exported as a function named middleware [OK]
Common Mistakes:
Using named export instead of default
Assigning middleware to a variable without export default
Incorrect export statement syntax
3. Given this middleware code snippet, what happens when a user is not authenticated?
import { NextResponse } from 'next/server';
export default function middleware(req) {
const token = req.cookies.get('token');
if (!token) {
return NextResponse.redirect(new URL('/login', req.url));
}
return NextResponse.next();
}
medium
A. The user stays on the current page without any change
B. The user is redirected to the /login page
C. The middleware throws an error and stops loading
D. The user is redirected to the homepage
Solution
Step 1: Analyze token check in middleware
The middleware checks if the 'token' cookie exists; if not, it triggers a redirect.
Step 2: Understand redirect behavior
If no token, middleware returns a redirect response to '/login' page.
Final Answer:
The user is redirected to the /login page -> Option B
Quick Check:
No token causes redirect to login [OK]
Hint: No token cookie means redirect to login page [OK]
Common Mistakes:
Assuming user stays on page without token
Thinking middleware throws error on missing token
Confusing redirect target URL
4. Identify the error in this middleware code that aims to protect routes:
import { NextResponse } from 'next/server';
export default function middleware(req) {
const token = req.cookies.token;
if (!token) {
return NextResponse.redirect('/login');
}
return NextResponse.next();
}
medium
A. Missing async keyword in middleware function
B. Redirect URL should be absolute, not relative
C. Accessing cookies incorrectly; should use req.cookies.get('token')
D. NextResponse.next() should be replaced with NextResponse.continue()
Solution
Step 1: Check cookie access method
In Next.js middleware, cookies are accessed with req.cookies.get('token'), not req.cookies.token.
Step 2: Verify redirect usage
Redirect can accept a relative path, so that is valid here.
Final Answer:
Accessing cookies incorrectly; should use req.cookies.get('token') -> Option C
Quick Check:
Use req.cookies.get('token') to read cookies [OK]
Hint: Use req.cookies.get('token') to read cookies in middleware [OK]
Common Mistakes:
Using dot notation for cookies object
Thinking redirect URL must be absolute
Confusing NextResponse.next() with continue()
5. You want to protect only the routes starting with /dashboard using middleware. Which is the correct way to apply middleware only to these routes?
hard
A. export const config = { matcher: ['/dashboard/:path*'] };
B. export const config = { matcher: ['/dashboard*'] };
C. export const config = { matcher: ['/dashboard'] };
D. export const config = { matcher: ['/dashboard/**'] };
Solution
Step 1: Understand matcher pattern syntax
The matcher uses path patterns where ':path*' matches all subpaths under /dashboard.
Step 2: Compare options for correct pattern
export const config = { matcher: ['/dashboard/:path*'] }; uses '/dashboard/:path*' which correctly matches /dashboard and all nested routes.