Recall & Review
beginner
What is the purpose of middleware in Next.js?
Middleware in Next.js runs before a request is completed. It can modify the request or response, such as redirecting users or rewriting URLs, helping control routing and access.
Click to reveal answer
beginner
How do you perform a redirect in Next.js middleware?
Use the NextResponse.redirect() method with the target URL. This sends the user to a new location before the page loads.
Click to reveal answer
intermediate
What is the difference between redirect and rewrite in Next.js middleware?
Redirect sends the user to a new URL and changes the browser address bar. Rewrite changes the URL internally without changing what the user sees in the address bar.
Click to reveal answer
intermediate
Show a simple example of rewriting a URL in Next.js middleware.
In middleware, use NextResponse.rewrite(new URL('/new-path', request.url)) to serve content from '/new-path' while keeping the original URL visible to the user.
Click to reveal answer
intermediate
Why might you use middleware to redirect users based on their location or device?
Middleware can check request details like headers or cookies and redirect users to region-specific pages or mobile versions, improving user experience without extra client code.
Click to reveal answer
Which Next.js middleware method changes the URL the user sees in the browser?
✗ Incorrect
NextResponse.redirect() sends a redirect response that changes the browser's URL.
What does NextResponse.rewrite() do in Next.js middleware?
✗ Incorrect
Rewrite changes the request URL internally but keeps the original URL visible to the user.
Where does Next.js middleware run in the request lifecycle?
✗ Incorrect
Middleware runs before the request finishes, allowing it to modify or redirect requests.
Which of these is a valid reason to use middleware for redirects?
✗ Incorrect
Middleware can inspect cookies or headers to decide if a redirect is needed.
What is the correct way to rewrite a request to '/dashboard' in middleware?
✗ Incorrect
NextResponse.rewrite() with a new URL rewrites the request internally.
Explain how you would use Next.js middleware to redirect users to a login page if they are not authenticated.
Think about checking user info and sending them somewhere else before loading the page.
You got /3 concepts.
Describe the difference between redirect and rewrite in Next.js middleware and when you might use each.
Consider what the user sees in the browser address bar.
You got /4 concepts.