0
0
NextJSframework~10 mins

Authentication in middleware in NextJS - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import NextResponse from Next.js.

NextJS
import { [1] } from 'next/server';
Drag options to blanks, or click blank then click option'
AauthMiddleware
BuseMiddleware
ChandleAuth
DNextResponse
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'.
2fill in blank
medium

Complete 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'
Asession_id
Btoken
Cauth_token
Duser_token
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect cookie names like 'session_id' or 'user_token'.
Forgetting to access cookies via 'request.cookies.get'.
3fill in blank
hard

Fix 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'
Aredirect
Bresponse
CResponse
DRedirect
Attempts:
3 left
💡 Hint
Common Mistakes
Using lowercase 'response.redirect' which is undefined.
Trying to use 'Redirect' as a function or class.
4fill in blank
hard

Fill 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'
A/*
B/
C?
D**
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.
5fill in blank
hard

Fill 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'
Atoken
Bsecret_key
C/login
Dauth_token
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.