Recall & Review
beginner
What is the purpose of middleware in Next.js when protecting routes?
Middleware in Next.js runs before a request reaches a route. It can check if a user is authenticated and redirect them if not, helping protect private pages.
Click to reveal answer
intermediate
How do you check if a user is authenticated inside Next.js middleware?
You typically check for a valid token or session cookie in the request headers or cookies. If missing or invalid, you redirect the user to a login page.
Click to reveal answer
beginner
What is the role of the NextResponse object in middleware?
NextResponse allows you to modify the response, like redirecting users or rewriting URLs before the request reaches the page or API route.
Click to reveal answer
intermediate
Why is middleware a better choice for protecting routes than client-side checks?
Middleware runs on the server before the page loads, so it prevents unauthorized users from even loading protected content, improving security and user experience.
Click to reveal answer
beginner
Give an example of a simple middleware redirecting unauthenticated users to '/login'.
Inside middleware, check if the request has a valid auth token. If not, return NextResponse.redirect(new URL('/login', request.url)). Otherwise, allow the request to continue.
Click to reveal answer
What does Next.js middleware run before?
✗ Incorrect
Middleware runs on the server before the request reaches the route or API handler.
Which object do you use to redirect users inside Next.js middleware?
✗ Incorrect
NextResponse lets you modify the response, including redirects.
What is a common way to identify an authenticated user in middleware?
✗ Incorrect
Authentication is usually verified by checking cookies or tokens sent with the request.
Why is server-side middleware protection more secure than client-side checks?
✗ Incorrect
Middleware blocks unauthorized requests before the page loads, improving security.
Where do you place the middleware file in a Next.js project?
✗ Incorrect
Middleware is placed at the root as middleware.js or middleware.ts to run on all routes or specific paths.
Explain how you would protect a Next.js route using middleware.
Think about checking user identity before the page loads.
You got /4 concepts.
Describe the benefits of using middleware for route protection compared to client-side checks.
Consider timing and security differences.
You got /4 concepts.