Skip to content
Gaurav TiwariDocs

Cloudflare Workers and Pages

Version 5.2.5 Updated November 22, 2026

A small Cloudflare Worker can serve your static site and proxy form submissions on the same domain. The API key is stored as a secret and added on the server.

The same proxy code also works as a Pages Function.

Create the Proxy

Finish the WordPress setup, then save this as src/core-forms-proxy.ts:

// Shared submit handler for any runtime with Request, Response and fetch.
export interface CoreFormsConfig {
  upstream?: string;       // https://cms.example.com/wp-json/core-forms/v1
  formId?: string;         // 123
  apiKey?: string;         // cf_...
  allowedOrigins?: string; // https://www.example.com,https://example.com
}

const MAX_BYTES = 16 * 1024;

function fail(status: number, message: string): Response {
  return new Response(JSON.stringify({ message }), {
    status,
    headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' },
  });
}

export async function submitToCoreForms(
  request: Request,
  config: CoreFormsConfig,
): Promise<Response> {
  if (request.method !== 'POST') return fail(405, 'Method not allowed.');

  const { upstream, formId, apiKey, allowedOrigins } = config;
  if (!upstream || !formId || !apiKey || !allowedOrigins) {
    return fail(503, 'The form proxy is not configured.');
  }

  const origins = allowedOrigins.split(',').map((item) => item.trim()).filter(Boolean);
  if (!origins.includes(request.headers.get('origin') ?? '')) {
    return fail(403, 'This origin is not allowed.');
  }

  // A soft signal that drops the laziest scripts. A captcha does the real work.
  const userAgent = request.headers.get('user-agent') ?? '';
  if (!/mozilla|safari|chrome|firefox/i.test(userAgent)) {
    return fail(403, 'Submission blocked.');
  }

  if (Number(request.headers.get('content-length') ?? 0) > MAX_BYTES) {
    return fail(413, 'Submission too large.');
  }
  const body = await request.arrayBuffer();
  if (body.byteLength > MAX_BYTES) return fail(413, 'Submission too large.');

  const type = request.headers.get('content-type') ?? '';
  let payload: unknown;
  try {
    if (type.includes('application/json')) {
      payload = JSON.parse(new TextDecoder().decode(body));
    } else {
      // Accept text fields from a normal HTML form post as well.
      const form = await new Response(body, { headers: { 'Content-Type': type } }).formData();
      const fields = new Map<string, string | string[]>();
      form.forEach((value, name) => {
        if (typeof value !== 'string') return;
        const previous = fields.get(name);
        fields.set(name, previous === undefined ? value : ([] as string[]).concat(previous, value));
      });
      payload = Object.fromEntries(fields);
    }
  } catch {
    return fail(400, 'Could not read the submission.');
  }
  if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
    return fail(400, 'Send the fields as a JSON object.');
  }

  const isPlain = (value: unknown) => value === null || typeof value !== 'object';
  for (const value of Object.values(payload)) {
    if (!(Array.isArray(value) ? value.every(isPlain) : isPlain(value))) {
      return fail(400, 'Send text, numbers or lists only.');
    }
  }
  // Always submit to the configured form, whatever the browser sent.
  (payload as Record<string, unknown>).id = formId;

  let response: Response;
  let result: string;
  try {
    response = await fetch(
      `${upstream.replace(/\/$/, '')}/forms/${encodeURIComponent(formId)}/submit`,
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          'X-Core-Forms-Key': apiKey,
          'User-Agent': userAgent,
        },
        body: JSON.stringify(payload),
        redirect: 'manual',
        signal: AbortSignal.timeout(15000),
      },
    );
    result = await response.text();
  } catch {
    return fail(502, 'The form server could not be reached.');
  }

  // A redirect, firewall page or PHP error is not a form response.
  if (!(response.headers.get('content-type') ?? '').includes('application/json')) {
    return fail(502, 'The form server returned an unexpected response.');
  }

  return new Response(result, {
    status: response.status,
    headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' },
  });
}

