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 authentication middleware in Next.js?
Authentication middleware in Next.js checks if a user is logged in before allowing access to certain pages or API routes. It acts like a security guard that verifies identity before entry.
Click to reveal answer
beginner
How do you define middleware in Next.js 14+?
Middleware in Next.js 14+ is a special function exported from a file named middleware.ts or middleware.js in the project root. It runs before a request is completed and can modify the response or redirect users.
Click to reveal answer
beginner
Which Next.js API helps you redirect users inside middleware?
You use the NextResponse.redirect() method to send users to another page, like a login page, if they are not authenticated.
Click to reveal answer
intermediate
What is a common way to check authentication status in Next.js middleware?
A common way is to check for a valid cookie or token in the request headers. If the token is missing or invalid, the middleware redirects the user to the login page.
Click to reveal answer
intermediate
Why is middleware a good place for authentication checks in Next.js?
Middleware runs before the page or API route loads, so it can stop unauthorized users early. This saves resources and improves security by preventing access to protected content.
Click to reveal answer
Where do you place the authentication middleware file in a Next.js 14+ project?
AIn the public folder
BIn the project root as middleware.ts or middleware.js
CInside the components folder
DInside the pages/api folder
✗ Incorrect
Middleware files must be named middleware.ts or middleware.js and placed in the project root to run on every request.
What does NextResponse.redirect() do in middleware?
ARedirects the user to another URL
BLogs the user out
CFetches data from an API
DSets cookies
✗ Incorrect
NextResponse.redirect() sends the user to a different page, commonly used to send unauthenticated users to the login page.
What is a common method to verify if a user is authenticated in middleware?
ACheck the browser's local storage
BCheck the user's IP address
CCheck for a valid token or cookie in the request
DCheck the user's screen size
✗ Incorrect
Authentication usually relies on tokens or cookies sent with the request to verify user identity.
Why should authentication be done in middleware rather than inside page components?
AMiddleware runs before the page loads, preventing unauthorized access early
BMiddleware is easier to write than page components
CPage components cannot access cookies
DMiddleware runs only on the client side
✗ Incorrect
Middleware runs before the page or API route loads, so it can block unauthorized users before rendering.
Which of these is NOT a feature of Next.js middleware?
AModify requests and responses
BRedirect users based on conditions
CRun code on the server before rendering
DDirectly update React component state
✗ Incorrect
Middleware cannot directly update React component state because it runs on the server before rendering.
Explain how authentication middleware works in Next.js and why it is useful.
Think about how middleware acts like a gatekeeper before showing content.
You got /4 concepts.
Describe the steps to create a simple authentication middleware in Next.js 14+.
Focus on file placement, token check, and redirect logic.
You got /4 concepts.
Practice
(1/5)
1. What is the main purpose of using middleware for authentication in Next.js?
easy
A. To fetch data from an external API before rendering
B. To check if a user is logged in before allowing access to certain pages
C. To style the pages dynamically based on user preferences
D. To optimize images for faster loading
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 B
Quick 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
A. import { NextResponse } from 'next/server';
B. import { middleware } from 'next/auth';
C. import middleware from 'next/middleware';
D. import { useMiddleware } from 'next/hooks';
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 A
Quick 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
A. The middleware throws an error
B. The user stays on the current page without changes
C. The user is redirected to the /login page
D. The user is redirected to the homepage
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 C
Quick 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
A. Accessing cookies should use request.cookies.get('token') instead of request.cookies.token
B. NextResponse.redirect requires a full URL, not just '/login'
C. Middleware function must be async
D. NextResponse.next() should be replaced with NextResponse.continue()
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 A
Quick 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
A. ['/dashboard', '/profile']
B. '/dashboard|/profile'
C. '/dashboard/*,/profile/*'
D. ['/dashboard*', '/profile*']
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 D
Quick Check:
Use array with wildcard for matcher [OK]
Hint: Use array with '*' wildcard for matcher paths [OK]