Skip to content
AnswerWell geo Documentation

Research · 7 min read · Answerwell

Static Site Serverless Functions: Forms, Routing, and Middleware

How Cloudflare Pages Functions handle form POSTs, file-based routes, middleware, advanced _worker.js mode, and deployment limits versus Formspree.

This page summarises Cloudflare documentation on Pages Functions: server-side handlers that run on the same project as your static site, with emphasis on form submissions, routing, and middleware. The same platform also documents hosted form backends (for example Formspree) when you do not want to write server code.

Pages Functions: what they are and when you need them

Section titled “Pages Functions: what they are and when you need them”

Pages Functions are serverless handlers colocated with a Pages project; they run on the Cloudflare Workers runtime and add dynamic behaviour without a dedicated server.

Pages Functions allows you to build full-stack applications by executing code on the Cloudflare network with Cloudflare Workers. With Functions, you can introduce application aspects such as authenticating, handling form submissions, or working with middleware.

— Cloudflare, Functions

Use them when the browser must talk to your logic on the same origin (for example POST to /api/submit), when you need middleware (auth, logging) around those routes, or when you want bindings (KV, D1, secrets) next to static assets. Use a third-party form service when you only need email notifications and storage and prefer not to maintain handlers—see the comparison below.

Approach Server code Typical action / client target Best when
HTML form with Formspree None on Pages https://formspree.io/f/{id} Contact forms, notifications, plugins (Sheets, Slack)
React form with Formspree Front end only (@formspree/react) Formspree form ID in useForm SPA forms without a custom API
HTML form + Pages Function functions/api/submit.js /api/submit on your site Parsing FormData, custom responses, your datastore
Standalone Worker (e.g. Airtable tutorial) Separate workers.dev URL Full Worker URL + path Backend shared across apps; refactor to Pages later (guide)

Formspree on Pages: endpoint without Functions

Section titled “Formspree on Pages: endpoint without Functions”

For plain HTML on Pages, the form’s action must point at a Formspree endpoint, not /, or submissions hit a URL with no handler.

The HTML form is complete, however, when the user submits this form, the data will be sent in a POST request to the / URL. No server exists to process the data at that URL, so it will cause an error. To fix that, create a new Formspree form, and copy its unique URL into the form’s action.

— Cloudflare, Add an HTML form with Formspree

Example pattern from the same tutorial:

<form method="POST" action="https://formspree.io/f/mqldaqwx">

For React, Cloudflare documents @formspree/react and useForm("YOUR_FORM_ID") in Add a React form with Formspree. To separate test and production submissions, use environment variables in the Pages project (for Create React App, REACT_APP_FORM_ID in Production vs Preview)—described in that tutorial’s environment-variables section.

Static HTML deployment settings called out there: framework preset None, build output directory public, after pushing to Git.

File-based routing: how a URL picks a Function

Section titled “File-based routing: how a URL picks a Function”

File-based routing maps files under /functions at the project root (not inside the static build folder alone) to HTTP paths.

Functions utilize file-based routing. Your /functions directory structure determines the designated routes that your Functions will run on.

— Cloudflare, Routing

File Route
/functions/helloworld.js /helloworld
/functions/api/submit.js /api/submit
/functions/users/[user].js /users/:user one segment
/functions/users/[[catchall]].js multiple trailing segments

If no Function matches, traffic falls back to a static asset when one exists (Routing). Trailing slashes are optional; a file foo.js and foo/index.js interact as documented on that page.

Dynamic segments appear on context.params:

Holds the values from dynamic routing.

— Cloudflare, API reference

For a file /users/[user].js, a request to /users/nevi yields context.params.user as a string; double-bracket catch-alls return arrays (Routing).

You can limit which paths invoke Functions with _routes.json in the build output (include / exclude; exclude wins)—see Routing.

onRequest handlers: POST forms, verbs, and JSON APIs

Section titled “onRequest handlers: POST forms, verbs, and JSON APIs”

Pages Functions export named handlers instead of a top-level fetch listener. The API reference states that a more specific verb export overrides the generic one—for example onRequestGet wins over onRequest for GET requests.

Common exports:

  • onRequest — all methods, if no verb-specific handler exists
  • onRequestPost — HTML form method="POST"
  • onRequestGet — JSON read APIs (blog API tutorial)

Each handler receives a context with at least request, env, params, and next (API reference). Handlers must return a Response or a Promise of one (Get started).

The Create a HTML form tutorial posts to /api/submit via:

<form method="POST" action="/api/submit">

The matching handler lives at functions/api/submit.js as onRequestPost. Default form encoding is application/x-www-form-urlencoded; multipart forms use enctype="multipart/form-data". Both parse with context.request.formData().

