In Cloudflare Pages Functions, how do onRequest and method exports like onRequestPost decide which handler runs, and what does the context argument carry?
answer
- one generic export, seven method exports
- the specific export wins
- a missing method falls through
- request, env, params, data, next
basics
~20 sA route file exports onRequest for every method or onRequestGet, onRequestPost and the like for one; a method-specific export wins over onRequest. The handler gets a context with request, env, params, data, next(), waitUntil() and functionPath, and must return a Response.
solid answer
~40 sA Pages Functions route file can export `onRequest`, which handles any method, and method variants: `onRequestGet`, `onRequestPost`, `onRequestPut`, `onRequestPatch`, `onRequestDelete`, `onRequestHead` and `onRequestOptions`. If both `onRequest` and `onRequestPost` exist, a `POST` runs only `onRequestPost`. If a file has no handler for the method at all, the router does not answer `405`; it skips the file and the request goes to the next matching route or falls through to static assets. Each handler receives one `context` object: `request`, `env` with bindings, vars and secrets, `params` from the filename, `data` shared along the middleware chain, `next()`, `waitUntil()`, `passThroughOnException()` and `functionPath`. The handler must return a `Response`; anything else fails the request.
code
javascript · 15 lines// functions/api/contact.js
export async function onRequestPost(context) {
const form = await context.request.formData();
const message = String(form.get("message") ?? "").slice(0, 2000);
const id = crypto.randomUUID();
await context.env.MESSAGES.put(`msg:${id}`, message);
return Response.json({ id, by: context.data.user }, { status: 201 });
}
export function onRequest() {
return new Response("Method Not Allowed", {
status: 405,
headers: { Allow: "POST" },
});
}go deeper
Recall the export names, onRequest plus the method variants, and that the handler takes one context object and returns a Response.
Explain the selection rule, what an unhandled method does, and where each context member comes from: params from the filename, env from bindings, data from middleware.
Show you would add a 405 fallback with an Allow header, cover HEAD deliberately and catch non-Response returns, because each silently changes what a client receives.
Treat method handling as an API contract: set a team convention for fallbacks and error shapes so every route file answers unsupported methods the same way.
## Handler exports A **route file** in a Pages project's `functions/` directory is an ES module. The Pages router looks at its **named exports** and recognises exactly these names: | Export | Runs for | |---|---| | `onRequest` | any method, when no more specific export matches | | `onRequestGet` | `GET` | | `onRequestPost` | `POST` | | `onRequestPut` | `PUT` | | `onRequestPatch` | `PATCH` | | `onRequestDelete` | `DELETE` | | `onRequestHead` | `HEAD` | | `onRequestOptions` | `OPTIONS` | The names are case-sensitive: `onRequestPOST` or `onPost` is ignored, and a file whose only export is misnamed never becomes a route. Each export is a function, or an array of functions that run in order through `context.next()`. ## How the router chooses The router tries routes from the most specific to the least specific. At the same path, a method-specific export sorts ahead of `onRequest`, so a file exporting both `onRequestPost` and `onRequest` runs `onRequestPost` for `POST` and `onRequest` for everything else. Three behaviours follow that catch people out: 1. **A missing method is skipped, not refused.** If a file exports only `onRequestPost`, a `GET` to the same path does not get `405 Method Not Allowed`. The router moves on to the next matching route, or falls through to the static assets. With no top-level `404.html` in the build output, Pages answers with the root `index.html` and status `200`. 2. **`onRequestGet` does not cover `HEAD`.** Each method is matched literally, so a `HEAD` request needs `onRequestHead` or `onRequest` to reach your code. 3. **A less specific route can catch the leftovers.** With a GET-only `functions/api/users/me.js` next to `functions/api/users/[id].js`, a `POST /api/users/me` runs `[id].js` with `id` set to `"me"`. The fix for all three is the same: export an `onRequest` fallback in the file that returns `405` with an `Allow` header naming the methods you do support. ## The context object Every handler, and every middleware, receives a single argument, conventionally named `context`: - **`request`**: the incoming `Request`. - **`env`**: the project's bindings, environment variables and secrets, plus `env.ASSETS` for fetching the project's own static files. - **`params`**: values captured by `[id]` and `[[path]]` filenames. - **`data`**: a plain object shared by every middleware and handler in one request's chain. Assigning a non-object throws `context.data must be an object`. - **`next(input?, init?)`**: runs the next handler in the chain, or the static asset server when there is none. - **`waitUntil(promise)`**: keeps work such as logging running after the response is sent. - **`passThroughOnException()`**: on an uncaught error, serve the static asset instead of failing. - **`functionPath`**: the path the route matched. Compared with a plain Worker's `fetch(request, env, ctx)`, the same pieces arrive on one object, and `next`, `params` and `data` are added by the Pages router. ## Work after the response, and failing open `context.waitUntil(promise)` extends the request so a promise, such as a write to an audit log, can finish after the response has gone out. Use it for work the client does not need to wait for; a write the client must be told about, like storing the contact message itself, is awaited before responding so a failure can still produce an error. `context.passThroughOnException()` asks Pages to serve the static asset for the path if the chain throws. Pages implements it by catching the error around your code and calling `env.ASSETS.fetch()`, so a failure such as exceeding the CPU-time or memory limit can still surface as an error rather than falling back. ## The return value A handler must return a `Response` or a promise of one. Returning a string or a plain object fails the request with the error `Your Pages function should return a Response`. `Response.json()` is the short way to send JSON. ## The contact form handler In the example below, `onRequestPost` reads the submitted form, caps the message length, stores it in a KV namespace bound as `MESSAGES`, and answers `201` with the identifier and the user that an earlier middleware put on `context.data`. The `onRequest` export answers every other method with `405` and an `Allow: POST` header, so a `GET` from a crawler never falls through to the site's HTML. ## What to say in an interview - Name the method exports and the rule that the specific one wins. - Say what happens to an unhandled method, and how to return a proper `405`. - List the context members and say where each comes from.
- In a Pages Functions file that exports only onRequestGet, what does a HEAD request get?It does not reach `onRequestGet`. The router matches the method literally, so the file is skipped for `HEAD` and the request goes to the next matching route or to the static assets. Export `onRequestHead`, or an `onRequest` fallback, if the route must answer `HEAD`.
- What happens if a Pages Functions handler returns a plain object instead of a Response?The request fails: the Pages router checks the return value and throws `Your Pages function should return a Response`. An error-handling middleware above it can catch that and answer `500`; otherwise the client sees an error. Wrap JSON in `Response.json()`.
- A file exporting only onRequestPost makes Pages answer GET with a 405.
- When both onRequest and onRequestPost exist, a POST runs both of them.
- onRequestGet also answers HEAD requests, as many servers do.
- A Pages handler may return a plain object and Pages serialises it to JSON.
- context.data can be reassigned to any value, such as a string.