Skip to content
Help

All help pages

Embed a form with the JavaScript SDK (React, Vue, Next.js, HTML)

The Canard Form JavaScript SDK shows a complete form on your website in one line, with React, Vue, Next.js, Nuxt or a plain HTML page. Alternatives without the SDK: HTML and fetch.

Canard Form is a hosted form backend: it validates and stores submissions, sends notifications and applies spam protection. To show a form on your website, the recommended way is the JavaScript SDK @canardform/sdk. No API key, server route or environment variable is needed.

The Integrations → Full integration tab of each form generates the code on this page with your real fields. The examples below use YOUR_FORM in place of the form ID.

The simplest way: copy and paste this code

Paste this code into your page, where the form should appear. That's it.

<div id="form"></div>
<script type="module">
    import { mountForm } from 'https://cdn.jsdelivr.net/npm/@canardform/sdk@1.0.0-alpha.4/+esm';
    mountForm('#form', 'YOUR_FORM');
</script>

The complete form shows: fields, steps, conditions, anti-robot check, errors and thank-you message. Nothing to install, no key, no server. This code works on any HTML page, CMS or template. The next sections show how to go further: dedicated components, server rendering, custom design.

Pick an integration

Your project Recommended integration
React, Next.js SDK: <CanardForm> component or useCanardForm hook
Vue, Nuxt SDK: <CanardForm> component or useCanardForm composable
Svelte, Angular, Astro, JavaScript with a bundler SDK: mountForm()
Static site, CMS, template without a build tool SDK loaded from a CDN
No JavaScript at all Without the SDK: plain HTML form

Why use the SDK

The SDK reads the published form and handles everything:

  • fields, labels, help texts and languages;
  • steps, with Previous and Next buttons;
  • display conditions;
  • the anti-robot check (hCaptcha);
  • validation in the browser and errors returned by the server;
  • the thank-you message, the "form closed" message and a fallback message if Canard Form can't be reached;
  • sending without duplicates, even after a network failure.

A change you publish in Canard Form applies on your website with no code change. The SDK is open source and typed in TypeScript. It works with or without a framework, and you stay in control of the design: CSS classes, how one field renders, or the full markup.

The SDK is in alpha. Copy the version shown in the Integrations tab, which is kept up to date.

Install the SDK

In a project that uses npm (with Vite, webpack, React, Vue, Next.js, Nuxt, Svelte, Angular, Astro…):

npm install @canardform/sdk@alpha

Then, depending on your project:

  • React, Next.js, Vue or Nuxt: use the <CanardForm> component (see React and Vue and Nuxt).
  • Any other project (JavaScript without a framework, Svelte, Angular, Astro…): call mountForm on an element of the page.
import { mountForm } from '@canardform/sdk';

// Builds the complete form inside <div id="form"></div>
mountForm('#form', 'YOUR_FORM');

Load the SDK from a CDN

For a website without a build tool (static site, CMS, template), load the SDK from jsDelivr:

<div id="form"></div>

<script type="module">
    import { mountForm } from 'https://cdn.jsdelivr.net/npm/@canardform/sdk@1.0.0-alpha.4/+esm';

    mountForm('#form', 'YOUR_FORM', {
        lang: 'en',
        classes: { form: 'my-form', submit: 'my-button' },
        onSubmitted: () => (window.location.href = '/thanks'),
    });
</script>

All options are optional and described in mountForm options.

React

import { CanardForm } from '@canardform/sdk/react';

export default function ContactForm() {
    return <CanardForm formId="YOUR_FORM" />;
}

To keep your design:

  • classes={{ form: '…', submit: '…' }} adds your classes.
  • renderField replaces how one field renders with your component.
  • The useCanardForm hook lets you write all the markup:
import { useCanardForm } from '@canardform/sdk/react';

