Nuxt 4 integration
The complete example lives in examples/nuxt-contact-form. It uses Nuxt UI, Zod, Cloudflare Turnstile and a reusable usePostvia composable.
Minimal inline version
<script setup lang="ts">
import { z } from 'zod'
const schema = z.object({
name: z.string().min(1, 'Enter your name'),
email: z.string().email('Enter a valid email address'),
message: z.string().min(10, 'Tell us a little more'),
})
const state = reactive({ name: '', email: '', message: '' })
const pending = ref(false)
const success = ref('')
const apiError = ref('')
const fieldErrors = ref<Record<string, string[]>>({})
const idempotencyKey = ref(crypto.randomUUID())
async function onSubmit(event: { data: z.output<typeof schema> }) {
pending.value = true
success.value = ''
apiError.value = ''
fieldErrors.value = {}
try {
const result = await $fetch<{ success: true, submission_id: string }>(
`https://api.postvia.dev/v1/forms/abc123/submissions`,
{
method: 'POST',
headers: {
Accept: 'application/json',
'Idempotency-Key': idempotencyKey.value,
},
body: event.data,
},
)
success.value = 'Your enquiry has been received.'
idempotencyKey.value = crypto.randomUUID()
} catch (error: any) {
apiError.value = error?.data?.error?.message ?? 'We could not send your enquiry.'
fieldErrors.value = error?.data?.error?.fields ?? {}
} finally {
pending.value = false
}
}
</script>
<template>
<UForm :schema="schema" :state="state" class="space-y-4" @submit="onSubmit">
<UFormField label="Name" name="name" :error="fieldErrors.name?.[0]">
<UInput v-model="state.name" autocomplete="name" />
</UFormField>
<UFormField label="Email" name="email" :error="fieldErrors.email?.[0]">
<UInput v-model="state.email" type="email" autocomplete="email" />
</UFormField>
<UFormField label="Message" name="message" :error="fieldErrors.message?.[0]">
<UTextarea v-model="state.message" :rows="5" />
</UFormField>
<UAlert v-if="apiError" color="error" variant="subtle" :title="apiError" role="alert" />
<UAlert v-if="success" color="success" variant="subtle" :title="success" role="status" />
<UButton type="submit" :loading="pending" :disabled="pending">Send enquiry</UButton>
</UForm>
</template>
For a typed, tested implementation, use the composable:
const { submit, pending, error, success } = usePostvia('abc123')
await submit({
name: 'John Smith',
email: '[email protected]',
message: 'Hello',
})
The example wires idempotency reuse, field errors, Retry-After and Turnstile reset around the composable. See the full files below.
Composable implementation
export function usePostvia(publicId: string, apiUrl = 'https://api.postvia.dev') {
const pending = ref(false)
const success = ref(false)
const successMessage = ref('')
const error = ref<string | null>(null)
const fieldErrors = ref<Record<string, string[]>>({})
const requestId = ref<string | null>(null)
const retryAfter = ref<number | null>(null)
const idempotencyKey = ref(crypto.randomUUID())
const lastPayload = ref<string | null>(null)
function rotateKey() {
idempotencyKey.value = crypto.randomUUID()
lastPayload.value = null
}
async function submit(values: Record<string, unknown>, turnstileToken?: string) {
pending.value = true
success.value = false
error.value = null
fieldErrors.value = {}
retryAfter.value = null
const signature = JSON.stringify(values)
if (lastPayload.value !== null && lastPayload.value !== signature) rotateKey()
lastPayload.value = signature
const response = await $fetch.raw(`${apiUrl}/v1/forms/${publicId}/submissions`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Idempotency-Key': idempotencyKey.value,
},
body: {
...values,
...(turnstileToken ? { 'cf-turnstile-response': turnstileToken } : {}),
},
ignoreResponseError: true,
})
pending.value = false
if (response.status === 200 || response.status === 201) {
success.value = true
successMessage.value = (response._data as any).message
rotateKey()
return true
}
const body = response._data as any
error.value = body?.error?.message ?? 'We could not send your enquiry.'
fieldErrors.value = body?.error?.fields ?? {}
requestId.value = body?.request_id ?? null
retryAfter.value = Number(response.headers.get('Retry-After')) || null
return false
}
return { submit, pending, success, successMessage, error, fieldErrors, requestId, retryAfter, idempotencyKey }
}
The full example also tracks the submission ID, rotates the key when the payload changes, resets Turnstile and focuses accessible error and success messages.
Runtime configuration
export default defineNuxtConfig({
modules: ['@nuxt/ui'],
runtimeConfig: {
public: {
postviaApiUrl: process.env.NUXT_PUBLIC_POSTVIA_API_URL || 'https://api.postvia.dev',
turnstileSiteKey: process.env.NUXT_PUBLIC_TURNSTILE_SITE_KEY || '',
},
},
})
NUXT_PUBLIC_POSTVIA_API_URL=https://api.postvia.dev
NUXT_PUBLIC_TURNSTILE_SITE_KEY=your-public-site-key
Turnstile
Render the widget on the client, keep the token until submit, and reset it after success or a failed verification. Do not reuse a token across submissions.
const token = ref('')
const widget = ref<HTMLElement>()
onMounted(() => {
window.turnstile?.render(widget.value!, {
sitekey: useRuntimeConfig().public.turnstileSiteKey,
action: 'contact',
callback: value => { token.value = value },
'expired-callback': () => { token.value = '' },
})
})
CORS and Origin
Nuxt SSR calls do not automatically send the browser Origin. Prefer submitting from the client. If you must submit during SSR, send the customer website origin explicitly and keep it on the allowlist.
Full example
examples/nuxt-contact-form/app/composables/usePostvia.tsexamples/nuxt-contact-form/app/composables/useTurnstile.tsexamples/nuxt-contact-form/app/components/ContactForm.vue