The CodePen embeds in a four-year-old article on headless form submission with the WordPress REST API stopped working after the WordPress site backing them failed to survive a forced infrastructure migration, and access to the account was lost. The pens existed to show how the REST API endpoints of common WordPress form plugins can capture and display validation errors and submission feedback in a fully custom front-end. The failure raises a broader question for anyone publishing educational demos: if the dependency had been a third-party service that couldn't be self-hosted or fixed, is there a way to build demos that survive it?
Test authors have faced the same problem for years. Third-party dependencies sit outside the bounds of control, so the most reliable fix is to remove the external service from the equation entirely. The techniques used to do that in tests carry over to demos.
Two ways to decouple a REST API dependency
- Mock the HTTP calls in code, returning stubbed responses instead of performing real network requests.
- Stand up a mock API server that serves predefined responses in place of the real service.
Both carry trade-offs, and the CodePen demos serve as the running example.
Intercepting fetch in the browser
Testing frameworks such as Jest and Playwright ship with mocking built in, but they aren't available inside a pen. The alternative is to monkey patch the Fetch API: overwrite an existing function to add behavior when the original source can't be changed. The replacement, fetchWPFormsRestApiInterceptor, adds custom logic for specific conditions and lets everything else pass through untouched.
const fetchWPFormsRestApiInterceptor = (fetch) => async (
resource,
options = {}
) => {
// To make sure we are dealing with the data we expect
if (typeof resource !== "string" || !(options.body instanceof FormData)) {
return fetch(resource, options);
}
if (resource.match(/wp-json\/contact-form-7/)) {
return contactForm7Response(options.body);
}
if (resource.match(/wp-json\/gf/)) {
return gravityFormsResponse(options.body);
}
return fetch(resource, options);
};
window.fetch = fetchWPFormsRestApiInterceptor(window.fetch);
That replacement is an interceptor — a pattern that modifies requests or responses under given conditions. Libraries like axios expose interceptors directly rather than requiring monkey patching, which is worth using sparingly, since stacked overrides easily introduce subtle bugs or conflicts.
Returning a fake response is then a matter of calling the static JSON method on the Response object:
const contactForm7Response = (formData) => {
const body = {}
return Response.json(body);
};
The body can be anything from plain text to a Blob or ArrayBuffer, and custom status codes and extra headers are also possible. For the demo, the response is assembled like this:
const contactForm7Response = (formData) => {
const submissionSuccess = {
into: "#",
status: "mail_sent",
message: "Thank you for your message. It has been sent.!",
posted_data_hash: "d52f9f9de995287195409fe6dcde0c50"
};
const submissionValidationFailed = {
into: "#",
status: "validation_failed",
message:
"One or more fields have an error. Please check and try again.",
posted_data_hash: "",
invalid_fields: []
};
if (!formData.get("somebodys-name")) {
submissionValidationFailed.invalid_fields.push({
into: "span.wpcf7-form-control-wrap.somebodys-name",
message: "This field is required.",
idref: null,
error_id: "-ve-somebodys-name"
});
}
// Or a more thorough way to check the validity of an email address
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.get("any-email"))) {
submissionValidationFailed.invalid_fields.push({
into: "span.wpcf7-form-control-wrap.any-email",
message: "The email address entered is invalid.",
idref: null,
error_id: "-ve-any-email"
});
}
// The rest of the validations...
const body = !submissionValidationFailed.invalid_fields.length
? submissionSuccess
: submissionValidationFailed;
return Response.json(body);
};
From that point on, any fetch call to a URL matching wp-json/contact-form-7 gets back the faked success or validation errors, depending on what was submitted.
A mocked API server on serverless
A traditionally hosted mock server brings back the same availability, maintenance and cost concerns as the original dependency. Serverless functions sidestep them; DigitalOcean Functions, for instance, has a free tier generous enough that a mocked API costs practically nothing and takes no more effort than mocking in code.
Simple cases can be built entirely in the Functions control panel, including the built-in code editor. More complex ones can be developed locally and deployed with doctl, DigitalOcean's CLI. Giving each endpoint its own Function avoids unnecessary conditions inside the handler. JavaScript (Node.js) is supported, so the base used for contactForm7Response carries over nearly unchanged:
function main(event) {
const body = {};
return { body };
}
The handler must be named main; it receives the event object describing the request as its first argument. Returning the JSON response is a matter of returning an object. The response-building code is reusable as-is; the one addition is extracting the submitted form data from event as FormData:
function main(event) {
// How do we get the FormData from the event?
const formData = new FormData();
const submissionSuccess = {
// ...
};
const submissionValidationFailed = {
// ...
};
if (!formData.get("somebodys-name")) {
submissionValidationFailed.invalid_fields.push({
// ...
});
}
// Or a more thorough way to check the validity of an email address
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.get("any-email"))) {
submissionValidationFailed.invalid_fields.push({
// ...
});
}
// The rest of the validations...
const body = !submissionValidationFailed.invalid_fields.length
? submissionSuccess
: submissionValidationFailed;
return { body };
}
Serverless functions generally expect JSON input, so other data types need an extra parsing step — and the demos' forms submit as multipart/form-data. Without libraries, the Response API can convert a multipart/form-data string into a FormData:
async function convertMultipartFormDataToFormData(data) {
const matches = data.match(/^\s*--(\S+)/);
if (!matches) {
return new FormData();
}
const boundary = matches[1];
return new Response(data, {
headers: {
"Content-Type": `multipart/form-data; boundary=${boundary}`
}
}).formData();
}
Most of that code exists to pull out the boundary variable, which is typically autogenerated, for example when a browser submits a form. The raw submitted data arrives in event.http.body, base64-encoded, so it must be decoded first:
async function main(event) {
const formData = await convertMultipartFormDataToFormData(
Buffer.from(event?.http?.body ?? "", "base64").toString("utf8")
);
// ...
const body = !submissionValidationFailed.invalid_fields.length
? submissionSuccess
: submissionValidationFailed;
return { body };
}
After that, only the calls to the original APIs need to be pointed at the mocked endpoints.
Choosing between the approaches
Both decouple the demo from the third-party API, and for this example the effort involved looks comparable. Manual mocking has the advantage of no external dependency at all — nothing outside the demo's own bundle — which makes it a reasonable default for small, self-contained demos. A mocked server, by contrast, can serve tests as well as demos; teams with more complex needs may want a mocked server in a language other than JavaScript, or an existing tool such as WireMock rather than a from-scratch implementation.
None of this needs to be applied by default. The CodePen demos ran for four years without incident. What matters is monitoring, so failures are noticed when they happen, and the tools on hand to respond.



