Given a middleware.ts file in Next.js that intercepts requests, what is the expected behavior when a request URL matches the middleware's matcher pattern?
import { NextResponse } from 'next/server'; export function middleware(request) { if (request.nextUrl.pathname.startsWith('/admin')) { return NextResponse.redirect(new URL('/login', request.url)); } return NextResponse.next(); } export const config = { matcher: ['/admin/:path*'], };
Look at the middleware function and what it returns when the path starts with '/admin'.
The middleware checks if the request path starts with '/admin'. If it does, it returns a redirect response to '/login'. Otherwise, it allows the request to continue normally.
Which option contains a syntax error in a Next.js middleware.ts file?
import { NextResponse } from 'next/server'; export function middleware(request) { if (request.nextUrl.pathname === '/home') { return NextResponse.rewrite('/dashboard'); } return NextResponse.next(); }
Check for missing brackets or incomplete statements.
Option A is missing the closing curly brace for the function, causing a syntax error.
Given this middleware, what URL will the user see in the browser after accessing '/profile'?
import { NextResponse } from 'next/server'; export function middleware(request) { if (request.nextUrl.pathname === '/profile') { return NextResponse.rewrite('/user/profile'); } return NextResponse.next(); }
Consider how NextResponse.rewrite works compared to redirect.
NextResponse.rewrite changes the resource served without changing the URL in the browser. So the URL stays '/profile' but the content is from '/user/profile'.
Examine this middleware code. Why does it cause an infinite redirect loop?
import { NextResponse } from 'next/server'; export function middleware(request) { if (request.nextUrl.pathname !== '/login') { return NextResponse.redirect(new URL('/login', request.url)); } return NextResponse.next(); }
Think about what happens when the request is already at '/login'.
The condition redirects any path not '/login' to '/login'. The infinite loop happens because the redirect response causes the browser to request '/login' again, triggering the middleware again. If the middleware or browser does not properly handle this, it can cause repeated redirects.
In a Next.js middleware.ts file, what does the config.matcher property control?
export const config = { matcher: ['/dashboard/:path*', '/settings'], };
Think about when middleware runs for incoming requests.
The config.matcher property tells Next.js which URL paths should trigger the middleware. Only requests matching these patterns run the middleware code.