Consider a Next.js app using middleware to protect routes under /dashboard. The middleware checks for a valid token cookie. What is the expected behavior when a user without a token tries to access /dashboard/profile?
import { NextResponse } from 'next/server'; export function middleware(request) { const token = request.cookies.get('token')?.value; if (!token) { return NextResponse.redirect(new URL('/login', request.url)); } return NextResponse.next(); } export const config = { matcher: '/dashboard/:path*', };
Think about what the middleware does when the token is missing.
The middleware checks if the token cookie exists. If not, it redirects the user to the login page, preventing access to protected routes.
Which option contains the correct syntax for accessing cookies in Next.js middleware?
export function middleware(request) { const token = request.cookies.get('token')?.value; if (!token) { return NextResponse.redirect(new URL('/login', request.url)); } return NextResponse.next(); }
Check the official Next.js middleware API for cookie access.
In Next.js middleware, cookies are accessed using request.cookies.get('name')?.value. Other options are either invalid or will cause runtime errors.
Given this middleware, what will the user see when accessing /dashboard/settings with a valid token cookie?
import { NextResponse } from 'next/server'; export function middleware(request) { const token = request.cookies.get('token')?.value; if (!token) { return NextResponse.redirect(new URL('/login', request.url)); } return NextResponse.next(); } export const config = { matcher: '/dashboard/:path*', }; // Assume /dashboard/settings page returns <h1>Settings Page</h1>
What does NextResponse.next() do?
When the token exists, the middleware calls NextResponse.next(), allowing the request to continue and render the protected page.
Review this middleware code. Why does it fail to redirect unauthenticated users?
import { NextResponse } from 'next/server'; export function middleware(request) { const token = request.cookies.get('token'); if (!token) { NextResponse.redirect(new URL('/login', request.url)); } return NextResponse.next(); } export const config = { matcher: '/dashboard/:path*', };
Check if the redirect response is properly handled.
The redirect response must be returned to stop the middleware and redirect the user. Without return, the middleware continues and allows access.
Which statement best explains how Next.js middleware enhances the performance of protected routes compared to client-side checks?
Think about where middleware runs in the request lifecycle.
Next.js middleware runs at the edge before the page is served, so it can block unauthorized requests early, saving bandwidth and improving user experience.