Skip to content
Gaurav TiwariDocs

Node.js and Express

Version 5.2.5 Updated November 22, 2026

A single Express file can serve your form and forward submissions to Core Forms. The key stays in the server’s environment.

You need Node.js 18 or newer for the built-in fetch. Express is the only dependency.

Install Express

Finish the WordPress setup, then run:

npm install express

Create the Server

// server.cjs
const express = require('express');

const {
  CORE_FORMS_UPSTREAM: upstream,
  CORE_FORMS_FORM_ID: formId,
  CORE_FORMS_API_KEY: apiKey,
  CORE_FORMS_ALLOWED_ORIGINS: allowedOrigins = '',
  PORT = 3000,
} = process.env;

const origins = allowedOrigins.split(',').map((item) => item.trim()).filter(Boolean);
const app = express();

app.use(express.json({ limit: '16kb' }));
app.use(express.urlencoded({ limit: '16kb', extended: false }));
app.use(express.static('public'));

app.post('/api/submit', async (req, res) => {
  res.set('Cache-Control', 'no-store');
  if (!upstream || !formId || !apiKey || !origins.length) {
    return res.status(503).json({ message: 'The form proxy is not configured.' });
  }
  if (!origins.includes(req.get('origin') || '')) {
    return res.status(403).json({ message: 'This origin is not allowed.' });
  }

  const userAgent = req.get('user-agent') || '';
  if (!/mozilla|safari|chrome|firefox/i.test(userAgent)) {
    return res.status(403).json({ message: 'Submission blocked.' });
  }
  if (!req.body || typeof req.body !== 'object' || Array.isArray(req.body)) {
    return res.status(400).json({ message: 'Send the fields as a JSON object.' });
  }

  const isPlain = (value) => value === null || typeof value !== 'object';
  for (const value of Object.values(req.body)) {
    if (!(Array.isArray(value) ? value.every(isPlain) : isPlain(value))) {
      return res.status(400).json({ message: 'Send text, numbers or lists only.' });
    }
  }
  // Always submit to the configured form, whatever the browser sent.
  req.body.id = formId;

  try {
    const 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(req.body),
        redirect: 'manual',
        signal: AbortSignal.timeout(15000),
      },
    );
    const result = await response.text();
    if (!(response.headers.get('content-type') || '').includes('application/json')) {
      return res.status(502).json({ message: 'The form server returned an unexpected response.' });
    }
    return res.status(response.status).type('json').send(result);
  } catch {
    return res.status(502).json({ message: 'The form server could not be reached.' });
  }
});

// Body parser errors, such as invalid JSON or a body over the limit.
app.use((error, req, res, next) => {
  if (res.headersSent) return next(error);
  return res.status(error.status || 500).json({ message: 'Could not read the submission.' });
});

app.listen(PORT, () => console.log(`Listening on port ${PORT}`));

The route accepts JSON and URL-encoded form posts, then sends JSON to WordPress.

Add a Page

Use the same field names as the form in WordPress:

<!-- public/index.html -->
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Contact us</title>
</head>
<body>
  <div data-core-form data-submit-url="/api/submit">
    <form class="cf-form" method="post">
      <label for="name">Name</label>
      <input id="name" name="name" autocomplete="name" required>

      <label for="email">Email</label>
      <input id="email" name="email" type="email" autocomplete="email" required>

      <button type="submit">Send</button>
    </form>
  </div>
  <script src="/core-forms-client.js" defer></script>
</body>
</html>

Save the submit script as public/core-forms-client.js.

Start the Server

Put the settings in a .env file outside the public folder:

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

Node.js 20.6 or newer can load that file directly:

node --env-file=.env server.cjs

On older versions, set the variables in your process manager or shell. Add http://localhost:3000 to the allowed origins while you test.

Test the Route

curl -i "https://www.example.com/api/submit" \
  -A "Mozilla/5.0" \
  -H "Origin: https://www.example.com" \
  -H "Content-Type: application/json" \
  --data '{"name":"Ada","email":"ada@example.com"}'

The proxy requires an allowed Origin and a browser-like user agent, so the command sends both. It creates a real entry.

Production Notes

  • Run the server behind HTTPS.
  • Rate limit /api/submit in Express or at your host.
  • Set Express’s trust proxy option before you rate limit by req.ip behind a load balancer.
  • The route forwards text fields. Use the embed or a standalone page for file uploads.
  • To record each visitor’s IP, add the proxy secret.
Share

Was this helpful?

Still stuck? Open a support ticket