Skip to content
Gaurav TiwariDocs

Astro

Version 5.2.5 Updated November 22, 2026

This Astro setup fetches the form’s HTML at build time and submits it through an endpoint on your own site. The API key stays on the server.

For a fully static site with no backend, use the short embed version at the end of this page.

Files

Finish the WordPress setup. You’ll create these files:

  • src/pages/contact.astro: the page.
  • public/core-forms-client.js: the submit script.
  • src/lib/core-forms-proxy.ts: the proxy logic.
  • src/pages/api/submit.ts: the endpoint.

Create the Page

Replace the API URL, form ID and fallback email:

---
// src/pages/contact.astro
export const prerender = true;

const FORM_API = 'https://cms.example.com/wp-json/core-forms/v1';
const FORM_ID = '123';
const SUPPORT_EMAIL = 'support@example.com';

let formHtml = '';
try {
  const response = await fetch(`${FORM_API}/forms/${FORM_ID}`);
  if (response.ok) formHtml = (await response.json()).html ?? '';
  else console.error(`Core Forms returned ${response.status}.`);
} catch (error) {
  console.error('Core Forms could not be reached.', error);
}
---
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>Contact us</title>
  </head>
  <body>
    <main>
      <h1>Contact us</h1>
      {formHtml ? (
        <div data-core-form data-submit-url="/api/submit" set:html={formHtml} />
      ) : (
        <p>The form is unavailable. Email <a href={`mailto:${SUPPORT_EMAIL}`}>{SUPPORT_EMAIL}</a>.</p>
      )}
    </main>
    <script is:inline src="/core-forms-client.js" defer></script>
  </body>
</html>

Rebuild the site after you edit the form. To fetch the current form on each request, change prerender to false.

Create the Proxy

Save this as src/lib/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 Endpoint

The endpoint runs on demand, so install the Astro adapter for your host. The rest of the site can stay static.

// src/pages/api/submit.ts
import type { APIRoute } from 'astro';
import { getSecret } from 'astro:env/server';
import { submitToCoreForms } from '../../lib/core-forms-proxy';

export const prerender = false;

export const POST: APIRoute = ({ request }) =>
  submitToCoreForms(request, {
    upstream: getSecret('CORE_FORMS_UPSTREAM'),
    formId: getSecret('CORE_FORMS_FORM_ID'),
    apiKey: getSecret('CORE_FORMS_API_KEY'),
    allowedOrigins: getSecret('CORE_FORMS_ALLOWED_ORIGINS'),
  });

getSecret() reads the values when the request runs, which keeps them out of the build.

Set the Environment

Add these to .env locally and to your host for production:

CORE_FORMS_UPSTREAM=https://cms.example.com/wp-json/core-forms/v1
CORE_FORMS_FORM_ID=123
CORE_FORMS_API_KEY=YOUR_SITE_API_KEY
CORE_FORMS_ALLOWED_ORIGINS=https://www.example.com,https://example.com

For local testing, add http://localhost:4321 to the allowed origins. Never give the key a PUBLIC_ prefix.

Static Site Without a Backend

Paste the embed into a page or component. is:inline tells Astro to leave the external script alone.

<div data-cf-form="contact" data-cf-key={import.meta.env.PUBLIC_CF_KEY}></div>
<script is:inline src="https://cms.example.com/wp-json/core-forms/v1/embed.js" defer></script>

This version makes the key public.

Before Launch

  • The starter forwards text fields. Use the embed or a standalone page for file uploads.
  • To record each visitor’s IP, add the proxy secret.
  • Add the captcha script.
  • Style the HTML with your CSS. The embed guide has a starting point.
  • Send a test entry and check it in Submissions.
Share

Was this helpful?

Still stuck? Open a support ticket