Checkbox groups with repeated names break a naive Object.fromEntries on FormData; the tutorial’s final handler loops entries and merges duplicate keys into arrays—see the Worker section of Create a HTML form.

Build an API for your front end using Pages Functions places functions/api/posts.js (onRequestGet returning Response.json(posts)) and functions/api/post/[[id]].js for /api/post/:id. That pattern suits client-rendered sites that fetch JSON from the same hostname.

Middleware: logic before the form or API handler

Section titled “Middleware: logic before the form or API handler”

Middleware runs before route handlers and is defined in _middleware.js under /functions.

Middleware is reusable logic that can be run before your onRequest function. Middlewares are typically utility functions. Error handling, user authentication, and logging are typical candidates for middleware within an application.

— Cloudflare, Middleware

functions/_middleware.js can cover the whole app, including in front of static files (Middleware). Middleware uses context.next() to continue the chain; you may export an array of functions to chain error handling and auth (Middleware).

When refactoring a standalone Worker that checked request.method, verb-specific exports (onRequestPost) often remove the need for manual method guards (Refactor a Worker to a Pages Function).

Advanced mode: single _worker.js instead of /functions

Section titled “Advanced mode: single _worker.js instead of /functions”

Advanced mode replaces the entire /functions tree with one Module Worker file in the build output directory:

Advanced mode allows you to develop your Pages Functions with a _worker.js file rather than the /functions directory.

— Cloudflare, Advanced mode

When using a _worker.js file, the entire /functions directory is ignored, including its routing and middleware characteristics.

— Cloudflare, Advanced mode

The Function must handle every request: custom paths (for example /api/*) and, for static hosting, forward everything else to assets:

In advanced mode, your Function will assume full control of all incoming HTTP requests to your domain. Your Function is required to make or forward requests to your project’s static assets. Failure to do so will result in broken or unwanted behavior.

— Cloudflare, Advanced mode

Typical pattern: return env.ASSETS.fetch(request) when not handling API logic. Cloudflare ships only _worker.js, not _worker.ts—compile TypeScript yourself (Advanced mode).

Configuration, environments, and operations

Section titled “Configuration, environments, and operations”

Optional Wrangler configuration can become the source of truth for Pages Functions settings (bindings, pages_build_output_dir, compatibility flags). That requires the V2 build system and differs from Workers config in several fields (Wrangler configuration).

Runtime flags (Node compatibility, compatibility date) are set in the dashboard under Settings > Functions > Compatibility Flags or via Wrangler (Get started). Secrets and bindings (D1, R2, KV) attach to the same env object handlers use (Get started).

On the Workers Free plan, Fail open / closed controls whether exhausted daily Function quota still serves static assets or returns an error—relevant if middleware performs auth on every request (Routing).

Pages Functions changelog entry notes GA status, metrics, billing, secrets, and wrangler pages deployment tail for log tailing.

ES module import/export is the recommended style; shared logic can live in separate modules imported from Function files (Module support).

  1. functions/ in the wrong place — It must sit at the Pages project root, not only inside public or dist (Get started).
  2. action="/" on static HTML — Without Formspree or a Function route, POST goes nowhere (Add an HTML form with Formspree).
  3. Expecting dashboard Direct Upload to pick up /functions — Use Git or Wrangler (Direct Upload).
  4. Advanced mode without ASSETS.fetch — Custom Worker runs but static files 404 (Advanced mode).
  5. Assuming _middleware.js runs in advanced mode — The /functions directory, including middleware, is ignored when _worker.js is used (Advanced mode).
  6. Multi-value checkboxes with Object.fromEntries — Later values overwrite earlier ones; use explicit merging (Create a HTML form).
  1. Confirm the project layout: functions/ at the repository root and static assets in the configured build output (for example public), matching Create a HTML form or your framework’s build directory from Routing.
  2. Deploy via Git or Wrangler (not dashboard-only Direct Upload if you rely on a functions/ folder) and open the live *.pages.dev URL from the deployment summary (Add an HTML form with Formspree).
  3. Submit a test form or POST to your API route; for the HTML Forms tutorial, expect JSON echo of parsed fields from /api/submit (Create a HTML form).
  4. If something fails at runtime, use dashboard or Wrangler log tailing mentioned in Changelog (wrangler pages deployment tail) and review Known issues for advanced-mode exceptions.
  5. You can check automatically in Answerwell (our tool): https://answerwell.org/workspace

If something on this page is wrong or unclear, email yimasynthetic@gmail.com with the page URL and the exact statement you are asking about, and we will correct or clarify it.