How do _middleware.js files in Cloudflare Pages Functions chain with context.next(), and how does an auth middleware pass the user to the handler?
answer
- a file named for its folder's scope
- export an array to chain
- outer folder runs first
- next() calls inward
- a shared per-request object
basics
~20 sA _middleware.js file runs before every Functions request under its folder, outer folders first. It exports onRequest, or an array run in order; each calls context.next() to continue or returns a Response to stop. Auth middleware stores the user on context.data for the handler.
solid answer
~40 sIn Pages Functions, a `_middleware.js` file applies to every request under its folder that invokes Functions, including subfolders, so `functions/api/_middleware.js` covers `/api`, `/api/contact` and `/api/users/42`. It exports `onRequest` (or a method variant), and the export may be an **array** of functions that run in order. Each function either returns a `Response`, which ends the chain, or returns `await context.next()`, which runs the next middleware, then the route handler, then the static asset server when no handler matches. Middleware in an outer folder runs before middleware in an inner one. Because `next()` returns the downstream response, the first function in the array can wrap everything in `try`/`catch` for error handling. An auth middleware checks the request, returns `401` on failure, and on success sets `context.data.user`, which the handler reads from the same per-request `context.data` object.
code
javascript · 21 lines// functions/api/_middleware.js
async function errorHandling(context) {
try {
return await context.next();
} catch (err) {
console.error(err);
return new Response("Internal error", { status: 500 });
}
}
function authentication(context) {
const expected = context.env.API_TOKEN;
const header = context.request.headers.get("Authorization");
if (!expected || header !== `Bearer ${expected}`) {
return new Response("Unauthorized", { status: 401 });
}
context.data.user = "site-owner";
return context.next();
}
export const onRequest = [errorHandling, authentication];go deeper
Recall the file name, _middleware.js, its folder scope and that context.next() continues while returning a Response stops.
Explain the order (outer folders first, array order inside a file), how next() returns the downstream response, and how context.data carries the user to the handler.
Show the defensive details: fail closed on a missing secret, keep stack traces out of responses, and remember that _routes.json excludes and advanced mode both bypass middleware.
Decide where cross-cutting rules live: root middleware applies everywhere but turns every request into a Functions invocation, so scope each concern to the narrowest folder that needs it.
## What Pages middleware is **Middleware** in Pages Functions is reusable logic that runs before the route handler: authentication, error handling, logging, adding headers. It lives in files named `_middleware.js` (or `.ts`) inside the `functions/` directory, and its **scope is its folder**: | File | Runs for | |---|---| | `functions/_middleware.js` | every request that invokes Functions, including requests that end at a static file | | `functions/api/_middleware.js` | `/api`, `/api/contact`, `/api/users/42` and anything deeper | | `functions/api/admin/_middleware.js` | `/api/admin` and below | A middleware file exports `onRequest`, or a method variant such as `onRequestPost` when it should only run for one method. ## The chain and `context.next()` For one request, the Pages router builds a list: every middleware whose folder contains the path, **outer folders first**, then the matching route handler, then the static asset server as the final fallback. `context.next()` runs the next item in that list and resolves to its `Response`. A middleware therefore has three choices: 1. **Stop the request** by returning its own `Response`, for example `401 Unauthorized`. Nothing further down runs. 2. **Continue** by returning `context.next()`. 3. **Wrap** the rest by awaiting `context.next()`, then inspecting or changing the response, or catching an error thrown further down. Middleware runs even when no route handler matches: for a path under `/api` with no route file, `next()` from the last middleware reaches the static asset server. A folder's middleware protects everything beneath it, files from the build output included, as long as the request invokes Functions. `context.next()` also accepts a new `Request` or URL string, which replaces the request seen by everything downstream. ## One request through the chain For `POST /api/contact` in a project with `functions/_middleware.js`, `functions/api/_middleware.js` exporting `[errorHandling, authentication]`, and `functions/api/contact.js`: 1. The root middleware runs and calls `context.next()`. 2. `errorHandling` runs, enters its `try` and awaits `context.next()`. 3. `authentication` checks the `Authorization` header; on success it sets `context.data.user` and calls `context.next()`. 4. `onRequestPost` in `contact.js` stores the message and returns `201`. 5. The response travels back out through `errorHandling` and the root middleware, either of which may change its headers on the way. If step 3 fails, it returns `401` and steps 4 and 5 never reach the handler; if step 4 throws, step 2's `catch` turns the error into a `500`. ## Chaining inside one file A middleware file can export an **array**: `export const onRequest = [errorHandling, authentication];`. The functions run in array order, so the first one wraps all the others. Placing the error handler first means an exception thrown in `authentication`, in the route handler or in deeper middleware reaches its `catch`. Every function in the chain must **return** a `Response`. A middleware that calls `context.next()` without returning its result returns `undefined`, and the request fails with `Your Pages function should return a Response`. ## Passing data with `context.data` Each request gets one `context.data` object, shared by every middleware and handler in its chain. An authentication middleware validates the credential and records who the caller is: - On failure it returns `401` and the handler never runs. - On success it sets `context.data.user` and calls `context.next()`. - The handler reads `context.data.user` and trusts it, because only code in the chain can write it. `context.data` must stay an object: assigning a string throws `context.data must be an object`. It lives for one request only; it is not a cache, and nothing on it survives to the next request. ## Writing the auth and error middleware safely The example below guards a contact API: - **Fail closed when the secret is missing.** If `API_TOKEN` is not set, the comparison would otherwise accept the literal header `Bearer undefined`. Checking `!expected` first rejects every request until the secret exists. - **Read the secret from `context.env`**, set with `wrangler pages secret put API_TOKEN`, never from a var committed in the Wrangler file. - **Log the error, return a generic body.** Echoing `err.stack` to the client hands internals to anyone who triggers a failure. ## Where middleware does not reach - Requests excluded by the project's `_routes.json` never invoke Functions, so no middleware runs for them. An exclude rule over a protected path removes its protection. - In advanced mode, where a `_worker.js` file replaces the `functions/` directory, `_middleware.js` files are ignored and the Worker composes its own logic.
- A Pages project has functions/_middleware.js and functions/api/_middleware.js. In what order do they run for /api/contact?The root `functions/_middleware.js` runs first, then `functions/api/_middleware.js`, then the route handler in `functions/api/contact.js`. Outer folders wrap inner ones, so the root middleware sees the final response on its way back out.
- Why put the error-handling function first in a middleware array?The array runs in order and each function wraps the ones after it through `context.next()`. The first function's `try`/`catch` therefore catches errors from the later middleware, the route handler and any deeper middleware. Placed last, it would only see errors from the handler.
- How would you make a Pages middleware run only for POST requests?Export `onRequestPost` from the `_middleware.js` file instead of `onRequest`. Middleware exports follow the same method rules as route files, so a `GET` under that folder skips this middleware and continues down the chain.
Pages middleware works like the checkpoints of an office building: the street door is checked first, then each inner door on the way to the room, and you pass the same doors in reverse on the way out. Any guard can turn you back, and the visitor badge issued at the front desk travels with you to the room, the way context.data carries the user to the handler.
- A _middleware.js file only runs for files in its own folder, not subfolders.
- Middleware in an inner folder runs before the middleware in the root folder.
- Middleware does not run when no route file matches the path.
- Values on context.data persist across requests like a cache.
- Each function in a middleware array runs independently, not as one chain.