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
Middleware for API routes in Next.js
📖 Scenario: You are building a Next.js API that needs to check if a user is authenticated before allowing access to certain routes. Middleware will help you run this check automatically for every request to these routes.
🎯 Goal: Create a middleware function for Next.js API routes that checks for a specific header x-api-key. If the header is missing or incorrect, the middleware should respond with a 401 status. Otherwise, it should allow the request to continue to the API handler.
📋 What You'll Learn
Create a middleware function in Next.js for API routes
Check for the presence of the x-api-key header
Compare the header value to a predefined secret key
Return a 401 Unauthorized response if the key is missing or wrong
Allow the request to continue if the key is correct
💡 Why This Matters
🌍 Real World
Middleware is commonly used in web apps to protect API routes by checking authentication or other conditions before running the main logic.
💼 Career
Understanding middleware in Next.js is important for building secure and maintainable backend APIs in modern React applications.
Progress0 / 4 steps
1
Create the API route handler
Create a file pages/api/hello.js with a default export function called handler that takes req and res parameters and responds with JSON { message: 'Hello, world!' }.
NextJS
Hint
This is the basic API route handler that sends a JSON response.
2
Define the secret API key
Above the handler function, create a constant called API_KEY and set it to the string 'secret123'.
NextJS
Hint
This key will be used to check incoming requests.
3
Create the middleware function
Create an async function called middleware that takes req and res. Inside it, check if req.headers['x-api-key'] is not equal to API_KEY. If so, respond with status 401 and JSON { error: 'Unauthorized' } and return. Otherwise, call await handler(req, res) to continue.
NextJS
Hint
This middleware checks the API key and blocks unauthorized requests.
4
Export the middleware as default
Change the default export to be the middleware function instead of handler.
NextJS
Hint
This makes the middleware the main function Next.js calls for this API route.
Practice
(1/5)
1. What is the main purpose of middleware in Next.js API routes?
easy
A. To run code before the API route handles a request
B. To replace the API route handler completely
C. To style the API response
D. To store data permanently on the server
Solution
Step 1: Understand middleware role
Middleware runs before the API route handler to process requests.
Step 2: Identify correct purpose
It can check, block, or modify requests but does not replace handlers or style responses.
Final Answer:
To run code before the API route handles a request -> Option A
Quick Check:
Middleware runs before API handler [OK]
Hint: Middleware runs before API handler to control requests [OK]
Common Mistakes:
Thinking middleware replaces the API handler
Confusing middleware with styling or storage
Assuming middleware runs after the API handler
2. Which of the following is the correct way to continue to the API route handler inside Next.js middleware?
Hint: Use NextResponse.next() to proceed to API handler [OK]
Common Mistakes:
Using NextResponse.stop() which blocks the request
Confusing redirect() with continuing
Forgetting to return NextResponse.next()
3. Given this middleware code, what will happen when a request with header x-auth: secret is sent?
import { NextResponse } from 'next/server';
export function middleware(request) {
if (request.headers.get('x-auth') !== 'secret') {
return NextResponse.redirect(new URL('/unauthorized', request.url));
}
return NextResponse.next();
}
medium
A. The request is redirected to /unauthorized
B. The request continues to the API route handler
C. The middleware throws an error
D. The request is blocked with no response
Solution
Step 1: Check header condition
The middleware checks if 'x-auth' header equals 'secret'. If yes, it continues.
Step 2: Analyze given header
The request has 'x-auth: secret', so condition is false and middleware returns NextResponse.next().
Final Answer:
The request continues to the API route handler -> Option B
Quick Check:
Header matches 'secret' so continue [OK]
Hint: Check header value to decide redirect or continue [OK]
Common Mistakes:
Assuming redirect happens even if header matches
Thinking middleware throws error on mismatch
Ignoring header case sensitivity
4. Identify the error in this Next.js middleware code:
import { NextResponse } from 'next/server';
export function middleware(request) {
if (!request.headers.get('authorization')) {
NextResponse.redirect('/login');
}
return NextResponse.next();
}
medium
A. Using 'authorization' header instead of 'auth'
B. Middleware function must be async
C. NextResponse.next() should be inside the if block
D. Missing return before NextResponse.redirect
Solution
Step 1: Check redirect usage
NextResponse.redirect must be returned to stop further processing.
Step 2: Identify missing return
The code calls NextResponse.redirect but does not return it, so middleware continues incorrectly.
Final Answer:
Missing return before NextResponse.redirect -> Option D
Quick Check:
Always return redirect response [OK]
Hint: Always return redirect to stop middleware flow [OK]
Common Mistakes:
Not returning redirect response
Thinking middleware must be async
Misplacing NextResponse.next() inside if block
5. You want to create middleware that blocks requests to API routes if the query parameter token is missing or empty. Which code correctly implements this behavior?
hard
A. export function middleware(request) {
const url = new URL(request.url);
if (!url.searchParams.get('token')) {
return NextResponse.redirect(new URL('/error', request.url));
}
return NextResponse.next();
}
B. export function middleware(request) {
if (!request.query.token) {
return NextResponse.redirect('/error');
}
return NextResponse.next();
}
C. export function middleware(request) {
if (request.url.token === '') {
return NextResponse.next();
}
return NextResponse.redirect('/error');
}
D. export function middleware(request) {
const token = request.headers.get('token');
if (!token) {
return NextResponse.next();
}
return NextResponse.redirect('/error');
}
Solution
Step 1: Access query parameters correctly
Use new URL(request.url) and url.searchParams.get('token') to read query params.
Step 2: Check token presence and redirect if missing
If token is missing or empty, redirect to /error; otherwise continue with NextResponse.next().
Final Answer:
Code that checks query param and redirects if missing -> Option A
Quick Check:
Use URL and searchParams for query checks [OK]
Hint: Use URL and searchParams to check query tokens [OK]