Bird
Raised Fist0
NextJSframework~20 mins

Middleware.ts file convention 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 Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
Middleware.ts: What happens when a request matches the middleware?

Given a middleware.ts file in Next.js that intercepts requests, what is the expected behavior when a request URL matches the middleware's matcher pattern?

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

export function middleware(request) {
  if (request.nextUrl.pathname.startsWith('/admin')) {
    return NextResponse.redirect(new URL('/login', request.url));
  }
  return NextResponse.next();
}

export const config = {
  matcher: ['/admin/:path*'],
};
AThe middleware redirects the user to '/login' for any URL starting with '/admin'.
BThe middleware allows all requests to '/admin' to proceed without changes.
CThe middleware blocks all requests to '/admin' by returning a 404 response.
DThe middleware modifies the request headers but does not redirect.
Attempts:
2 left
💡 Hint

Look at the middleware function and what it returns when the path starts with '/admin'.

📝 Syntax
intermediate
2:00remaining
Middleware.ts: Identify the syntax error

Which option contains a syntax error in a Next.js middleware.ts file?

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

export function middleware(request) {
  if (request.nextUrl.pathname === '/home') {
    return NextResponse.rewrite('/dashboard');
  }
  return NextResponse.next();
}
Aexport function middleware(request) { return NextResponse.rewrite('/dashboard');
Bexport function middleware(request) { return NextResponse.redirect('/login'); }
Cexport function middleware(request) { return NextResponse.rewrite('/dashboard'); }
Dexport function middleware(request) { return NextResponse.next(); }
Attempts:
2 left
💡 Hint

Check for missing brackets or incomplete statements.

state_output
advanced
2:00remaining
Middleware.ts: What is the output URL after rewrite?

Given this middleware, what URL will the user see in the browser after accessing '/profile'?

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

export function middleware(request) {
  if (request.nextUrl.pathname === '/profile') {
    return NextResponse.rewrite('/user/profile');
  }
  return NextResponse.next();
}
AThe browser URL changes to '/user/profile'.
BThe browser URL changes to '/profile' and content from '/profile' is shown.
CThe browser URL remains '/profile' but content from '/user/profile' is shown.
DThe browser URL changes to '/user/profile' and content from '/profile' is shown.
Attempts:
2 left
💡 Hint

Consider how NextResponse.rewrite works compared to redirect.

🔧 Debug
advanced
2:00remaining
Middleware.ts: Why does this middleware cause an infinite redirect?

Examine this middleware code. Why does it cause an infinite redirect loop?

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

export function middleware(request) {
  if (request.nextUrl.pathname !== '/login') {
    return NextResponse.redirect(new URL('/login', request.url));
  }
  return NextResponse.next();
}
ABecause NextResponse.next() is missing parentheses.
BBecause the redirect URL is malformed and causes a server error.
CBecause the middleware does not return a response for '/login' paths.
DBecause it redirects all paths except '/login' to '/login', including requests already at '/login'.
Attempts:
2 left
💡 Hint

Think about what happens when the request is already at '/login'.

🧠 Conceptual
expert
2:00remaining
Middleware.ts: What is the purpose of the config.matcher property?

In a Next.js middleware.ts file, what does the config.matcher property control?

NextJS
export const config = {
  matcher: ['/dashboard/:path*', '/settings'],
};
AIt sets environment variables for the middleware execution.
BIt specifies which request paths the middleware should run on.
CIt defines the order in which multiple middleware files execute.
DIt controls the caching behavior of middleware responses.
Attempts:
2 left
💡 Hint

Think about when middleware runs for incoming requests.

Practice

(1/5)
1. What is the primary purpose of the middleware.ts file in a Next.js project?
easy
A. To run code before requests reach pages or API routes
B. To define React components for UI rendering
C. To store global CSS styles
D. To configure database connections

Solution

  1. Step 1: Understand middleware role

    Middleware runs before the request reaches pages or APIs, allowing pre-processing.
  2. Step 2: Compare with other file roles

    React components handle UI, CSS files style, and database configs are separate; middleware is for request handling.
  3. Final Answer:

    To run code before requests reach pages or API routes -> Option A
  4. Quick Check:

    Middleware = pre-request code [OK]
Hint: Middleware runs before pages or APIs handle requests [OK]
Common Mistakes:
  • Confusing middleware with UI components
  • Thinking middleware manages styles or database
  • Assuming middleware runs after page rendering
2. Which of the following is the correct way to export a middleware function in middleware.ts?
easy
A. export default function middleware(req) { return NextResponse.next(); }
B. export function middleware(req) { NextResponse.next(); }
C. export const middleware = (req) => NextResponse.next();
D. module.exports = function middleware(req) { return NextResponse.next(); }

Solution

  1. Step 1: Identify modern export syntax

    Next.js middleware uses named export with const arrow function for clarity and modern style.
  2. Step 2: Check syntax validity

    export const middleware = (req) => NextResponse.next(); uses export const middleware = (req) => NextResponse.next(); which is valid and recommended.
  3. Final Answer:

    export const middleware = (req) => NextResponse.next(); -> Option C
  4. Quick Check:

    Use named const export for middleware [OK]
Hint: Use named const arrow function export for middleware [OK]
Common Mistakes:
  • Using CommonJS module.exports instead of ES module export
  • Using default export instead of named export
  • Declaring middleware as a regular function without export
3. Given this middleware.ts snippet, what will happen when a request to /dashboard is made?
import { NextResponse } from 'next/server';

export const config = { matcher: ['/dashboard'] };

export const middleware = (req) => {
  if (!req.cookies.get('token')) {
    return NextResponse.redirect(new URL('/login', req.url));
  }
  return NextResponse.next();
};
medium
A. The user is redirected to /login if no token cookie is present
B. The request proceeds to /dashboard regardless of cookies
C. The middleware throws a runtime error due to missing cookie method
D. The middleware blocks all requests to /dashboard

Solution

  1. Step 1: Analyze matcher and cookie check

    The middleware runs only on /dashboard and checks if 'token' cookie exists.
  2. Step 2: Determine behavior based on cookie presence

    If no token cookie, it redirects to /login; otherwise, it allows the request.
  3. Final Answer:

    The user is redirected to /login if no token cookie is present -> Option A
  4. Quick Check:

    Missing token cookie triggers redirect [OK]
Hint: Check cookie presence to decide redirect or continue [OK]
Common Mistakes:
  • Assuming middleware runs on all routes
  • Thinking request proceeds without token cookie
  • Confusing redirect URL construction
4. Identify the error in this middleware.ts code snippet:
import { NextResponse } from 'next/server';

export const middleware = (req) => {
  if (req.cookies.token === undefined) {
    return NextResponse.redirect('/login');
  }
  return NextResponse.next();
};
medium
A. Missing import of NextRequest from 'next/server'
B. Accessing cookies directly as an object instead of using req.cookies.get()
C. Using arrow function instead of regular function
D. Not exporting config.matcher for route matching

Solution

  1. Step 1: Check cookie access method

    In Next.js middleware, cookies are accessed via req.cookies.get('name'), not as object properties.
  2. Step 2: Identify error cause

    Using req.cookies.token will be undefined or cause error; correct is req.cookies.get('token').
  3. Final Answer:

    Accessing cookies directly as an object instead of using req.cookies.get() -> Option B
  4. Quick Check:

    Use req.cookies.get('token') to access cookies [OK]
Hint: Use req.cookies.get('name') to read cookies in middleware [OK]
Common Mistakes:
  • Accessing cookies as properties instead of using get() method
  • Forgetting to import NextResponse
  • Assuming arrow functions are invalid in middleware
5. You want your middleware.ts to run only on API routes starting with /api/private and redirect users without a valid auth cookie to /api/auth/unauthorized. Which config and middleware code correctly implements this?
hard
A. export const config = { matcher: ['/api/private/:path*'] }; export const middleware = (req) => { if (!req.cookies.get('auth')) { return NextResponse.rewrite(new URL('/api/auth/unauthorized', req.url)); } return NextResponse.next(); };
B. export const config = { matcher: ['/api/private/*'] }; export const middleware = (req) => { if (req.cookies.auth === undefined) { return NextResponse.redirect('/api/auth/unauthorized'); } return NextResponse.next(); };
C. export const config = { matcher: ['/api/private'] }; export default function middleware(req) { if (!req.cookies.get('auth')) { return NextResponse.redirect('/api/auth/unauthorized'); } return NextResponse.next(); };
D. export const config = { matcher: ['/api/private/:path*'] }; export const middleware = (req) => { if (!req.cookies.get('auth')) { return NextResponse.redirect(new URL('/api/auth/unauthorized', req.url)); } return NextResponse.next(); };

Solution

  1. Step 1: Verify matcher pattern for API routes

    The pattern /api/private/:path* correctly matches all routes under /api/private.
  2. Step 2: Check cookie access and redirect method

    Using req.cookies.get('auth') is correct. Redirect uses NextResponse.redirect(new URL(...)) with full URL.
  3. Step 3: Compare options for correctness

    export const config = { matcher: ['/api/private/:path*'] }; export const middleware = (req) => { if (!req.cookies.get('auth')) { return NextResponse.redirect(new URL('/api/auth/unauthorized', req.url)); } return NextResponse.next(); }; uses correct matcher, cookie access, and redirect syntax. Others have errors like wrong cookie access, missing URL object, or rewrite instead of redirect.
  4. Final Answer:

    export const config = { matcher: ['/api/private/:path*'] }; export const middleware = (req) => { if (!req.cookies.get('auth')) { return NextResponse.redirect(new URL('/api/auth/unauthorized', req.url)); } return NextResponse.next(); }; -> Option D
  5. Quick Check:

    Use matcher with :path*, get() for cookies, and redirect with URL [OK]
Hint: Use :path* matcher and req.cookies.get() with NextResponse.redirect(URL) [OK]
Common Mistakes:
  • Using wildcard * instead of :path* in matcher
  • Accessing cookies as properties instead of get()
  • Using rewrite instead of redirect for unauthorized access
  • Not wrapping redirect URL in new URL()