Submitting Custom Forms to HubSpot With JavaScript

A custom HTML form can send data to HubSpot with a JSON POST request - without a private access token. Match input names to HubSpot properties, validate the values, and submit them to the public forms endpoint using the portal ID and form GUID.
This guide covers a demo request form with 5 contact fields and a separate consent checkbox, including how to:
- Add page context and consent data when needed.
- Block repeat clicks while a request is pending.
- Announce success and errors with accessible messages.
- Keep entered values after failed or unconfirmed requests.
- Test field mappings, delivery, and error handling before publishing.
Private tokens belong on a protected server, never in browser JavaScript.
Custom JavaScript Forms to HubSpot: Submission Flow
Set Up the HubSpot Form and HTML Fields
Find Form IDs and Match Field Names
Save your portal ID and form GUID in your config, then send submissions to HubSpot’s public submission endpoint.
POST https://api.hsforms.com/submissions/v3/integration/submit/{portalId}/{formGuid}
Before building a multi-step or static form in HTML, check each field’s internal name, type, required status, and validation rules in HubSpot. Each HTML name must match its HubSpot property name. In this “Request a demo” example, email and first name are required. Consent is required only when your configured process calls for it.
| HTML input name | HubSpot property name or payload mapping | Field type | Required? |
|---|---|---|---|
email |
email |
Yes | |
firstname |
firstname |
Single-line text | Yes |
lastname |
lastname |
Single-line text | No |
company |
company |
Single-line text | No |
jobtitle |
jobtitle |
Single-line text | No |
consent |
legalConsentOptions (not a contact property) |
Checkbox | When required |
Build Accessible HTML Fields
Use those property names to build inputs with accessible labels and matching error targets. Keep each maxlength at or below HubSpot’s limits.
<form id="contact-form"> <label for="email">Work email (required)</label> <input id="email" name="email" type="email" autocomplete="email" required maxlength="254" aria-describedby="email-error" /> <p id="email-error" role="alert"></p> <label for="firstname">First name (required)</label> <input id="firstname" name="firstname" type="text" autocomplete="given-name" required maxlength="100" aria-describedby="firstname-error" /> <p id="firstname-error" role="alert"></p> <label for="lastname">Last name</label> <input id="lastname" name="lastname" type="text" autocomplete="family-name" maxlength="100" aria-describedby="lastname-error" /> <p id="lastname-error" role="alert"></p> <label for="company">Company</label> <input id="company" name="company" type="text" autocomplete="organization" maxlength="255" aria-describedby="company-error" /> <p id="company-error" role="alert"></p> <label for="jobtitle">Job title</label> <input id="jobtitle" name="jobtitle" type="text" autocomplete="organization-title" maxlength="100" aria-describedby="jobtitle-error" /> <p id="jobtitle-error" role="alert"></p> <!-- Use approved consent copy here and map it separately in `legalConsentOptions`. --> <label for="consent"> <input id="consent" name="consent" type="checkbox" required aria-describedby="consent-error" /> I agree to the processing of my personal information. </label> <p id="consent-error" role="alert"></p> <button type="submit">Submit</button> <p id="submission-status" role="status" aria-live="polite"></p> </form>
Keep native browser validation on. Don’t add novalidate.
When the form needs consent, handle it separately from contact fields through legalConsentOptions. Keep optional marketing subscriptions separate from processing consent.
sbb-itb-5f36581
Validate Inputs and Build the Payload
Read and Validate FormData
Place the script after the form. Trim submitted values, check field rules, and reject whitespace-only input before building the payload. Browser validation is a convenience, not a safeguard. Enforce rules and limits on the server, too.
With the HTML in place, normalize the inputs, then include only approved HubSpot properties in the request body.
const form = document.querySelector("#contact-form"); const names = [ "email", "firstname", "lastname", "company", "jobtitle", "consent" ]; const inputs = Object.fromEntries( names.map((name) => [name, form.elements.namedItem(name)]) ); function showErrors(errors) { for (const name of names) { const errorMessage = errors[name] || ""; document.querySelector(`#${name}-error`).textContent = errorMessage; inputs[name].setAttribute("aria-invalid", errorMessage ? "true" : "false"); } const firstInvalid = names.find((name) => errors[name]); if (firstInvalid) inputs[firstInvalid].focus(); } form.addEventListener("submit", async (event) => { event.preventDefault(); showErrors({}); // Clear prior errors. const formData = new FormData(form); const values = {}; const errors = {}; for (const name of names.filter((name) => name !== "consent")) { const input = inputs[name]; const value = String(formData.get(name) ?? "").trim(); values[name] = value; input.value = value; if (input.required && !value) { errors[name] = "Complete this required field."; } else if (input.maxLength >= 0 && value.length > input.maxLength) { errors[name] = `Use ${input.maxLength} characters or fewer.`; } else if (!input.validity.valid) { errors[name] = input.validationMessage; } } if (values.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(values.email)) { errors.email = "Enter a valid email address."; } if (inputs.consent.required && !inputs.consent.checked) { errors.consent = "Agree to processing before submitting."; } if (Object.keys(errors).length) { showErrors(errors); return; } const payload = buildPayload(values); // Add the POST request and response handling here in the next section. });
Map Inputs to HubSpot Properties
Once validation passes, convert the allowed values into HubSpot’s field format. Add this helper to the same script. It leaves out empty optional values and keeps consent outside fields.
function buildPayload(values) { const fields = ["email", "firstname", "lastname", "company", "jobtitle"] .filter((name) => values[name] !== "") .map((name) => ({ name, value: values[name] })); const payload = { fields }; const context = buildContext(); if (Object.keys(context).length) payload.context = context; return payload; }
Here’s an example payload only.
{ "fields": [ { "name": "email", "value": "alex.taylor@example.com" }, { "name": "firstname", "value": "Alex" }, { "name": "company", "value": "Example Company" } ], "context": { "pageUri": "https://www.example.com/contact", "pageName": "Contact us" } }
Add Page Details and Consent
Send page context only when it’s safe and relevant. This helper strips query strings and fragments, but the remaining path and page title must not reveal sensitive information. Include them only after checking that condition.
Replace hasAnalyticsConsent() with your consent manager’s current decision before including hubspotutk. The context then feeds the same POST request shown in the next section.
function hasAnalyticsConsent() { return false; // Wire to your consent state. } function getCookie(name) { const prefix = `${name}=`; const cookie = document.cookie .split(";") .map((part) => part.trim()) .find((part) => part.startsWith(prefix)); if (!cookie) return null; try { return decodeURIComponent(cookie.slice(prefix.length)) || null; } catch { return null; } } function buildContext() { const context = {}; const pageUri = window.location.origin + window.location.pathname; const pageName = document.title.trim(); if (pageUri) context.pageUri = pageUri; if (pageName) context.pageName = pageName; const hutk = hasAnalyticsConsent() ? getCookie("hubspotutk") : null; if (hutk) context.hutk = hutk; return context; }
Use legalConsentOptions only for consent you collected, and keep marketing opt-ins separate. Place this block inside buildPayload(), before return payload;. The text must match your approved notice and checkbox label.
if (inputs.consent.checked) { payload.legalConsentOptions = { consent: { consentToProcess: true, text: "I agree that Example Company may store and process my information to respond to my request." } }; }
Submit the Form and Handle the Response
Send a POST Request to HubSpot
Once the payload is ready, send it to HubSpot and handle the response.
Place this script after the form. The public endpoint supports cross-origin AJAX without a private token. Keep authenticated requests on a protected backend, never in browser JavaScript.
const PORTAL_ID = "REPLACE_WITH_PORTAL_ID"; const FORM_GUID = "REPLACE_WITH_FORM_GUID"; const CONSENT_TEXT = "REPLACE_WITH_APPROVED_CONSENT_TEXT"; const PROPERTY_NAMES = [ "email", "firstname", "lastname", "company", "jobtitle" ]; const form = document.querySelector("#contact-form"); const button = form.querySelector('button[type="submit"]'); const names = [...PROPERTY_NAMES, "consent"]; const inputs = Object.fromEntries( names.map((name) => [name, form.elements.namedItem(name)]) ); const errorNodes = Object.fromEntries( names.map((name) => [ name, document.getElementById(`${name}-error`) ]) ); for (const name of names) { const describedBy = new Set( (inputs[name].getAttribute("aria-describedby") || "") .split(/\s+/).filter(Boolean) ); describedBy.add(errorNodes[name].id); inputs[name].setAttribute( "aria-describedby", [...describedBy].join(" ") ); } const status = document.querySelector("#submission-status"); status.tabIndex = -1; let inFlight = false; function setStatus(message) { status.textContent = message; } function showErrors(errors) { for (const name of names) { errorNodes[name].textContent = errors[name] || ""; inputs[name].setAttribute( "aria-invalid", errors[name] ? "true" : "false" ); } } function readAndValidate() { const data = new FormData(form); const values = {}; const errors = {}; for (const name of PROPERTY_NAMES) { const input = inputs[name]; const value = String(data.get(name) ?? "").trim(); values[name] = value; if (input.required && !value) { errors[name] = "Complete this required field."; } else if (input.maxLength >= 0 && value.length > input.maxLength) { errors[name] = `Use ${input.maxLength} characters or fewer.`; } else if (!input.validity.valid) { errors[name] = input.validationMessage; } } if (values.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(values.email)) { errors.email = "Enter a valid email address."; } if (inputs.consent.required && !inputs.consent.checked) { errors.consent = "Agree to processing before submitting."; } return { values, errors }; } function buildPayload(values) { const payload = { fields: PROPERTY_NAMES .filter((name) => values[name] !== "") .map((name) => ({ name, value: values[name] })) }; if (inputs.consent.checked) { payload.legalConsentOptions = { consent: { consentToProcess: true, text: CONSENT_TEXT } }; } return payload; } async function readResponseBody(response) { // Body failures must not override a known HTTP result. try { const type = response.headers.get("content-type") || ""; if (!type.includes("application/json")) return null; const text = await response.text(); return text.trim() ? JSON.parse(text) : null; } catch { return null; } } function failureMessage(code) { if (code === 400) { return "Check your entries for information that could not be accepted."; } if ([401, 403, 404].includes(code)) { return "Contact the site team to fix this form’s setup."; } if (code === 429) { return "Too many submissions were sent; try again later."; } if (code >= 500) { return "HubSpot is temporarily unavailable; try again later."; } return "The submission could not be accepted; contact the site team if this continues."; } form.addEventListener("submit", async (event) => { event.preventDefault(); if (inFlight) return; const { values, errors } = readAndValidate(); showErrors(errors); const firstInvalid = names.find((name) => errors[name]); if (firstInvalid) { setStatus("Check the highlighted fields and try again."); inputs[firstInvalid].focus(); return; } if ([PORTAL_ID, FORM_GUID, CONSENT_TEXT] .some((value) => value.startsWith("REPLACE_WITH_"))) { setStatus("This form needs a setup fix. Contact the site team."); return; } const payload = buildPayload(values); const endpoint = "https://api.hsforms.com/submissions/v3/integration/submit/" + `${encodeURIComponent(PORTAL_ID)}/${encodeURIComponent(FORM_GUID)}`; inFlight = true; const wasDisabled = button.disabled; button.disabled = true; form.setAttribute("aria-busy", "true"); setStatus("Submitting…"); try { const response = await fetch(endpoint, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) }); // Tolerate JSON, empty, and malformed bodies. // Never render or log the response body. await readResponseBody(response); if (!response.ok) { setStatus(failureMessage(response.status)); console.error("HubSpot submission HTTP error", { status: response.status }); return; } showErrors({}); form.reset(); setStatus("Thanks - your submission was received."); status.focus(); } catch { setStatus( "We couldn’t confirm the submission. Your entries are still here. " + "Check your connection before trying again." ); console.error("HubSpot submission result unconfirmed"); } finally { inFlight = false; button.disabled = wasDisabled; form.removeAttribute("aria-busy"); } });
Block Duplicate Clicks While Submitting
The inFlight guard blocks repeat clicks while the request runs. The disabled button and “Submitting…” message show that the form is working, and finally restores the controls.
This stops repeated clicks - not duplicate submissions after an uncertain network result. The code skips automatic retries on purpose.
Announce Successful Submissions
After a successful response, update the live region and clear the form. Only response.ok triggers success. An empty or unreadable response body doesn't change that result.
Messages use textContent, never HTML from the API. Keep form.reset() only if your flow calls for clearing every field, including consent.
Keep Entered Values After Errors
When a request fails, keep the inputs so users can make corrections and resubmit. For 400, check field mappings, required properties, and consent settings. For 403 or 404, check the IDs and endpoint configuration. For 429, check request volume.
A rejected fetch, including a network or CORS failure, means the browser could not confirm the result. It doesn't mean HubSpot rejected the submission. Logs contain only a fixed technical label and, when available, the HTTP status - never submitted values or response bodies.
Test and Troubleshoot the Form
Test Inputs and Submission Behavior
Before publishing, check validation, payload mapping, and response handling on staging with synthetic data.
Try valid entries, missing required fields, whitespace-only values, malformed emails, excessive lengths, and both checked and unchecked consent. Invalid inputs should show field errors without sending a request. Valid inputs should map to the expected payload fields and consent object. Also test without the optional HubSpot tracking cookie; submissions should still work.
Using only the keyboard, check labels, visible focus, Enter-to-submit behavior, and whether focus moves to the first invalid field. Confirm that screen readers announce status updates. With network throttling enabled, make sure repeated fast clicks send only one request. After an offline failure, controls should work again, and entered values should remain available.
Check that the submission appears in the intended HubSpot form history and contact record. Verify the mapped properties, consent, configured page context, and any configured workflow enrollment. If contact deduplication makes the results unclear, use a new test email address you control.
Find and Fix Request Errors
If a test fails, inspect the request before changing the form.
In DevTools, open Network → Fetch/XHR. Check the request URL, method, status, timing, payload, and response body. Compare the portal and form IDs, submitted field names, consent object, and any configured context with HubSpot’s form definition.
Inspect these details locally. Before sharing screenshots or logs, remove names, emails, phone numbers, IP addresses, cookies, tokens, and personal data in responses.
| Symptom | Likely cause | Fix |
|---|---|---|
404 or submission reaches the wrong form |
Incorrect IDs or URL | Copy IDs from the intended form and verify the request URL. |
| Field name mismatch | Incorrect field names | Match internal property names and confirm that the fields belong to the form. |
| Required-field or consent rejection | Missing values or incompatible consent | Check trimmed required values, consent structure, legal text, and subscription requirements. |
| Malformed-request error | Invalid JSON or content type | Send JSON with JSON.stringify(payload) and Content-Type: application/json. |
429 |
Excessive request volume | Stop test bursts, check duplicate protection, and follow retry guidance without blindly replaying submissions. |
| CORS or network failure | Connection, endpoint, or policy issue | Check Console details, URL, connection, and applicable backend CORS settings; treat delivery as unconfirmed. |
Do not use mode: "no-cors". It produces an opaque response with status 0, which prevents useful response inspection. If a private-app token appears in browser code or shared logs, revoke or rotate it immediately and move authenticated requests to a protected backend.
How to Build a Flow Framework with HubSpot Forms API | HubSpot.Extend() 2022
Conclusion: Check Before Publishing
Read values with FormData, validate them, and map them to HubSpot properties. Send a JSON payload with fields, context, and consent when needed. Update the UI only after HubSpot returns success.
Test the form end to end before publishing:
- Consent: Required choices are explicit, unchecked by default, and included only when selected.
- Payload: The portal ID, form GUID, field names, page context, and consent data match the intended form.
- Duplicate protection: Block additional submission attempts while a request is pending.
- Accessible feedback: Announce success messages and errors that explain what users can do next.
- Recovery: Keep users’ inputs when requests fail so they can try again.
- Security: Keep private-app tokens on the server, and rate-limit any authenticated route.
- Delivery check: After a controlled test, confirm that the HubSpot contact record contains the expected values and consent.
FAQs
How can I prevent spam on a public form?
Enable CAPTCHA on your HubSpot form, but keep in mind: it can block API submissions with a FORM_HAS_RECAPTCHA_ENABLED error. Use HubSpot’s blockedEmailDomains setting to block disposable or low-quality email addresses.
Add your form’s domain to HubSpot’s analytics tracking site domain list so legitimate submissions aren’t flagged as bot traffic. Before sending a POST request, check required fields and email syntax. Use the correct endpoint and headers to avoid unintended failures.
Will submissions update existing HubSpot contacts?
Yes. HubSpot matches contacts by email. When someone submits the same email address again, HubSpot updates the existing contact record rather than creating a new one.
The same applies to Reform-to-HubSpot submissions: Reform sends the submission data and uses the email address to match the contact.
How do I submit dropdowns and multiple checkboxes?
Use HubSpot’s internal property names, not display labels. Match internal option values exactly, including spelling and capitalization.
For dropdowns, send the selected value. For multiple checkboxes, first confirm that the property accepts multiple selections. Then send the selected options as an array or a delimited string, based on the property’s configuration.
Reform handles mapping automatically after you connect your HubSpot account and assign fields in the integration settings.
Related Blog Posts
Get new content delivered straight to your inbox
The Response
Updates on the Reform platform, insights on optimizing conversion rates, and tips to craft forms that convert.
Drive real results with form optimizations
Tested across hundreds of experiments, our strategies deliver a 215% lift in qualified leads for B2B and SaaS companies.

.webp)


