Formpost

Framework guides

Astro

A static island that posts to the endpoint.

Astro ships zero JavaScript by default, which suits a plain form post perfectly. Add a script only if you want to stay on the page after submitting.

src/pages/contact.astro
---
const accessKey = import.meta.env.PUBLIC_CONTACT_KEY;
---

<form action="https://api.formpost.ai/submit" method="POST" id="contact">
  <input type="hidden" name="access_key" value={accessKey} />
  <input type="text" name="name" required />
  <input type="email" name="email" required />
  <textarea name="message" required></textarea>
  <input type="checkbox" name="botcheck" style="display:none" tabindex="-1" autocomplete="off" />
  <button type="submit">Send</button>
</form>

<script>
  // Without the type parameter this is an Element and .action fails to compile
  const form = document.querySelector<HTMLFormElement>("#contact");

  form?.addEventListener("submit", async (event) => {
    event.preventDefault();

    const res = await fetch(form.action, {
      method: "POST",
      headers: { Accept: "application/json" },
      body: new FormData(form),
    });

    if ((await res.json()).success) form.reset();
  });
</script>