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?
answer
- the generated file follows the functions tree
- root middleware means slash star
- exclude wins over include
- custom file replaces the generated one
- 100 rules, 100 characters
basics
~20 sWrangler 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.
solid answer
~40 sOnce a Pages project has Functions, the `_routes.json` file decides which requests invoke the Functions Worker; requests outside it are free static-asset requests. When the build output has no `_routes.json`, Wrangler generates one from the `functions/` tree, turning each route it finds into an `include` rule such as `/api/contact` or `/docs/*`. A root `functions/_middleware.js` has to see every path, so the generated file becomes `include: ["/*"]`, and every image, stylesheet and page now runs the Worker and counts as a Workers request. The fix is to move the middleware to the folder that needs it, such as `functions/api/`, or to ship a custom `_routes.json` in the build output directory with `exclude` rules for static paths, since `exclude` wins over `include`. Excluded paths skip all middleware, so never exclude a protected path.
code
json · 5 lines{
"version": 1,
"include": ["/*"],
"exclude": ["/assets/*", "/about", "/favicon.ico"]
}go deeper
Recall that _routes.json lists include and exclude patterns that decide which requests run Functions, and that static requests are free.
Explain how Wrangler generates the file from the functions/ tree, why root middleware turns it into /*, and that exclude beats include.
Diagnose the cost jump from the generated file, choose between scoping the middleware and a custom file, and name the traps: excludes bypass auth, new routes are not added for you.
Set the team's rule: middleware scoped to the narrowest folder by default, and any custom _routes.json reviewed whenever a route folder is added, because it fails silently.
## Two kinds of requests on a Pages project A Cloudflare Pages project serves **static assets** from its build output and, if it has a `functions/` directory, runs **Pages Functions**, compiled into one Worker. The two are billed differently: - A **static request**, one that does not invoke Functions, is free and unlimited on every plan. - A **Functions request** is billed as a **Workers request**. On the Workers Free plan it counts toward the 100,000 requests a day shared with the account's Workers, a limit that resets at midnight UTC; on a paid plan it counts toward the Workers quota. Once Functions exist, every request invokes the Worker by default. The file that narrows this is **`_routes.json`**. ## How `_routes.json` decides `_routes.json` sits in the **build output directory** and has three fields: | Field | Meaning | |---|---| | `version` | the schema version, currently `1` | | `include` | path patterns that invoke Functions; at least one is required | | `exclude` | path patterns that never invoke Functions; **exclude wins over include** | A `*` matches any number of path segments, so `/assets/*` covers `/assets/img/logo.png`. A request that matches `include` and no `exclude` rule invokes the Worker, **even if it ends up serving a static file** through `context.next()`. Every other request goes straight to the asset server. ## Why the root middleware widened it When the build output has no `_routes.json`, Wrangler **generates one** from the `functions/` tree at deploy time. A project with `functions/api/contact.js` and `functions/docs/[[path]].js` gets `include: ["/api/contact", "/docs/*"]`, so the homepage and its assets stay static. A middleware file needs a rule covering its whole folder: `functions/api/_middleware.js` turns the first rule into `/api/*`, and `functions/_middleware.js` adds `/*`, after which consolidation leaves just `include: ["/*"]`. From that deployment on, every request, logo and stylesheet included, runs the Worker. The symptoms: 1. The Workers request count jumps to roughly the site's total traffic. 2. On the Free plan the daily allowance runs out early. What happens next depends on the project's **Fail open / closed** setting under **Settings > Runtime**: fail open keeps serving static assets without running Functions, fail closed returns an error page. 3. Nothing else looks wrong, because every response is still correct. ## The fixes, in order of preference 1. **Scope the middleware.** If the middleware exists for the API, move it to `functions/api/_middleware.js`. The generated file returns to `/api/*` and static paths stop invoking Functions. 2. **Ship a custom `_routes.json`.** If the middleware must stay at the root, for example to add a header to pages, place a `_routes.json` in the build output with `include: ["/*"]` and `exclude` rules for the static trees, as in the example. A custom file **replaces** the generated one entirely. ## Rules Wrangler enforces `wrangler pages dev` and deploys validate a custom file and refuse an invalid one: - at least one `include` rule (`Routes must have at least 1 include rule`); - at most **100** `include` and `exclude` rules combined; - each rule at most **100** characters; - every rule starts with `/`; - no splat rule overlapping another rule in the same list, such as `/api/*` beside `/api/contact`. When a generated file would pass 100 rules, Wrangler collapses it to `/*`. ## Checking the rules before and after a deploy - `wrangler pages functions build --output-routes-path ./routes.json` writes the file Wrangler would generate, so a reviewer can see `/*` appear the moment a root middleware is added. - A deploy that picks up a custom file logs `Uploading _routes.json`; a deploy without one uploads the generated rules instead. - The project's request metrics show the effect: once static paths are excluded, Functions requests drop back to roughly the API traffic. ## The traps of a hand-written file - **Excludes bypass middleware.** An excluded path never invokes Functions, so no `_middleware.js` runs for it. Excluding a path that auth middleware protects serves it unprotected. - **New routes are not added for you.** With a custom file, a route file added later outside its `include` rules never runs; the request falls through to static assets, often as the single-page app's `index.html` with status `200`. Review `_routes.json` with every new route folder. - **Build output, not project root.** The file must sit at the root of the build output directory that Pages deploys; a copy beside `functions/` in the project root is ignored.
- A Pages project ships a custom _routes.json with include ["/api/*"]. A developer adds functions/webhooks/payments.js. What happens to requests for /webhooks/payments?They never reach the new Function. The custom `_routes.json` replaces the generated one, and `/webhooks/payments` matches no `include` rule, so the request goes to the static asset server. Add `/webhooks/*` to `include`, or delete the custom file if the generated rules are enough.
- Why is excluding /api/admin/* from _routes.json dangerous when functions/api/_middleware.js does authentication?An excluded path never invokes the Functions Worker, so no middleware runs for it. Any static file the build output has under `/api/admin/` would then be served to anyone, with no auth check. Excludes belong only on paths that are meant to be public.
- What does a Workers Free plan Pages project do when its daily Functions allowance runs out?It follows the project's Fail open / closed setting. Fail open keeps serving static assets without running Functions, so auth middleware stops running too; fail closed returns an error page instead. Projects that do auth in Functions usually choose fail closed, or upgrade to remove the daily limit.
- A request that falls through to a static file through next() is not billed.
- Include rules win over exclude rules when both match a path.
- A custom _routes.json is merged with the generated one.
- Excluding a path from _routes.json still runs its middleware.
- _routes.json belongs in the project root next to the functions/ folder.