Skip to content

Pages Functions: add server-side routes to a Pages project

Use the functions/ directory to turn a static Pages site into one with dynamic API routes. File-based routing, bindings to KV/R2/D1, mixing static and dynamic, and tailing live logs with wrangler.

A team has a Pages-hosted static site working in production and now wants to add a handful of server-side routes — a contact-form endpoint, a /api/og image generator, a webhook receiver, an authenticated API that reads from D1. They do not want to spin up a separate Workers project, copy custom-domain plumbing, or pay for a second build pipeline. Pages Functions exists for exactly this shape of work: a functions/ directory inside the same Pages project, file-based routes, the same bindings system as standalone Workers, and the same wrangler pages deployment tail you’d use to debug a Worker.

How to verify

If the project already exists on Pages, confirm Functions is wired correctly by adding one route and tailing it. A live request hitting the function shows up in the tail within a second.

# 1. Add a function locally
mkdir -p functions/api
cat > functions/api/health.ts <<'EOF'
export const onRequestGet: PagesFunction = async () => {
  return new Response(JSON.stringify({ ok: true, ts: Date.now() }), {
    headers: { 'content-type': 'application/json' }
  });
};
EOF

# 2. Commit, push, wait for the deploy to finish
git add functions/ && git commit -m "add health route" && git push

# 3. Tail the production deployment and hit the route
npx wrangler pages deployment tail --project-name=my-site &
curl https://my-site.pages.dev/api/health

The tail line should show the GET to /api/health with a 200. If the request 404s at the edge, the function file is in the wrong place — functions/ must sit at the repo root (or at the configured root directory in a monorepo), not under src/, not under dist/.

What’s happening

A Pages project with a functions/ directory at the root becomes a hybrid: the static assets from the build output directory still ship to the edge as files, but the file tree under functions/ is compiled into a single Worker that handles every request matching its routes. The router runs first — if a request path matches a function file, the function runs; otherwise the static asset is served. There is no priority configuration to memorize, the rule is “function wins if it matches”.

File names are the route. functions/api/hello.ts exports onRequestGet/onRequestPost/etc. and serves /api/hello. Square brackets in filenames are dynamic segments: functions/api/[slug].ts matches /api/anything. Double brackets are catch-alls: functions/api/[[path]].ts matches /api/a/b/c. _middleware.ts files run on every request beneath their directory and let you compose auth, logging, CORS, and so on without repeating yourself.

Bindings — KV namespaces, R2 buckets, D1 databases, Queues, environment variables, secrets — are attached in the Pages dashboard or the project’s wrangler.toml. The runtime injects them into the context.env argument of every function. The same Worker-style context.env.MY_KV.get('key') and context.env.DB.prepare(...).all() calls work here verbatim. Production and Preview have separate binding scopes, so a preview deployment can talk to a staging D1 while production talks to the real one.

Pages request routingRequestGET /api/users/42match?functions/yesno — staticFunctionfunctions/api/[id].tsonRequestGetStatic asset/index.html, /img.pngcontext.envbindings injectedat runtimeKV / R2D1QueuesSame project, same domain, same deploy — functions and static assets share everything
If a request matches a file under functions/, the function runs with bindings injected; otherwise the static asset wins.

The procedure

1. Add the functions/ directory

The directory must be at the repo root (or at the root directory configured for the Pages project). Inside, the path-to-file convention is the entire router:

my-site/
  functions/
    _middleware.ts          # runs on every /* request
    api/
      health.ts             # GET /api/health
      users/
        [id].ts             # GET /api/users/42, /api/users/anything
      webhooks/
        [[path]].ts         # GET /api/webhooks/a, /api/webhooks/a/b/c
    sitemap.xml.ts          # GET /sitemap.xml (replaces a static file)
  dist/                     # static build output (unchanged)

Functions are TypeScript or JavaScript. The exports are HTTP-method-specific: onRequestGet, onRequestPost, onRequestPut, onRequestDelete, plus a catch-all onRequest. Returning a Response is the contract.

2. Wire bindings

Bindings are how a function reaches anything beyond pure compute. There are two ways to declare them: the Pages dashboard (Settings → Functions → Bindings) for ad-hoc setup, or a wrangler.toml at the project root for repo-tracked configuration. The wrangler.toml form, which is what most teams converge on:

name = "my-site"
compatibility_date = "2026-05-01"

[[kv_namespaces]]
binding = "SESSIONS"
id = "abc123def456..."

[[r2_buckets]]
binding = "UPLOADS"
bucket_name = "my-site-uploads"

