Svelte contact form

Formgong team ·

Paste this into Svelte. Posts go to Formgong. No database and no Resend.

250 free submissions a month

How forms work in Svelte

A Svelte app built with Vite is plain frontend code, so the form needs an endpoint to send to. Formgong is that endpoint: the component posts to https://formgong.com/submit and shows the translated answer.

The snippet uses Svelte 5 syntax: $state for the status message and the onsubmit attribute. On Svelte 4, use on:submit|preventDefault and a plain let variable instead; the request itself is the same.

Set it up in Svelte

  1. Create a form in Formgong and copy the access key.
  2. Save the snippet as ContactForm.svelte and replace the key.
  3. Translate the labels and set _lang to the page language.
  4. Run the dev server, send a test and check the Formgong inbox.
Svelte
<script>
  let status = $state("");

  async function onSubmit(event) {
    event.preventDefault();
    const fields = Object.fromEntries(new FormData(event.currentTarget));
    const response = await fetch("https://formgong.com/submit", {
      method: "POST",
      headers: { "Content-Type": "application/json", Accept: "application/json" },
      body: JSON.stringify({ _lang: "en", ...fields, access_key: "fk_your_access_key" }),
    });
    const result = await response.json();
    status = result.message || (result.success ? "Sent. Thank you!" : "Could not send. Please try again.");
  }
</script>

<form onsubmit={onSubmit}>
  <label>Name <input name="name" placeholder="Your name" required></label>
  <label>Email <input name="email" type="email" placeholder="you@example.com" required></label>
  <label>Message <textarea name="message" placeholder="How can we help?" required></textarea></label>
  <div aria-hidden="true" style="position:absolute;inset-inline-start:0;top:0;width:1px;height:1px;overflow:hidden;clip-path:inset(50%)">
    <input name="botcheck" tabindex="-1" autocomplete="off">
  </div>
  <button type="submit">Send</button>
  <p role="status">{status}</p>
</form>

Component package: npm install @formgong/svelte (npm: @formgong/svelte)

Add to an existing project: npx formgong init (npm: formgong)

Svelte or SvelteKit?

This page is for Svelte without SvelteKit. If your project uses SvelteKit, see the SvelteKit page: it explains why form actions do not work on prerendered pages.

Either way, Formgong replaces the server and email code you would otherwise write for a contact form.

Questions and answers

Does it work with Svelte 4?

Yes. Replace $state with let status = "" and onsubmit={onSubmit} with on:submit|preventDefault={onSubmit}.

Do I need a store or a library?

No. One component with fetch is enough.

Can I validate fields first?

Yes. Validate in the submit handler before calling fetch; the browser's own required and type="email" checks also apply.

Start free