export default function ContactForm() {
    const form = useCanardForm('YOUR_FORM');

    if (form.status === 'sent')
        return <p>Thanks, your message has been sent.</p>;

    return (
        <form onSubmit={form.handleSubmit} onChange={form.handleChange}>
            <input type="text" name="name" required />
            <input type="email" name="email" required />
            {form.isVisible('company') && <input type="text" name="company" />}
            <div ref={form.captchaRef} />
            <button type="submit" disabled={form.status === 'sending'}>
                Send
            </button>
            {form.error && <p>{form.error}</p>}
        </form>
    );
}
  • form.isVisible(key) applies the form's display conditions.
  • form.captchaRef places the anti-robot check, if the form requires it.

Multi-step form: one section per step, and buttons to move forward and back. The Integrations tab generates this code with your real steps.

<section data-step="contact" hidden={!form.isStep('contact')}>
  {/* fields of the "contact" step */}
</section>
<section data-step="project" hidden={!form.isStep('project')}>
  {/* fields of the "project" step */}
</section>

{form.step > 0 && (
  <button type="button" onClick={form.previous}>Previous</button>
)}
{form.step < form.steps.length - 1 ? (
  <button type="button" onClick={(event) => form.next(event.currentTarget)}>Next</button>
) : (
  <button type="submit">Send</button>
)}

Next.js (App Router)

Read the form on the server so it is in the HTML from the start (SSR, better for SEO and display), then pass it to a client component:

// app/contact/page.tsx
import { getForm } from '@canardform/sdk';
import ContactForm from './ContactForm';

export default async function ContactPage() {
    const definition = await getForm('YOUR_FORM');

    return <ContactForm definition={definition} />;
}
// app/contact/ContactForm.tsx
'use client';
import type { PublicForm } from '@canardform/sdk';
import { CanardForm } from '@canardform/sdk/react';

export default function ContactForm({
    definition,
}: {
    definition: PublicForm;
}) {
    return <CanardForm formId="YOUR_FORM" definition={definition} />;
}

Vue and Nuxt

<script setup lang="ts">
import { CanardForm } from '@canardform/sdk/vue';
</script>

<template>
    <CanardForm form-id="YOUR_FORM" />
</template>

To replace a single field, use the #field slot (see CanardForm component).

Write all the markup with the useCanardForm composable:

<script setup lang="ts">
import { useCanardForm } from '@canardform/sdk/vue';

const form = useCanardForm('YOUR_FORM');
</script>

<template>
    <p v-if="form.status.value === 'sent'">
        Thanks, your message has been sent.
    </p>
    <form v-else @submit="form.handleSubmit" @input="form.handleChange">
        <input type="text" name="name" required />
        <input type="email" name="email" required />
        <input v-if="form.isVisible('company')" type="text" name="company" />
        <div :ref="form.captchaRef" />
        <button type="submit">Send</button>
        <p v-if="form.error.value">{{ form.error.value }}</p>
    </form>
</template>

Nuxt (SSR): read the form on the server and pass it to the component.

<script setup lang="ts">
import { getForm } from '@canardform/sdk';
import { CanardForm } from '@canardform/sdk/vue';

const { data } = await useAsyncData(() => getForm('YOUR_FORM'));
</script>

<template>
    <CanardForm form-id="YOUR_FORM" :definition="data" />
</template>

Svelte, Angular, Astro and others

With a bundler, import mountForm from @canardform/sdk and call it on an element of the page, as with the CDN. To render the form with your own components, createFormController (from @canardform/sdk/controller) provides state, validation, steps and sending with no rendering at all.

mountForm options

mountForm(target, formId, options) builds the form inside target (a CSS selector such as '#form', or an HTML element). All options are optional.

Option Type Purpose
lang string The form's language ('en', 'fr'…). Defaults to the browser's language if the form offers it, otherwise its default language. Also used for the acknowledgement email.
publicUrl string Your custom domain address, for example 'https://forms.your-site.com'. Defaults to https://canardform.app.
classes object Your CSS classes, per element: form, field, error, success, closed, unavailable, submit (see CSS classes).
messages object Fallback texts when the form doesn't provide them: submit, success, closed, unavailable, error, next, previous.
onSubmitted (submissionId, form) => void Called after a successful submission. By default, the form is replaced by the thank-you message.
onError (error, form) => void Called when the submission is rejected (invalid field, closed form…). By default, the message shows below the form.
beforeSubmit (data: FormData) => FormData | void Adds or changes data just before sending: hidden field, campaign ID, UTM source… Can be async.
renderField (field, element) => HTMLElement | void Replaces how a field renders. Return undefined to keep the default rendering.
idempotencyKey string Duplicate-protection key for the submission. Generated automatically: only provide it if you handle retries yourself.
fetch typeof fetch A fetch function to use instead of the browser's (tests, proxy).

