0
0
NextJSframework~5 mins

Redirect and rewrite in middleware in NextJS - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
ANextResponse.rewrite()
BNextResponse.redirect()
CNextResponse.next()
DNextResponse.json()
What does NextResponse.rewrite() do in Next.js middleware?
AChanges the URL internally without changing the browser address bar
BRedirects the user to a new URL
CStops the request and returns an error
DSends JSON data to the client
Where does Next.js middleware run in the request lifecycle?
ABefore the request is completed
BAfter the page is rendered
COnly on the client side
DOnly during build time
Which of these is a valid reason to use middleware for redirects?
ATo change the page content after rendering
BTo style the page dynamically
CTo redirect users based on cookies or headers
DTo fetch data from an API
What is the correct way to rewrite a request to '/dashboard' in middleware?
Areturn NextResponse.redirect('/dashboard')
Breturn NextResponse.json({ path: '/dashboard' })
Creturn NextResponse.next()
Dreturn NextResponse.rewrite(new URL('/dashboard', request.url))
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.