Cloudflare Pages Functions Fail - Fix /functions Routing & Build
A Cloudflare Pages Function did not run - it returned 404 because the file is not in the functions/ directory or exports the wrong handler, or it failed because a binding it needs is not configured.
What this error means
A request to a Pages Function path returns the static 404 instead of running the function, or the build/deploy reports a functions error. It is deterministic: a misplaced file or wrong export never wires up the route until corrected.
# Request to /api/hello returns the SPA 404 instead of the function
# functions/ directory not detected, or:
[ERROR] Failed to produce a Pages Functions build:
functions/api/hello.ts has no valid export (expected onRequest)Common causes
File location or export is wrong
Pages Functions must live under functions/ with the path mapping the route, and export an onRequest/onRequestGet handler. A file elsewhere, or a default export, does not register a route.
Missing binding for the function
The function uses a KV/D1/R2 binding or env var not configured in the Pages project, so it throws at runtime even though it is routed.
How to fix it
Place the file and export the right handler
Put the function under functions/ matching the URL path and export an onRequest* handler.
// functions/api/hello.ts -> serves /api/hello
export const onRequestGet: PagesFunction = async (context) => {
return new Response("ok");
};Configure the function’s bindings
- Add KV/D1/R2 bindings and env vars in the Pages project settings (Functions → Bindings).
- Reference them via
context.env.<NAME>in the handler. - Test locally with
wrangler pages devto confirm routing and bindings.
How to prevent it
- Keep functions under
functions/with paths mapping to routes andonRequest*exports. - Configure required bindings/env vars in the Pages project.
- Verify routes and bindings with
wrangler pages devbefore deploying.