Next.js
This setup uses the Next.js App Router. A Server Component fetches the form, a small Client Component connects it and a route handler adds the API key.
It works without the drop-in embed, so the key never reaches the browser.
Files
Finish the WordPress setup. You’ll create these files:
app/contact/page.tsx: the page.app/contact/CoreForm.tsx: the Client Component.public/core-forms-client.js: the submit script.lib/core-forms-proxy.ts: the proxy logic.app/api/submit/route.ts: the route handler.
The paths assume app and lib are in the project root.
Create the Page
// app/contact/page.tsx
import CoreForm from './CoreForm';
async function getFormHtml(): Promise<string> {
const base = process.env.CORE_FORMS_UPSTREAM;
const id = process.env.CORE_FORMS_FORM_ID;
try {
const response = await fetch(`${base}/forms/${id}`, { next: { revalidate: 300 } });
if (response.ok) return (await response.json()).html ?? '';
console.error(`Core Forms returned ${response.status}.`);
} catch (error) {
console.error('Core Forms could not be reached.', error);
}
return '';
}
export default async function ContactPage() {
const html = await getFormHtml();
return (
<main>
<h1>Contact us</h1>
{html ? (
<CoreForm html={html} />
) : (
<p>
The form is unavailable. Email{' '}
<a href="mailto:support@example.com">support@example.com</a>.
</p>
)}
</main>
);
}
The page refreshes the form every 5 minutes. Use cache: 'no-store' in place of the next option to fetch it on every request.
Create the Client Component
// app/contact/CoreForm.tsx
'use client';
import Script from 'next/script';
import { useCallback, useEffect, useMemo, useRef } from 'react';
declare global {
interface Window {
CoreFormsClient?: { bind(host: HTMLElement | null): void };
}
}
export default function CoreForm({ html }: { html: string }) {
const host = useRef<HTMLDivElement>(null);
const markup = useMemo(() => ({ __html: html }), [html]);
const bind = useCallback(() => window.CoreFormsClient?.bind(host.current), []);
useEffect(() => {
bind();
}, [bind, html]);
return (
<>
<div ref={host} data-submit-url="/api/submit" dangerouslySetInnerHTML={markup} />
<Script src="/core-forms-client.js" onReady={bind} />
</>
);
}
The memoized markup stops React from replacing the form while the visitor types. Only render HTML from a WordPress site you control.
Create the Proxy
Save this as 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 Route Handler
// app/api/submit/route.ts
import { submitToCoreForms } from '../../../lib/core-forms-proxy';
export async function POST(request: Request) {
return submitToCoreForms(request, {
upstream: process.env.CORE_FORMS_UPSTREAM,
formId: process.env.CORE_FORMS_FORM_ID,
apiKey: process.env.CORE_FORMS_API_KEY,
allowedOrigins: process.env.CORE_FORMS_ALLOWED_ORIGINS,
});
}
Set the Environment
Add these to .env.local and to your hosting provider:
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:3000 to the allowed origins. Never give the key a NEXT_PUBLIC_ prefix.
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.
- Load the captcha script in your layout with
next/script. - Add CSS for the form. The embed guide has a starting point.
- Send a test entry and confirm that the Network panel shows no API key.