skip to content

Pages Function Routes

Pages Functions turn files under functions/ into routes that run on Workers, with middleware and bindings. Interviewers ask how _routes.json limits invocations and when _worker.js takes over.

on this pageshow

explore

questions

6

In Cloudflare Pages Functions, how do files under functions/ become routes, and how do [id] and [[path]] filenames capture URL segments?

level: juniorimportance: must knowfreq 35%

answer

  1. the folder tree is the route table
  2. index.js serves the folder path
  3. one bracket pair, one segment
  4. two bracket pairs, any depth
  5. context.params: string versus array

basics

~20 s

Each file under functions/ serves the URL path that mirrors its location, and index.js serves its folder. A [id].js file matches exactly one segment, read as a string from context.params.id; [[path]].js matches any depth and yields an array.

solid answer

~40 s

Pages builds its route table from the `functions/` directory: `functions/about.js` serves `/about`, `functions/api/index.js` serves `/api`, and a trailing slash is optional. A filename in single brackets, such as `functions/api/users/[id].js`, matches exactly one path segment and exposes it as a string in `context.params.id`. Double brackets, such as `functions/docs/[[path]].js`, match any number of segments and expose them as an array, so `/docs/a/b/c` gives `["a", "b", "c"]`. When several files could match, the more specific route wins: a fixed name beats `[id]`, which beats `[[path]]`. A file only becomes a route if it exports `onRequest` or a method variant such as `onRequestPost`. If no Function matches, the request falls through to the project's static assets.

code

javascript · 10 lines
javascript
// functions/api/users/[id].js -> /api/users/42
export function onRequest(context) {
  return Response.json({ id: context.params.id });
}

// functions/docs/[[path]].js -> /docs/a/b/c
export function onRequestGet(context) {
  const segments = context.params.path ?? [];
  return Response.json({ depth: segments.length, segments });
}

go deeper

for a junior

Recall the mapping: the file path under functions/ is the URL, index.js serves its folder, single brackets capture one segment and double brackets capture any depth.

for a middle

Explain the types on context.params, the specificity order (fixed, then parameter, then catch-all) and that unmatched requests fall through to static assets.

for a senior

Show you can predict surprising matches, such as a POST skipping a GET-only file and landing in a parameter route, or a mistyped API path answering 200 with the single-page app's HTML.

for a principal

Weigh file-based routing against advanced mode: the tree keeps routes reviewable in a pull request, while a large existing Worker may not split into files without a rewrite.

