Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to import NextResponse from Next.js.
NextJS
import { [1] } from 'next/server';
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect function names like 'useMiddleware' or 'authMiddleware'.
Trying to import middleware from 'next/auth' instead of 'next/server'.
✗ Incorrect
NextResponse is imported from 'next/server' and used to handle redirects and responses in Next.js middleware.
2fill in blank
mediumComplete the code to check if the user token exists in the request cookies.
NextJS
export function middleware(request) {
const token = request.cookies.get('[1]');
if (!token) {
return Response.redirect(new URL('/login', request.url));
}
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect cookie names like 'session_id' or 'user_token'.
Forgetting to access cookies via 'request.cookies.get'.
✗ Incorrect
The cookie named 'token' is commonly used to store the authentication token.
3fill in blank
hardFix the error in the middleware to correctly redirect unauthenticated users.
NextJS
if (!token) { return [1].redirect(new URL('/login', request.url)); }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using lowercase 'response.redirect' which is undefined.
Trying to use 'Redirect' as a function or class.
✗ Incorrect
The 'Response.redirect' method is used to redirect in Next.js middleware.
4fill in blank
hardFill both blanks to allow middleware to run only on protected routes and skip public ones.
NextJS
export const config = {
matcher: ['/dashboard[1]', '/settings[2]']
}; Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '/' which matches only the exact path, not subpaths.
Using '?' or '**' which are not valid in Next.js matcher patterns.
✗ Incorrect
Using '/*' matches all subpaths under '/dashboard' and '/settings'.
5fill in blank
hardFill all three blanks to extract the token, verify it, and allow or redirect accordingly.
NextJS
import { jwtVerify } from 'jose'; export async function middleware(request) { const token = request.cookies.get('[1]'); if (!token) return Response.redirect(new URL('/login', request.url)); try { const { payload } = await jwtVerify(token.value, new TextEncoder().encode('[2]')); request.user = payload; } catch (error) { return Response.redirect(new URL('[3]', request.url)); } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong cookie names like 'auth_token'.
Using incorrect secret key names or values.
Redirecting to wrong URLs on verification failure.
✗ Incorrect
The cookie name is 'token', the secret key is 'secret_key', and redirect on error goes to '/login'.