Wiring Sitecore Forms to the Outside World with Webhooks

Woman clicking Submit on an EcoFlow contact form

SitecoreAI Forms doesn’t send email or store submissions on its own. In order to fill that gap, I used webhooks. You can write a small endpoint, point the form at it, and run whatever logic the submission needs.

On a recent SitecoreAI project, the legacy site’s forms used Sitecore Forms submit actions like Save Data and a custom Send Email, and neither one exists in SitecoreAI Forms. To replace Send Email, I built webhook handlers that receive each submission and relays them to SendGrid (though any email provider could work) as a notification email. Each form has its own handler.

In today’s post, we’ll walk through the three part process of setting up a webhook, using a simple Contact form as the running example:

  1. Write the handler logic as a Next.js API route.
  2. Register the webhook in SitecoreAI Forms.
  3. Attach it to a form and test it.

The basics: How a form submission reaches the code

In SitecoreAI Forms, a webhook can be considered the destination for a form’s data.

Each form can have one submission webhook attached to it, and on a form’s submission POSTs the submitted values to its URL. The handler does everything after that.

For a simple Send Email webhook, the flow looks like this:

  1. A user submits a form on the site.
  2. SitecoreAI Forms POSTs the field values to that form’s assigned webhook URL.
  3. The handler checks the webhook’s x-webhook-secret header, then parses and validates the payload (submission data).
  4. The handler builds a SendGrid Mail Send request on the server, so the SendGrid API key never reaches the browser.
  5. SendGrid delivers the notification to the specified “to” inbox, with the submitter set as reply-to, and returns a 200 success message.
    1. a 500-series error is sent instead if the webhook fails to parse, validate or send the data.
  6. Forms runs the form’s submit action: a success message or a redirect.

In this case, the handler lives in the same Next.js head app as the site, as an API route under pages/api/forms/. Hosting it there means no extra service to deploy, and it reads secrets from the same environment variables as the rest of the app.

Step 1: Write the handler

SitecoreAI only accepts a public HTTPS URL, so the endpoint has to be deployed before you can register it. To start, I created the webhook endpoint under pages/api/forms/submit-contact.ts in the head app.

Map field names to friendly keys

Forms identifies each field by an internal name such as first_name or email_address. Map them to the keys your code uses, and keep a second map of the labels the email should show, in form order. This makes the webhook contract explicit, and if an author renames a field there’s only one place to update.

Note that the labels here are what are sent through with the submission data via email, and not the labels on the form itself. You can (and often) should use the same values here for consistency, but it is not required.

const FIELD_NAME_MAP: Record<string, string> = {
first_name: 'firstName',
last_name: 'lastName',
email_address: 'email',
phone_number: 'phone',
company: 'company',
how_can_we_help: 'message',
};
const FIELD_LABELS: Record<string, string> = {
firstName: 'First name',
lastName: 'Last name',
email: 'Email',
phone: 'Phone',
company: 'Company',
message: 'How can we help?',
};

Parse the payload defensively

The payload carries more than field values. Since at this point we’re only concerned with the actual field data, I skipped over the reCAPTCHA token, the domain key and any signature fields.

The handler also accepts two shapes: a flat object keyed by field name, and a { fields: [{ name, value }] } array. Multi-select values arrive as arrays and checkboxes as booleans, so I had to normalize everything to strings:

const EXCLUDED_FIELD_KEYS = new Set(['g-recaptcha-response', 'domain']);
const SIGNATURE_FIELD_PREFIX = 'signature_';
function normalizeFieldValue(value: unknown): string {
if (Array.isArray(value)) return value.map(String).join(', ');
if (typeof value === 'boolean') return value ? 'Yes' : 'No';
return String(value ?? '');
}
function extractFields(body: unknown): Record<string, string> {
if (!body || typeof body !== 'object') return {};
const raw = body as Record<string, unknown>;
const entries: Array<[string, unknown]> = Array.isArray(raw.fields)
? (raw.fields as Array<{ name?: string; value?: unknown }>)
.filter((f) => f?.name)
.map((f) => [f.name as string, f.value])
: Object.entries(raw);
const result: Record<string, string> = {};
for (const [key, value] of entries) {
if (EXCLUDED_FIELD_KEYS.has(key) || key.startsWith(SIGNATURE_FIELD_PREFIX)) continue;
result[FIELD_NAME_MAP[key] || key] = normalizeFieldValue(value);
}
return result;
}

Authenticate, validate, then send

The handler accepts only POST requests, and checks a shared secret header before anything else. I setup the webhook so that it fails with a clear 500 if any environment variable is missing, and rejects submissions that lack required fields.

