Track 06 · Lesson 6 of 8APIs and servers
Middleware
Lesson 6 of 8· 8 min
Middleware is code that runs on every request before your route sees it. Each piece does one job (log, check CORS, limit, authenticate, parse) and then either passes the request on or answers it right there. The order they run in matters a lot.
Order the chain
Move pieces up and down, then send each request
- 1JSON body parserbody parsed, next()
- 2Auth401: preflights never carry tokens
- 3LoggerRecords every request
- 4Rate limit100 requests a minute per client
- 5CORSAnswers preflights, adds CORS headers
- →Route handler
4 ordering problems
CORS runs after Auth: preflights get 401 and the browser blocks every cross-origin call.
Logger isn’t first: requests rejected before it never show up in your logs.
Rate limit runs after Auth: a flood of bad tokens still costs a token check each.
The body is parsed before Auth: anonymous clients can make you parse huge bodies.
// Express-style: each runs in this order, and calls next() to pass the request on
app.use(express.json({ limit: "100kb" }))
app.use(requireToken())
app.use(logger())
app.use(rateLimit({ limit: 100, windowMs: 60_000 }))
app.use(cors({ origin: "https://app.example.com" }))
app.post("/orders", createOrder)next() or a response#
Every piece receives the request and does one of two things: calls next() to hand it to the following piece, or returns a response and stops the chain. That’s how a missing token never reaches your route, and how a CORS preflight gets answered without touching your database.
Why order matters#
- Log first, so you also see the requests that get rejected.
- CORS before auth, because preflight requests never carry tokens; put auth first and every cross-origin call fails with a confusing CORS error.
- Rate-limit before expensive work, so floods are dropped cheaply.
- Authenticate before parsing big bodies, so strangers can’t make you parse megabytes.
In Next.js#
Next.js runs one function before matching routes, in a file at the project root. In Next.js 16 it’s called proxy.ts (it was middleware.ts before):
// proxy.ts
import { NextResponse, type NextRequest } from "next/server"
export function proxy(request: NextRequest) {
if (!request.cookies.has("session")) {
return NextResponse.redirect(new URL("/login", request.url))
}
return NextResponse.next()
}
export const config = { matcher: ["/dashboard/:path*"] }
It’s great for redirects, rewrites and quick checks. Real authorization still belongs next to the data, in each route or a shared function, because the proxy can be skipped by paths it doesn’t match.
Check yourself