Create the Worker

The Worker handles /api/submit and passes every other request to your static files.

// src/worker.ts
import { submitToCoreForms } from './core-forms-proxy';

interface Env {
  ASSETS: Fetcher;
  CORE_FORMS_API_KEY: string;
  CORE_FORMS_UPSTREAM: string;
  CORE_FORMS_FORM_ID: string;
  CORE_FORMS_ALLOWED_ORIGINS: string;
}

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    if (new URL(request.url).pathname === '/api/submit') {
      return submitToCoreForms(request, {
        upstream: env.CORE_FORMS_UPSTREAM,
        formId: env.CORE_FORMS_FORM_ID,
        apiKey: env.CORE_FORMS_API_KEY,
        allowedOrigins: env.CORE_FORMS_ALLOWED_ORIGINS,
      });
    }
    return env.ASSETS.fetch(request);
  },
};

Configure Wrangler

Save this as wrangler.jsonc and replace the name, URLs, form ID and domains:

{
  "$schema": "node_modules/wrangler/config-schema.json",
  "name": "your-site",
  "main": "src/worker.ts",
  "compatibility_date": "2026-11-01",
  "assets": {
    "directory": "./dist",
    "binding": "ASSETS",
    "html_handling": "auto-trailing-slash",
    "not_found_handling": "404-page",
    "run_worker_first": ["/api/*"]
  },
  // Safe to commit. The API key is stored as a secret instead.
  "vars": {
    "CORE_FORMS_UPSTREAM": "https://cms.example.com/wp-json/core-forms/v1",
    "CORE_FORMS_FORM_ID": "123",
    "CORE_FORMS_ALLOWED_ORIGINS": "https://www.example.com,https://example.com"
  },
  "routes": [
    { "pattern": "example.com", "custom_domain": true },
    { "pattern": "www.example.com", "custom_domain": true }
  ]
}

run_worker_first sends API requests to the Worker before the static file rules run.

Add the Secret and Deploy

Store the key as a secret. Don’t put it under vars.

npx wrangler secret put CORE_FORMS_API_KEY
npx wrangler deploy

For local development, put the key in .dev.vars and keep that file out of Git:

CORE_FORMS_API_KEY=YOUR_SITE_API_KEY

Add your local origin to CORE_FORMS_ALLOWED_ORIGINS while you test.

Use a Pages Function

On Cloudflare Pages, skip worker.ts. Keep the proxy file and create this function:

// functions/api/submit.ts
import { submitToCoreForms } from '../../src/core-forms-proxy';

interface Env {
  CORE_FORMS_API_KEY: string;
  CORE_FORMS_UPSTREAM: string;
  CORE_FORMS_FORM_ID: string;
  CORE_FORMS_ALLOWED_ORIGINS: string;
}

export const onRequestPost: PagesFunction<Env> = ({ request, env }) =>
  submitToCoreForms(request, {
    upstream: env.CORE_FORMS_UPSTREAM,
    formId: env.CORE_FORMS_FORM_ID,
    apiKey: env.CORE_FORMS_API_KEY,
    allowedOrigins: env.CORE_FORMS_ALLOWED_ORIGINS,
  });

Set the 4 environment values in the Pages project, with the API key saved as a secret.

Connect the Form

Put the form’s HTML or your own markup inside a host element. Then load the submit script:

<div data-core-form data-submit-url="/api/submit">
  <!-- Your form -->
</div>
<script src="/core-forms-client.js" defer></script>

Visitor IP Addresses

WordPress records Cloudflare’s IP for a Worker request. To pass the visitor’s IP, save a proxy secret in WordPress, store it as a Worker secret and send both proxy headers. Use cf-connecting-ip as the IP.

The starter forwards text fields. Use the embed or a standalone page for file uploads.

If a firewall protects WordPress, allow the Worker’s requests to /wp-json/core-forms/v1/. A challenge page can’t be solved by a server.

Share

Was this helpful?

Still stuck? Open a support ticket