## What file-based routing means in Pages Functions **Pages Functions** is the server-side layer of a Cloudflare Pages project: JavaScript or TypeScript files in a `functions/` directory at the project root that Wrangler compiles into a single Worker at deploy time. You never write a router. The **directory structure is the route table**: where a file sits under `functions/` decides which URL path runs it. A file joins the table only when it exports a request handler: `onRequest`, or one of the method variants `onRequestGet`, `onRequestPost`, `onRequestPut`, `onRequestPatch`, `onRequestDelete`, `onRequestHead` and `onRequestOptions`. A helper module with no such export is just code other files can import. ## Static routes | File | URL path | |---|---| | `functions/index.js` | `/` | | `functions/about.js` | `/about` | | `functions/api/index.js` | `/api` | | `functions/api/contact.js` | `/api/contact` | Three rules cover the static case: - **`index.js` serves its folder.** `functions/api/index.js` answers `/api`, not `/api/index`. - **The trailing slash is optional.** `/api/contact` and `/api/contact/` reach the same file. - **A folder index beats a sibling file.** If both `functions/foo.js` and `functions/foo/index.js` exist, `/foo` and `/foo/` run `functions/foo/index.js`. ## Dynamic segments: `[id]` and `[[path]]` Brackets in a filename turn a segment into a parameter, and the value appears on `context.params` under the name inside the brackets. | Filename | Matches | `context.params` for the example | |---|---|---| | `functions/api/users/[id].js` | exactly one segment after `/api/users/` | `/api/users/42` gives `{ id: "42" }` | | `functions/docs/[[path]].js` | any number of segments after `/docs/` | `/docs/a/b/c` gives `{ path: ["a", "b", "c"] }` | The difference in **type** matters in code: a single-bracket parameter is a **string**, a double-bracket parameter is an **array of strings**. Code that calls `.toLowerCase()` on a catch-all value throws. A request for the bare folder (`/docs`) can also reach the catch-all with no `path` key at all, so guard for `undefined`. `/api/users/42/extra` does **not** match `[id].js`, because one bracket pair means exactly one segment. ## Which file wins when several match Wrangler sorts the routes so that the most specific one is tried first: 1. Routes with **more path segments** are tried before routes with fewer. 2. Within the same depth, a **fixed segment** (`me.js`) beats a **parameter** (`[id].js`), which beats a **catch-all** (`[[path]].js`). 3. At the same path, a **method-specific export** (`onRequestGet`) is tried before a generic `onRequest`. So with `functions/api/users/me.js` and `functions/api/users/[id].js` side by side, `GET /api/users/me` runs `me.js`, and `GET /api/users/42` runs `[id].js` with `id` set to `"42"`. The method rule has a consequence worth knowing: a route is skipped when its file has no handler for the request's method, and the request moves on to the next matching route. If `me.js` exports only `onRequestGet`, a `POST /api/users/me` lands in `[id].js` with `id` set to `"me"`. ## When no Function matches If no route matches, the request **falls through to static assets**: the file in the build output is served as if Functions did not exist. If there is no such file, Pages applies its normal not-found behaviour, which for a project without a top-level `404.html` means serving the root `index.html` as a single-page application. A mistyped API path can therefore answer `200` with HTML, which surprises a client expecting JSON. ## Mistakes interviewers listen for - Treating `[[path]]` values as a string, or expecting `[id]` to match nested paths. - Naming a file `functions/api/users/:id.js` in the style of a web framework's router; the bracket syntax is the only parameter syntax. - Exporting a handler under a name the router does not recognise, such as `onPost` or `onRequestPOST`; the file then never runs. - Expecting a `404` from Functions when nothing matches, when the asset server decides the response. ## Seeing the route table Routing is decided at build time from the file tree, so adding or renaming a file changes the routes only after the next deployment. Two commands show what the tree produces before anything ships: - `wrangler pages dev ./public` serves the build output and runs the Functions together, on `http://localhost:8788` unless `--port` says otherwise, so a `curl` against each path shows which file answers. - `wrangler pages functions build --outdir ./out --output-routes-path ./routes.json` compiles the directory into one Worker and writes the include rules Wrangler derived from the tree. Which requests reach the Functions Worker at all is a separate question, answered by the project's `_routes.json` file.

  • Both functions/foo.js and functions/foo/index.js exist in a Pages project. Which one answers /foo/?
    `functions/foo/index.js` answers both `/foo` and `/foo/`. The trailing slash is optional in Pages Functions routing, and when a folder index and a same-named sibling file both exist, the folder's `index.js` wins. Keeping only one of the two avoids the confusion.
  • A Pages project has functions/api/users/me.js exporting only onRequestGet, next to functions/api/users/[id].js exporting onRequest. What runs for POST /api/users/me?
    `[id].js` runs, with `context.params.id` set to `"me"`. The router skips a route whose file has no handler for the request method and moves to the next matching route, here the parameter route. Exporting an `onRequest` fallback in `me.js`, for example one that returns `405`, keeps such requests out of the parameter route.
  • Where do you read the matched segments, and what type are they?
    On `context.params`, keyed by the name in the brackets. A single-bracket file such as `[id].js` gives a string; a double-bracket file such as `[[path]].js` gives an array of strings, one per segment, which can be absent for the bare folder path.

  • A [id].js file also matches /api/users/42/extra and nested paths.
  • A [[path]] catch-all parameter arrives as one slash-joined string.
  • Pages Functions parameters are declared with :id in the filename.
  • When no Function matches, Pages Functions always returns a 404.
  • functions/api/index.js serves the URL /api/index.
open as a page

Why did adding functions/_middleware.js to a Cloudflare Pages site make every image and stylesheet request invoke Functions, and how does _routes.json fix it?

level: seniorimportance: must knowfreq 25%

basics

~20 s

Wrangler generates _routes.json from the functions/ tree, and a root _middleware.js makes it include /*, so every request invokes the Functions Worker. Scope the middleware to a folder such as functions/api/, or ship a custom _routes.json whose exclude list covers static paths.

open as a page

When a Cloudflare Pages project's build output contains a _worker.js file, what happens to its functions/ directory, and what must that Worker do?

level: middleimportance: should knowfreq 22%

basics

~20 s

A _worker.js in the build output switches the Pages project to advanced mode: the functions/ directory, its routing and its middleware are ignored. The file is a module Worker that receives every request and must call env.ASSETS.fetch() to serve static files.

open as a page

In Cloudflare Pages Functions, how do onRequest and method exports like onRequestPost decide which handler runs, and what does the context argument carry?

level: middleimportance: should knowfreq 28%

basics

~20 s

A 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.

open as a page

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?

level: middleimportance: should knowfreq 30%

basics

~20 s

A _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.

open as a page

Why might context.env.MESSAGES still be undefined in a Cloudflare Pages Function after a KV binding named MESSAGES was added in the dashboard?

level: seniorimportance: should knowfreq 25%

basics

~20 s

Pages attaches bindings when a deployment is created, so the project needs a redeploy after a dashboard change. Preview and production keep separate bindings, a Wrangler file with pages_build_output_dir replaces dashboard settings, and wrangler pages dev reads only the Wrangler file or flags.

open as a page