0
0
NextJSframework~10 mins

Middleware for API routes in NextJS - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Middleware for API routes
API Request Received
Middleware Runs First
Middleware Passes
API Route Handler
Response Sent Back
When an API request comes in, middleware runs first to check or modify the request. If it passes, the API handler runs; if blocked, an error response is sent.
Execution Sample
NextJS
export function middleware(req) {
  if (!req.headers.get('authorization')) {
    return new Response('Unauthorized', { status: 401 });
  }
}

export async function GET(req) {
  return new Response('Success');
}
This middleware checks for an authorization header before allowing the GET API route to respond.
Execution Table
StepActionRequest HeadersMiddleware ResultAPI Handler CalledResponse Sent
1Request received with no authorization header{}Returns 401 UnauthorizedNo401 Unauthorized
2Request received with authorization header{authorization: 'token123'}Passes middlewareYes200 Success
3Request received with empty authorization header{authorization: ''}Passes middleware (header exists)Yes200 Success
4Request received with other headers{content-type: 'json'}Returns 401 UnauthorizedNo401 Unauthorized
💡 Middleware blocks requests missing 'authorization' header, stopping API handler from running.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4
req.headers.get('authorization')undefinedundefined'token123'''undefined
middleware resultnoneResponse 401passpassResponse 401
API handler callednonoyesyesno
response statusnone401200200401
Key Moments - 3 Insights
Why does the API handler not run when the authorization header is missing?
Because the middleware returns a 401 Response early (see execution_table step 1), it stops further processing and the API handler is never called.
If the authorization header is empty, why does the middleware pass?
The middleware only checks if the header exists, not its content. An empty string counts as existing, so it passes (execution_table step 3).
What happens if middleware returns a Response object?
Returning a Response from middleware stops the API handler from running and sends that response immediately (see steps 1 and 4).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the middleware result at step 2?
AReturns 401 Unauthorized
BPasses middleware
CThrows an error
DSkips middleware
💡 Hint
Check the 'Middleware Result' column at step 2 in the execution_table.
At which step does the API handler NOT get called?
AStep 1
BStep 3
CStep 2
DStep 3 and 4
💡 Hint
Look at the 'API Handler Called' column for each step in the execution_table.
If the middleware checked for a specific token value instead of just existence, how would step 3 change?
AAPI handler would not be called
BMiddleware would still pass
CMiddleware would return 401 Unauthorized
DResponse would be 500 error
💡 Hint
Think about how checking token value affects middleware result in step 3's empty string header.
Concept Snapshot
Middleware runs before API routes in Next.js.
It can block or modify requests.
Return a Response in middleware to stop API handler.
Check headers or auth in middleware.
If middleware passes, API route runs normally.
Full Transcript
In Next.js API routes, middleware runs first when a request arrives. It can check things like headers or authorization. If middleware returns a Response, it stops the API handler from running and sends that response immediately. If middleware does not return a Response, the API handler runs and sends its response. For example, middleware can check if an authorization header exists. If missing, it returns a 401 Unauthorized response. If present, the API handler runs and returns success. This flow helps protect API routes by filtering requests early.