Then, it builds the email: known fields first in form order, then anything unmapped, with empty values dropped.

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method not allowed.' });
}
const expectedSecret = process.env.CONTACT_FORM_WEBHOOK_SECRET;
if (!expectedSecret || req.headers['x-webhook-secret'] !== expectedSecret) {
return res.status(401).json({ error: 'Unauthorized.' });
}
const apiKey = process.env.SENDGRID_API_KEY;
const fromEmail = process.env.SENDGRID_FROM_EMAIL;
const notificationEmail = process.env.CONTACT_NOTIFICATION_EMAIL;
if (!apiKey || !fromEmail || !notificationEmail) {
console.error('Contact form: SendGrid environment variables are not configured.');
return res.status(500).json({ error: 'Email delivery is not configured.' });
}
const submission = extractFields(req.body);
if (!submission.firstName || !submission.lastName || !submission.email) {
return res.status(400).json({ error: 'Missing required fields.' });
}
const orderedKeys = [
...Object.keys(FIELD_LABELS).filter((key) => key in submission),
...Object.keys(submission).filter((key) => !(key in FIELD_LABELS)),
];
const bodyLines = orderedKeys
.filter((key) => submission[key] !== '')
.map((key) => `${FIELD_LABELS[key] || key}: ${submission[key]}`)
.join('\n');
const contactName = `${submission.firstName} ${submission.lastName}`.trim();
const sendGridBody = {
personalizations: [
{ to: [{ email: notificationEmail }], subject: `Contact form — ${contactName}` },
],
from: { email: fromEmail, name: 'Website Contact Form' },
reply_to: { email: submission.email, name: contactName },
content: [{ type: 'text/plain', value: bodyLines }],
};
try {
const response = await fetch('https://api.sendgrid.com/v3/mail/send', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${apiKey}` },
body: JSON.stringify(sendGridBody),
});
if (!response.ok) {
// Log only the status: SendGrid's error body can echo submitted values.
console.error('SendGrid Mail Send error:', response.status);
return res.status(502).json({ error: 'Failed to send email.' });
}
return res.status(200).json({ success: true });
} catch (err) {
console.error('Failed to call SendGrid Mail Send API:', err);
return res.status(500).json({ error: 'An unexpected error occurred.' });
}
}

I then added the variables to each environment (local, Dev, UAT, and Production). In my case, the non-local environments are hosted on Vercel, so I added the environment variables there, and to my .env.local file locally:

VariablePurpose
CONTACT_FORM_WEBHOOK_SECRETShared secret that Forms sends in the x-webhook-secret header
SENDGRID_API_KEYSendGrid key with Mail Send permission
SENDGRID_FROM_EMAILVerified sender address
CONTACT_NOTIFICATION_EMAILInbox that receives this form’s notifications

After those environment variables were set, I deployed the webhook to each environment.

Step 2: Register the webhook in SitecoreAI Forms

Now that the the webhook route was deployed, I needed to register the webhook in SitecoreAI Forms. You can do this from the Webhooks tab on the SitecoreAI Forms dashboard, or from a form’s Settings page under Manage webhooks.

There’s a few different options when registering a webhook, but here’s what I went with:

  1. I set Authentication Type to API key, entered x-webhook-secret as the header name, and the value of the CONTACT_FORM_WEBHOOK_SECRET environment variable setup earlier as the value.
  2. Because this webhook was for a contact form, I set Name to Contact Form — Send Email.
  3. I set the URL to that of the webhook route: https://<my-site>/api/forms/submit-contact.

Note: The URL has to meet SitecoreAI’s endpoint requirements:

  • HTTPS only, with a valid certificate and TLS 1.2 or 1.3
  • Port 443 or 8443
  • Publicly reachable: no localhost, no private network addresses

The API key option matches the header check in the handler. Forms also supports Basic auth, OAuth 2 client credentials and custom headers, which is useful when the target is a third-party API rather than your own route.

Note: Try to avoid No authentication: Sitecore discourages it, and it would leave your relay open to anyone with the URL.

Step 3: Attach it to a form and test

The last step is to attach the webhook to a form. The easiest way I found to do this was to open up the specific form and attach it there:

  1. I opened the form in the form editor and clicked Settings.
  2. Then, under Form submission webhook, I picked the Contact Form — Send Email webhook from Choose webhook and clicked Add.
  3. Finally, I saved, then activated the form.

To test, I started at the route and worked outward:

  • Test the route by itself
    • I sent a POST request with a sample payload with Postman, checking for a 401 without the header, a 400 with a required field missing, and a 200 plus an email in my inbox when everything is valid.
  • Test the full path
    • I submitted the form from a page and confirmed the email arrives with every field in form order and reply-to set to the applicant.
  • Test the failure path
    • I temporarily broke some settings, such as the notification address variable, and checked what visitors see when the webhook returns an error.

Lessons I learned

  • Pull the shared logic out early
    • I initially had only one form that I needed a webhook for. As the project progressed, more and more forms were required. Each form’s handler repeated about 120 lines of parsing, auth and SendGrid code, and only the field maps, env var name and required fields were different. I created a shared createSendEmailHandler({ fieldMap, labels, recipientEnv, required }) turning each new form into a config file.
  • Pay attention to copy-paste drift
    • When my list of forms grew, I was copying and pasting handlers, which lead to small bugs such as trying to read fields a form doesn’t have. Consider adding tests that sends each form’s sample payload and checks the output email.
  • Don’t log submission bodies
    • SendGrid’s (and other email service providers) error responses can echo submitted values, such as a user’s email or address. I decided to log the status code only, and never return upstream error text to SitecoreAI Forms.
  • Field names are part of the contract
    • If an author renames a field in the form editor, its internal name changes and the value lands under an unmapped key. It still appears in the email, but with a raw label and possibly a failed required check. I decided to create some documentation to explain this.
  • Plan per environment
    • Webhooks belong to a tenant, so UAT and production each need their own entry pointing at their own URL. I made sure that the URLs used for each tenant reflected that environment’s URLs.

Wrapping up

A SitecoreAI Forms webhook comes down to three parts: an authenticated API route that owns the logic, a webhook entry that points at it, and a form setting that ties them together. Once the first handler works, adding Send Email to another form takes a field map and an environment variable. The same pattern works for any submit action Forms doesn’t include, whether that’s saving to a database, posting to a CRM or routing by zip code.

I hope you found this guide on how to use SitecoreAI Forms webhooks useful! If you have any questions, please drop a comment below!

Until next time, happy Sitecoring!

Sources

Leave a Reply