In Next.js, middleware runs before a request reaches a page or API route. What is the main reason middleware intercepts requests?
Think about what middleware can do before the page or API handles the request.
Middleware intercepts requests to allow changes like redirects, authentication checks, or header modifications before the request reaches the final page or API route.
Consider this Next.js middleware snippet that redirects users based on a condition. What will the user see if the condition is true?
export function middleware(request) {
if (!request.cookies.get('token')) {
return Response.redirect(new URL('/login', request.url))
}
return Response.next()
}Redirect means sending the user to a different page before loading the original one.
If the token cookie is missing, the middleware redirects the user to /login, so they never see the original page.
Given this middleware code, what header will the final response include?
export function middleware(request) {
const response = Response.next()
response.headers.set('X-Custom-Header', 'HelloWorld')
return response
}Think about how middleware can add headers to responses.
The middleware creates a response with Response.next(), then sets a custom header before returning it. This header will be included in the final response.
Which option correctly fixes the syntax error in this Next.js middleware?
export function middleware(request) {
if request.cookies.get('user') {
return Response.next()
}
return Response.redirect('/login')
}JavaScript requires parentheses around conditions in if statements.
The if statement must have parentheses around its condition. Without them, it's a syntax error.
Examine this middleware code. Why does it cause a runtime error?
export function middleware(request) {
if (!request.cookies.get('session')) {
return Response.redirect('/signin')
}
const response = Response.next()
response.headers.append('Set-Cookie', 'visited=true')
return response
}Consider if the headers of the Response object can be changed after Response.next()
Response.next() returns a response with immutable headers. Trying to append headers causes a runtime error.