mountForm returns a promise with:

  • definition: the published form as read (fields, language, texts);
  • element: the <form> element that was built;
  • destroy(): removes the form from the page.

Full example:

import { mountForm } from '@canardform/sdk';

const { destroy } = await mountForm('#form', 'YOUR_FORM', {
    lang: 'en',
    classes: { form: 'grid gap-4', submit: 'btn btn-primary' },
    messages: { success: 'Thanks, we will get back to you within 24 hours.' },
    beforeSubmit: (data) => {
        data.set(
            'source',
            new URLSearchParams(location.search).get('utm_source') ?? '',
        );
    },
    onSubmitted: (id) => {
        window.location.href = '/thanks';
    },
    onError: (error) => {
        console.warn(error.message);
    },
});

For beforeSubmit to save a value, the form must contain a field with that key, usually a hidden field. A hidden field already reads the page address parameter on its own: beforeSubmit is for a value only your site knows (customer ID, cart…).

CanardForm component (React and Vue)

<CanardForm> builds the complete form, like mountForm.

React prop Vue attribute Purpose
formId form-id The form ID (required).
lang lang The form's language.
publicUrl public-url Your custom domain address.
definition :definition The form already read on the server with getForm(), for an immediate render (SSR).
classes :classes Your CSS classes, per element (see CSS classes).
messages :messages Fallback texts: submit, success, closed, unavailable, next, previous.
onSubmitted @submitted Called with the submission ID after a successful submission.
renderField #field slot Replaces how a field renders (see below).
loading #loading slot Content shown while the form is loading.
fetch :fetch A custom fetch function.
idempotencyKey Duplicate-protection key (React only, generated automatically otherwise).

Replacing a field in React: renderField receives { field, error, children }, where children is the default rendering. Return undefined to keep it. <FieldInput field={field} /> gives the control alone, without a label.

import { CanardForm, FieldInput } from '@canardform/sdk/react';

<CanardForm
    formId="YOUR_FORM"
    renderField={({ field, error }) =>
        field.key === 'message' ? (
            <label className="block">
                {field.label}
                <FieldInput field={field} />
                {error && <span className="text-red-600">{error}</span>}
            </label>
        ) : undefined
    }
/>;

Vue slots:

  • #field="{ field, error, input }": replaces how a field renders. input() gives the control alone. A slot that renders nothing for a field keeps the default rendering.
  • #loading: while loading.
  • #success="{ submissionId }": instead of the thank-you message.
  • #closed: instead of the "form closed" message.
  • #unavailable: if the form can't be loaded.

useCanardForm hook and composable

useCanardForm(formId, options) (from @canardform/sdk/react or @canardform/sdk/vue) handles state, conditions, steps, the anti-robot check and sending. You write all the markup. Options: lang, publicUrl, definition, fetch, idempotencyKey.

It returns (in Vue, state values are refs, read with .value in the script):

Value Purpose
definition The published form (fields, texts, language), null while loading.
status 'idle', 'sending', 'sent' or 'error'.
errors First error of each rejected field, by key: errors.email.
error General message (closed form, network issue…).
submissionId The submission ID after sending.
unavailable true if the form couldn't be loaded: show a fallback message.
steps, step The steps to go through (those with at least one visible field) and the current step's index.
handleSubmit Wire to the <form>'s submit.
handleChange Wire to onChange (React) or @input (Vue): updates display conditions.
isVisible(key) Should the field show, given the current answers?
isStep(key) Is this step the one shown?
next(element) Checks the current step's fields, then moves to the next one.
previous() Goes back to the previous step.
captchaRef Put it on an empty element inside the form: the anti-robot check shows there when required.
submit(data) Sends an object or a FormData without going through the <form>.
reset() Goes back to the initial state (for example to send another submission).

