JavaScript integration
Submit a form from plain JavaScript with retries and Turnstile.
Use fetch and send JSON. Browsers add the Origin header automatically, but the page must be served from an origin on the website allowlist.
const endpoint = 'https://api.postvia.dev/v1/forms/abc123/submissions'
async function submitForm(values, turnstileToken) {
const idempotencyKey = crypto.randomUUID()
const response = await fetch(endpoint, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'Idempotency-Key': idempotencyKey,
},
body: JSON.stringify({
...values,
...(turnstileToken ? { 'cf-turnstile-response': turnstileToken } : {}),
}),
})
const result = await response.json()
if (!response.ok) {
throw Object.assign(new Error(result.error?.message ?? 'Submission failed'), {
status: response.status,
code: result.error?.code,
fields: result.error?.fields,
requestId: result.request_id,
retryAfter: response.headers.get('Retry-After'),
})
}
return result
}
Reuse the key on retry
Generate the key once per logical submission. If the network drops before a response, retry with the same key and payload. Do not create a new key for the same attempt.
async function submitWithRetry(values, token) {
const key = crypto.randomUUID()
const body = JSON.stringify({ ...values, 'cf-turnstile-response': token })
for (let attempt = 0; attempt < 2; attempt++) {
const response = await fetch(endpoint, {
method: 'POST',
headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'Idempotency-Key': key },
body,
})
if (response.ok) return response.json()
if (response.status !== 503 && response.status !== 429) {
const body = await response.json()
throw Object.assign(new Error(body.error?.message ?? 'Submission failed'), {
status: response.status,
code: body.error?.code,
})
}
await new Promise(resolve => setTimeout(resolve, 1000 * (attempt + 1)))
}
}
Do not automatically retry an invalid or expired Turnstile token. Obtain a fresh token and reset the widget first.
Handle errors
422— show field errors and keep the values.429— wait forRetry-After, then retry with the same key.503— the service or Turnstile is temporarily unavailable; retry with backoff.403— origin or verification failure; do not retry blindly.
See Handling validation errors and Handling successful submissions.