Bird
Raised Fist0
NextJSframework~5 mins

Protected routes with middleware in NextJS - Cheat Sheet & Quick Revision

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
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?
AAfter the page is rendered
BOnly after user logs in
COnly on client-side navigation
DBefore the request reaches a route or API
Which object do you use to redirect users inside Next.js middleware?
ANextResponse
BNextRequest
CRouter
DResponse
What is a common way to identify an authenticated user in middleware?
ACheck the user's IP address
BCheck for a session cookie or token
CCheck the browser's local storage
DCheck the page URL
Why is server-side middleware protection more secure than client-side checks?
ABecause it runs after the page loads
BBecause it uses JavaScript on the client
CBecause it prevents unauthorized content from loading at all
DBecause it only runs on mobile devices
Where do you place the middleware file in a Next.js project?
AIn the root directory as middleware.js or middleware.ts
BInside /public folder
CInside /components folder
DIn the /pages directory
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.

      Practice

      (1/5)
      1. What is the main purpose of middleware in Next.js when protecting routes?
      easy
      A. To check user authentication before allowing access to certain pages
      B. To style the pages dynamically based on user preferences
      C. To preload images for faster page loading
      D. To manage database connections automatically

      Solution

      1. Step 1: Understand middleware role

        Middleware runs before a page loads to control access or modify requests.
      2. Step 2: Identify protection purpose

        In protected routes, middleware checks if a user is authenticated before allowing access.
      3. Final Answer:

        To check user authentication before allowing access to certain pages -> Option A
      4. Quick Check:

        Middleware protects routes by checking authentication [OK]
      Hint: Middleware runs before page load to check user access [OK]
      Common Mistakes:
      • Thinking middleware styles pages
      • Confusing middleware with database management
      • Assuming middleware preloads images
      2. Which of the following is the correct way to export middleware in Next.js to protect routes?
      easy
      A. export function middleware() { /* code */ }
      B. function middleware() { /* code */ } export middleware
      C. export middleware = () => { /* code */ }
      D. export default function middleware(req) { /* code */ }

      Solution

      1. Step 1: Recall Next.js middleware export syntax

        Middleware must be exported as the default export function named middleware.
      2. Step 2: Check options for correct syntax

        Only export default function middleware(req) { /* code */ } uses "export default function middleware(req)" which is valid syntax.
      3. Final Answer:

        export default function middleware(req) { /* code */ } -> Option D
      4. Quick Check:

        Middleware uses default export function [OK]
      Hint: Middleware must be default exported as a function named middleware [OK]
      Common Mistakes:
      • Using named export instead of default
      • Assigning middleware to a variable without export default
      • Incorrect export statement syntax
      3. Given this middleware code snippet, what happens when a user is not authenticated?
      import { NextResponse } from 'next/server';
      
      export default function middleware(req) {
        const token = req.cookies.get('token');
        if (!token) {
          return NextResponse.redirect(new URL('/login', req.url));
        }
        return NextResponse.next();
      }
      medium
      A. The user stays on the current page without any change
      B. The user is redirected to the /login page
      C. The middleware throws an error and stops loading
      D. The user is redirected to the homepage

      Solution

      1. Step 1: Analyze token check in middleware

        The middleware checks if the 'token' cookie exists; if not, it triggers a redirect.
      2. Step 2: Understand redirect behavior

        If no token, middleware returns a redirect response to '/login' page.
      3. Final Answer:

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

        No token causes redirect to login [OK]
      Hint: No token cookie means redirect to login page [OK]
      Common Mistakes:
      • Assuming user stays on page without token
      • Thinking middleware throws error on missing token
      • Confusing redirect target URL
      4. Identify the error in this middleware code that aims to protect routes:
      import { NextResponse } from 'next/server';
      
      export default function middleware(req) {
        const token = req.cookies.token;
        if (!token) {
          return NextResponse.redirect('/login');
        }
        return NextResponse.next();
      }
      medium
      A. Missing async keyword in middleware function
      B. Redirect URL should be absolute, not relative
      C. Accessing cookies incorrectly; should use req.cookies.get('token')
      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 req.cookies.get('token'), not req.cookies.token.
      2. Step 2: Verify redirect usage

        Redirect can accept a relative path, so that is valid here.
      3. Final Answer:

        Accessing cookies incorrectly; should use req.cookies.get('token') -> Option C
      4. Quick Check:

        Use req.cookies.get('token') to read cookies [OK]
      Hint: Use req.cookies.get('token') to read cookies in middleware [OK]
      Common Mistakes:
      • Using dot notation for cookies object
      • Thinking redirect URL must be absolute
      • Confusing NextResponse.next() with continue()
      5. You want to protect only the routes starting with /dashboard using middleware. Which is the correct way to apply middleware only to these routes?
      hard
      A. export const config = { matcher: ['/dashboard/:path*'] };
      B. export const config = { matcher: ['/dashboard*'] };
      C. export const config = { matcher: ['/dashboard'] };
      D. export const config = { matcher: ['/dashboard/**'] };

      Solution

      1. Step 1: Understand matcher pattern syntax

        The matcher uses path patterns where ':path*' matches all subpaths under /dashboard.
      2. Step 2: Compare options for correct pattern

        export const config = { matcher: ['/dashboard/:path*'] }; uses '/dashboard/:path*' which correctly matches /dashboard and all nested routes.
      3. Final Answer:

        export const config = { matcher: ['/dashboard/:path*'] }; -> Option A
      4. Quick Check:

        Use '/dashboard/:path*' to match dashboard and subpaths [OK]
      Hint: Use ':path*' to match all subpaths under a route [OK]
      Common Mistakes:
      • Using wildcard * without colon for subpaths
      • Matching only exact /dashboard without subpaths
      • Using invalid glob pattern like /**