[[d1_databases]]
binding = "DB"
database_name = "my-site-prod"
database_id = "00000000-1111-2222-3333-444444444444"

[vars]
PUBLIC_API_URL = "https://api.example.com"

# Secrets are NOT in wrangler.toml — set them via:
#   wrangler pages secret put STRIPE_KEY --project-name=my-site

Once deployed, context.env.SESSIONS, context.env.UPLOADS, context.env.DB are available in every function. The shape of the file is identical to a standalone Workers project, which means moving a function between Pages and a Worker is mostly file relocation.

3. Write a function with a binding

A representative handler — list users from D1, paginated:

// functions/api/users/index.ts
interface Env {
  DB: D1Database;
}

export const onRequestGet: PagesFunction<Env> = async ({ request, env }) => {
  const url = new URL(request.url);
  const limit = Math.min(parseInt(url.searchParams.get('limit') ?? '20'), 100);
  const offset = parseInt(url.searchParams.get('offset') ?? '0');

  const result = await env.DB
    .prepare('SELECT id, email, created_at FROM users ORDER BY id LIMIT ? OFFSET ?')
    .bind(limit, offset)
    .all();

  return Response.json({ users: result.results, count: result.results.length });
};

The PagesFunction<Env> generic gives the binding types to the IDE. The handler is plain Web Fetch API — request, Response, URL, no Node compat needed for this shape. For Node APIs (Buffer, crypto, streams) add compatibility_flags = ["nodejs_compat"] to wrangler.toml.

4. Add a middleware

_middleware.ts files run on every request beneath their directory. The most common use is auth — reject requests without a valid header before the route handler ever sees them.

// functions/api/_middleware.ts
export const onRequest: PagesFunction = async ({ request, next }) => {
  const auth = request.headers.get('authorization');
  if (!auth?.startsWith('Bearer ')) {
    return new Response('Unauthorized', { status: 401 });
  }
  // Validate token against KV, JWT, etc., then:
  return next();
};

Middleware composes: a functions/_middleware.ts runs first, then functions/api/_middleware.ts, then the route handler. Return next() to pass through, return a Response to short-circuit.

5. Develop locally with wrangler pages dev

The local dev loop matches the production runtime closely enough to catch most bugs before deploy:

# Build the static assets, then run the dev server pointing at them + functions/
npm run build
npx wrangler pages dev ./dist --compatibility-date=2026-05-01

# To run with real bindings (KV/R2/D1) instead of local mocks:
npx wrangler pages dev ./dist --kv=SESSIONS --r2=UPLOADS --d1=DB

Without flags, bindings are local in-memory mocks (KV is a Map, D1 is a SQLite file). With --kv/--r2/--d1 plus --remote, the local process talks to the real Cloudflare resources — useful for reproducing production data shape, dangerous if you write to prod.

6. Tail production logs

Once deployed, wrangler pages deployment tail streams the function logs. This is the equivalent of kubectl logs -f for Pages Functions:

# Tail the latest production deployment
npx wrangler pages deployment tail --project-name=my-site

# Filter to a specific status code or method
npx wrangler pages deployment tail --project-name=my-site --status=error
npx wrangler pages deployment tail --project-name=my-site --method=POST

Console output from console.log inside the function shows up in the tail. For permanent log storage, configure a Logpush job to push to R2 or an external endpoint.

Common pitfalls

  • functions/ in the wrong place — placing it under src/ or dist/ makes Pages serve the file as a static asset. It must be at the project root (or the configured root directory).
  • Build output overlap — a static file at dist/api/health.json and a function at functions/api/health.ts are a conflict. Functions take precedence, but mixing them on the same path causes confusion at review time. Keep API paths out of the static build.
  • Bindings missing in Preview — bindings are scoped per environment. A function that works on production but 500s on a PR preview usually means the Preview scope of wrangler.toml doesn’t have the same kv_namespaces/d1_databases entries.
  • Secret committed by mistake — putting an API key in [vars] in wrangler.toml makes it readable to anyone with repo access. Use wrangler pages secret put instead; secrets never appear in the file.
  • Cold start expectations — Pages Functions run on the Workers runtime, so cold starts are sub-5ms — but if a function does a large DB roundtrip, that’s the latency the user sees. Profile with console.time and the tail to confirm.

For teams running Pages Functions alongside Workers, R2, and D1, Stack Harbor handles the bindings hygiene, secret rotation, log routing, and the deploy-gate test pass that catches a function regression before it reaches production — see how we operate managed operations for clients on the Cloudflare stack. For the connect-the-repo flow that puts a Pages project on the air in the first place, see the Pages-from-Git article.