Bird
Raised Fist0
NextJSframework~20 mins

Authentication in middleware in NextJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Middleware Authentication Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What happens when an unauthenticated user accesses a protected route?

Consider a Next.js middleware that checks for a valid authentication token in cookies. If the token is missing, the middleware redirects the user to the login page.

What will the user experience when trying to access /dashboard without a token?

NextJS
import { NextResponse } from 'next/server';

export function middleware(request) {
  const token = request.cookies.get('authToken');
  if (!token) {
    return NextResponse.redirect(new URL('/login', request.url));
  }
  return NextResponse.next();
}

export const config = { matcher: ['/dashboard'] };
AThe user sees a blank page because the middleware blocks rendering.
BThe dashboard loads but shows an error message about missing authentication.
CThe user is redirected to the login page before the dashboard loads.
DThe user can access the dashboard without any interruption.
Attempts:
2 left
💡 Hint

Think about what the middleware does when the token is missing.

📝 Syntax
intermediate
2:00remaining
Identify the syntax error in this Next.js middleware for authentication

Which option contains a syntax error that will prevent the middleware from running?

NextJS
import { NextResponse } from 'next/server';

export function middleware(request) {
  const token = request.cookies.get('authToken')
  if (!token) {
    return NextResponse.redirect(new URL('/login', request.url));
  }
  return NextResponse.next();
}

export const config = { matcher: ['/profile'] };
ANo syntax error; the code runs correctly.
BMissing semicolon after getting the token cookie.
CMissing parentheses in the 'middleware' function declaration.
DUsing 'request.cookies.get' instead of 'request.cookies.get()'.
Attempts:
2 left
💡 Hint

Check if JavaScript requires semicolons and if the method calls are correct.

🔧 Debug
advanced
2:00remaining
Why does this middleware fail to redirect unauthenticated users?

The middleware is intended to redirect users without a valid token to the login page. However, unauthenticated users can still access protected pages. What is the likely cause?

NextJS
import { NextResponse } from 'next/server';

export function middleware(request) {
  const token = request.cookies.get('authToken');
  if (token === undefined) {
    return NextResponse.redirect(new URL('/login', request.url));
  }
  return NextResponse.next();
}

export const config = { matcher: ['/settings'] };
AThe matcher pattern does not include the protected route.
BThe check should be for falsy value (!token), not only undefined.
CThe middleware is missing an async keyword.
DThe redirect URL is incorrect and causes a silent failure.
Attempts:
2 left
💡 Hint

Consider what values request.cookies.get() returns when the cookie is missing.

state_output
advanced
2:00remaining
What is the value of the response status after middleware redirect?

In Next.js middleware, when redirecting unauthenticated users, what HTTP status code does the response have?

NextJS
import { NextResponse } from 'next/server';

export function middleware(request) {
  const token = request.cookies.get('authToken');
  if (!token) {
    return NextResponse.redirect(new URL('/login', request.url));
  }
  return NextResponse.next();
}

export const config = { matcher: ['/account'] };
A200 (OK)
B301 (Moved Permanently)
C404 (Not Found)
D307 (Temporary Redirect)
Attempts:
2 left
💡 Hint

Think about the common status code used for temporary redirects.

🧠 Conceptual
expert
3:00remaining
Why use middleware for authentication instead of client-side checks in Next.js?

Which reason best explains why authentication is often handled in Next.js middleware rather than only on client-side components?

AMiddleware runs on the server edge, preventing unauthorized page rendering and reducing data exposure.
BMiddleware allows faster client-side rendering by skipping authentication checks.
CClient-side checks are more secure because they run after the page loads.
DMiddleware can modify React component state directly before rendering.
Attempts:
2 left
💡 Hint

Consider where middleware runs and what it can prevent before the page loads.

Practice

(1/5)
1. What is the main purpose of using middleware for authentication in Next.js?
easy
A. To fetch data from an external API before rendering
B. To check if a user is logged in before allowing access to certain pages
C. To style the pages dynamically based on user preferences
D. To optimize images for faster loading

Solution

  1. Step 1: Understand middleware role

    Middleware runs before page rendering to control access.
  2. Step 2: Identify authentication use

    Middleware checks if user is logged in to allow or block access.
  3. Final Answer:

    To check if a user is logged in before allowing access to certain pages -> Option B
  4. Quick Check:

    Middleware controls access = C [OK]