For another library (Svelte, Angular, Solid…), createFormController(formId, options) from @canardform/sdk/controller provides the same functions, plus getState() and subscribe(listener) to follow the state.

getForm and submitForm functions

Both functions work in the browser and on a server (Node.js, Next.js, Nuxt, serverless functions).

import { getForm, submitForm, CanardFormError } from '@canardform/sdk';

// Read the published form (fields, steps, texts, language)
const form = await getForm('YOUR_FORM', { lang: 'en' });

// Send a submission: an object, or a FormData for files
try {
    const id = await submitForm('YOUR_FORM', {
        name: 'Camille',
        email: 'camille@example.com',
    });
} catch (error) {
    if (error instanceof CanardFormError) {
        console.log(error.error, error.status, error.errors);
    }
}
  • Options of getForm and submitForm: lang, publicUrl, fetch, plus idempotencyKey for submitForm.
  • CanardFormError carries the stable code (error, see Responses and error codes), the HTTP status (status) and per-field errors (errors).
  • If the form requires the anti-robot check, a submission sent from a server is refused: use submitForm in the browser, with the hCaptcha widget.

CSS classes

The SDK sets these classes by default. Style them, or replace them with the classes option:

Element Default class classes key
The <form> cf-form form
Each field (label, control, help, error) cf-field field
Error message cf-error error
Thank-you message cf-success success
"Form closed" message cf-closed closed
Fallback message (form unreachable) cf-unavailable unavailable
Submit button cf-submit submit

A class passed in classes replaces the default class of that element.

Without the SDK: HTML form or fetch

If you can't load JavaScript, or want to write all the code yourself, send submissions straight to the form's address. You then reproduce the fields, the anti-robot check and the messages yourself, and a change to the form in Canard Form means changing your code.

Form address

Each form has a public address:

https://canardform.app/v1/f/YOUR_FORM
  • GET with the Accept: application/json header returns the published definition (steps, fields, options, conditions).
  • POST sends a submission.

With a custom domain, the address becomes https://forms.your-site.com/v1/f/YOUR_FORM. For the SDK, pass the option publicUrl: 'https://forms.your-site.com'.

HTML form without JavaScript

The simplest option: a plain HTML form. Each field's name is the field's key (shown in the editor under Advanced settings).

<form action="https://canardform.app/v1/f/YOUR_FORM" method="POST">
    <label
        >Name
        <input type="text" name="name" required />
    </label>
    <label
        >Email
        <input type="email" name="email" required />
    </label>
    <label
        >Message
        <textarea name="message" required></textarea>
    </label>
    <input
        type="hidden"
        name="_redirect"
        value="https://your-site.com/thanks"
    />
    <input
        type="text"
        name="_hp"
        style="display:none"
        tabindex="-1"
        autocomplete="off"
    />
    <button type="submit">Send</button>
</form>
  • _redirect (optional): the page on your website shown after sending (see The page shown after sending).
  • _hp: an invisible trap field. If it is filled in, the submission is rejected as spam.
  • Multiple checkboxes: name="key[]", one box per option, with the option's value.
  • Files: add enctype="multipart/form-data" to the <form>.
  • If there is an error, the form's Canard Form page shows with the errors and the values entered.

In this mode, steps show on a single page and conditional fields must stay optional. The bot check needs JavaScript: pick the Standard or Strict protection (see Spam protection), or add the hCaptcha widget described below.

The page shown after sending

After a successful submission, the visitor's browser is sent to the _redirect address when all of these hold:

  • it is a full address, in https:// (or http://);
  • its domain is exactly the one of the page holding the form: www.mysite.com and mysite.com are two different domains;
  • the browser tells where the submission comes from. It does so on its own (Origin header, otherwise Referer), unless your site prevents it with Referrer-Policy: no-referrer.

Otherwise, the visitor sees the Canard Form thank-you page. The answer is saved in every case. If something is wrong (missing field, file too large…), there is no redirect: the form page shows the errors and what the person had typed.

