Complete the code to create middleware that intercepts all requests.
export function [1](req) { return new Response('Intercepted by middleware'); }
The function named middleware is the standard way to intercept requests in Next.js middleware.
Complete the code to check the request URL pathname in middleware.
export function middleware(req) {
const url = req.nextUrl;
if (url.pathname === [1]) {
return new Response('Home page intercepted');
}
}The root path '/' is the pathname for the home page, so checking for it intercepts requests to the home page.
Fix the error in the middleware code to correctly rewrite the request to '/login'.
import { NextResponse } from 'next/server'; export function middleware(req) { return NextResponse.[1]('/login'); }
To change the request path without redirecting, use NextResponse.rewrite(). Redirect sends a new response to the client.
Fill both blanks to create middleware that blocks access to '/admin' and redirects to '/login'.
import { NextResponse } from 'next/server'; export function middleware(req) { const url = req.nextUrl; if (url.pathname === [1]) { return NextResponse.[2]('/login'); } }
Checking for '/admin' blocks that path, and redirect sends the user to '/login'.
Fill all three blanks to create middleware that logs the request method, checks if the path is '/secret', and rewrites to '/login' if so.
import { NextResponse } from 'next/server'; export function middleware(req) { console.log('Request method:', req.[1]); const url = req.nextUrl; if (url.pathname === [2]) { return NextResponse.[3]('/login'); } }
The request method is accessed via req.method. Checking for '/secret' matches the path. Using rewrite changes the request path internally.