Hint: Middleware runs before pages to check login [OK]
Common Mistakes:
  • Thinking middleware styles pages
  • Confusing middleware with data fetching
  • Assuming middleware optimizes images
2. Which of the following is the correct way to import middleware in Next.js 14+ for authentication?
easy
A. import { NextResponse } from 'next/server';
B. import { middleware } from 'next/auth';
C. import middleware from 'next/middleware';
D. import { useMiddleware } from 'next/hooks';

Solution

  1. Step 1: Check Next.js middleware import

    Next.js middleware uses 'next/server' for NextResponse and request handling.
  2. Step 2: Identify correct import

    Only 'import { NextResponse } from "next/server";' is valid for middleware response.
  3. Final Answer:

    import { NextResponse } from 'next/server'; -> Option A
  4. Quick Check:

    Middleware uses NextResponse from next/server [OK]
Hint: Middleware uses NextResponse from 'next/server' [OK]
Common Mistakes:
  • Importing middleware from 'next/auth' which doesn't exist
  • Using default import from 'next/middleware' which is invalid
  • Trying to import hooks for middleware
3. Given this middleware code snippet, what happens when a user is not authenticated?
import { NextResponse } from 'next/server';
export function middleware(request) {
  const token = request.cookies.get('token');
  if (!token) {
    return NextResponse.redirect(new URL('/login', request.url));
  }
  return NextResponse.next();
}
medium
A. The middleware throws an error
B. The user stays on the current page without changes
C. The user is redirected to the /login page
D. The user is redirected to the homepage

Solution

  1. Step 1: Check token presence

    The code checks if 'token' cookie exists; if not, it redirects.
  2. Step 2: Understand redirect behavior

    Without token, middleware returns redirect to '/login' URL.
  3. Final Answer:

    The user is redirected to the /login page -> Option C
  4. Quick Check:

    No token means redirect to /login [OK]
Hint: No token cookie triggers redirect to /login [OK]
Common Mistakes:
  • Assuming user stays on page without token
  • Thinking middleware throws error on missing token
  • Confusing redirect to homepage instead of /login
4. Identify the error in this Next.js middleware code for authentication:
import { NextResponse } from 'next/server';
export function middleware(request) {
  const token = request.cookies.token;
  if (!token) {
    return NextResponse.redirect('/login');
  }
  return NextResponse.next();
}
medium
A. Accessing cookies should use request.cookies.get('token') instead of request.cookies.token
B. NextResponse.redirect requires a full URL, not just '/login'
C. Middleware function must be async
D. NextResponse.next() should be replaced with NextResponse.continue()

Solution

  1. Step 1: Check cookie access method

    In Next.js middleware, cookies are accessed with request.cookies.get('token'), not as a property.
  2. Step 2: Verify redirect argument

    NextResponse.redirect accepts a URL object or string, but string '/login' is allowed; full URL preferred but not mandatory.
  3. Final Answer:

    Accessing cookies should use request.cookies.get('token') instead of request.cookies.token -> Option A
  4. Quick Check:

    Use cookies.get('token') to read cookie [OK]
Hint: Use cookies.get('token') to read cookies in middleware [OK]
Common Mistakes:
  • Accessing cookies as properties instead of using get()
  • Thinking redirect needs full URL always
  • Assuming middleware must be async
  • Confusing NextResponse.next() with continue()
5. You want to protect only the /dashboard and /profile pages using middleware authentication. Which matcher configuration correctly applies middleware only to these paths?
export const config = {
  matcher: ???
};
hard
A. ['/dashboard', '/profile']
B. '/dashboard|/profile'
C. '/dashboard/*,/profile/*'
D. ['/dashboard*', '/profile*']

Solution

  1. Step 1: Understand matcher syntax

    Matcher accepts array of path patterns; '*' matches subpaths.
  2. Step 2: Choose correct pattern for pages

    Using ['/dashboard*', '/profile*'] matches both exact and nested routes under these paths.
  3. Final Answer:

    ['/dashboard*', '/profile*'] -> Option D
  4. Quick Check:

    Use array with wildcard for matcher [OK]
Hint: Use array with '*' wildcard for matcher paths [OK]
Common Mistakes:
  • Using string with pipe '|' instead of array
  • Omitting '*' wildcard to match subpaths
  • Using comma-separated string instead of array