Why this rule: without it, anyone could use a Canard Form address to send your visitors to a trapped site. An attacker can of course send fake headers from their own program, but the redirect then only applies to themselves: a visitor's browser always gives the real page of origin.

With the SDK or fetch, _redirect is not used: the response is JSON. Redirect yourself in onSubmitted (see mountForm options).

Send with JavaScript fetch

To stay on the page and show your own message:

<form id="contact">
    <input type="text" name="name" required />
    <input type="email" name="email" required />
    <textarea name="message" required></textarea>
    <button type="submit">Send</button>
    <p id="result"></p>
</form>

<script>
    const form = document.getElementById('contact');
    const result = document.getElementById('result');

    form.addEventListener('submit', async (event) => {
        event.preventDefault();
        const response = await fetch('https://canardform.app/v1/f/YOUR_FORM', {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Idempotency-Key': crypto.randomUUID(),
            },
            body: new FormData(form),
        });
        if (response.ok) {
            form.reset();
            result.textContent = 'Thanks, your message has been sent.';
        } else {
            result.textContent = 'Check the fields and try again.';
        }
    });
</script>

The Accept: application/json header is required to get a JSON response instead of a redirect. Send the body as FormData (required with files) or as JSON with Content-Type: application/json.

Anti-robot check (hCaptcha)

If the form uses the Anti-robot check (the default, see Spam protection), every submission must include an hCaptcha token.

  • With the SDK, the widget shows automatically (or where captchaRef is placed).
  • With HTML or fetch, add the widget inside the form. The public key (data-sitekey) is in the code from the Integrations tab:
<div class="h-captcha" data-sitekey="PUBLIC_KEY"></div>
<script src="https://js.hcaptcha.com/1/api.js" async defer></script>

The widget adds the h-captcha-response field to the form. Without a valid token, the submission is refused with the captcha_failed code.

Responses and error codes

With Accept: application/json:

Status Body Meaning
201 {"submission_id": "…"} Submission saved
200 {"submission_id": "…"} Same Idempotency-Key already received: nothing is saved twice
422 {"error": "validation_failed", "errors": {…}} Invalid fields, with one message per field
422 {"error": "captcha_failed"} Anti-robot check missing or invalid
422 {"error": "spam_rejected"} The _hp trap field was filled in
410 {"error": "form_closed"} Form disabled, archived or outside its dates
403 {"error": "quota_exceeded"} Monthly submission limit reached
403 {"error": "origin_not_allowed"} Website missing from the form's allowed websites
403 {"error": "storage_quota_exceeded"} File storage full
409 {"error": "idempotency_conflict"} Same Idempotency-Key with different content
409 {"error": "idempotency_in_progress"} Same Idempotency-Key still being processed, retry in a moment
429 Too many submissions from the same address
500 {"error": "technical_error", "reference": "…"} Technical error, report it with the reference

Idempotency-Key: send a unique value per attempt (for example crypto.randomUUID()) and reuse it if you resend the same submission after a network failure. Without this header, a double click within the same minute is still deduplicated.

Files

Send files as multipart/form-data, with the field key as name (name="resume", or name="documents[]" for several files). Accepted types, number of files and maximum size are those set on the File field (see The File upload field).

Content Security Policy

If your website sends a Content-Security-Policy header, allow:

  • canardform.app (or your custom domain) in connect-src and form-action, and in frame-src for the iframe integration;
  • https://hcaptcha.com https://*.hcaptcha.com in script-src, frame-src, style-src and connect-src if the form uses the anti-robot check;
  • https://cdn.jsdelivr.net in script-src only if you load the SDK from the CDN.

Integration with an AI agent

In Integrations → With an AI agent, click Copy the prompt and paste it into your project's agent (Claude Code, Cursor, Copilot…). The prompt contains the form ID, its fields and steps, which integration to pick for your stack and the checks to run. The agent detects your framework and adds the form following the project's conventions.

SDK documentation

The full SDK documentation (options, types, custom rendering, SSR) is at canardform.github.io/sdk-js. The SDK is open source. To read submissions from your server, use the API.