How to add a contact form to a static site

Static sites have no server to receive a form. This guide adds a working contact form to plain HTML, Astro, Next.js static export and Hugo sites.

Static sites are fast and cheap to host, but the moment you need a contact form you hit a wall: there is no server to send the form to. The host delivers your files and does nothing else.

The fix is to send the form somewhere that can receive it. This guide builds one contact form that works with JavaScript switched off, improves it with a small script, and then shows how to place it in Astro, a Next.js static export and Hugo.

Why static sites cannot receive forms

A static site is a folder of files that were generated ahead of time. When a visitor requests a page, the host sends the matching file. No code runs on the server for that request.

A form submission is different. The browser sends the field values to the URL in the form's action attribute and expects a program at that URL to read them. On a static host there is no such program, so the request fails or returns the same page unchanged.

You have two choices: add server code somewhere, such as a serverless function you write and maintain, or point the form at a form backend, a hosted service that receives submissions for you. This guide uses FormDB as the form backend. Each form gets an endpoint like https://api.formdb.io/f/your-form-id, which you copy from the form's Setup tab after creating an account.

Start with a form that works without JavaScript

Progressive enhancement means building the basic version first, using features every browser supports, and adding improvements on top for browsers that can use them. For a form, the basic version is a plain HTML post.

<form id="contact-form" action="https://api.formdb.io/f/your-form-id" method="POST">
  <label for="name">Name</label>
  <input id="name" type="text" name="name" required>

  <label for="email">Email</label>
  <input id="email" type="email" name="email" required>

  <label for="message">Message</label>
  <textarea id="message" name="message" rows="6" required></textarea>

  <input type="text" name="_gotcha" tabindex="-1" autocomplete="off" style="display:none">

  <button type="submit">Send message</button>
  <p id="contact-status" role="status"></p>
</form>

This already works on any static host. The browser posts the fields to FormDB, the submission lands in your inbox, a notification email goes to the workspace owner, and the visitor sees a hosted thank-you page. To send visitors to your own thank-you page instead, set a redirect URL in the form settings.

The hidden _gotcha input is a honeypot: a field people never see but many spam bots fill in. FormDB drops any submission where it has a value.

Enhance the form with fetch

A full page navigation is fine, but staying on the page feels smoother. The script below intercepts the submit event and sends the same data with fetch, the browser's built-in function for HTTP requests.

const form = document.querySelector("#contact-form");
const statusLine = document.querySelector("#contact-status");

if (form && statusLine) {
  form.addEventListener("submit", async (event) => {
    event.preventDefault();

    const button = form.querySelector("button[type=submit]");
    button.disabled = true;
    statusLine.textContent = "Sending...";

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

      if (response.ok) {
        form.reset();
        statusLine.textContent = "Thanks, your message is on its way.";
      } else {
        statusLine.textContent = body.error.message;
      }
    } catch (err) {
      statusLine.textContent = "Could not reach the server. Please try again.";
    } finally {
      button.disabled = false;
    }
  });
}

Three things make this work:

  • Accept: application/json tells FormDB to reply with JSON instead of a page. Success is status 201 with {"ok":true,"id":"..."}. Failure is {"ok":false,"error":{"code":"...","message":"..."}}.
  • new FormData(form) collects every named field, including the honeypot. Do not set a Content-Type header yourself. The browser adds the correct one.
  • CORS is already handled. CORS (cross-origin resource sharing) is the browser rule that decides whether a script on one site may call another site. FormDB's endpoint allows these requests from any website.

If the script fails to load, or a visitor has JavaScript disabled, the form falls back to the plain post from the previous section. Nobody is locked out.

Plain HTML on any static host

Paste the form into your page and add the script before the closing </body> tag:

<script src="/contact-form.js" defer></script>

Save the JavaScript above as contact-form.js next to your HTML files. It works the same on any host that serves static files, because the only server involved is FormDB's.

Astro

In Astro, put the form in a component. Create src/components/ContactForm.astro with the form markup followed by a script tag:

<form id="contact-form" action="https://api.formdb.io/f/your-form-id" method="POST">
  <label for="name">Name</label>
  <input id="name" type="text" name="name" required>

  <label for="email">Email</label>
  <input id="email" type="email" name="email" required>

  <label for="message">Message</label>
  <textarea id="message" name="message" rows="6" required></textarea>

  <input type="text" name="_gotcha" tabindex="-1" autocomplete="off" style="display:none">

  <button type="submit">Send message</button>
  <p id="contact-status" role="status"></p>
</form>

<script>
  // Paste the fetch script from the previous section here.
</script>

Astro bundles the contents of a <script> tag in a component and loads it on pages that use the component. No UI framework is needed. Import the component in a page and use it as <ContactForm />.

Next.js static export

With output: "export" in your Next.js configuration, the site is built to static files and there is no server at runtime, so server-side form handling is not available. A client component that posts to FormDB works well.

"use client";

import { useState } from "react";

const ENDPOINT = "https://api.formdb.io/f/your-form-id";

export default function ContactForm() {
  const [state, setState] = useState("idle");
  const [message, setMessage] = useState("");

  async function handleSubmit(event) {
    event.preventDefault();
    const form = event.currentTarget;
    setState("sending");
    setMessage("");

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

      if (response.ok) {
        form.reset();
        setMessage("Thanks, your message is on its way.");
      } else {
        setMessage(body.error.message);
      }
    } catch (err) {
      setMessage("Could not reach the server. Please try again.");
    } finally {
      setState("idle");
    }
  }

  return (
    <form action={ENDPOINT} method="POST" onSubmit={handleSubmit}>
      <label htmlFor="name">Name</label>
      <input id="name" type="text" name="name" required />

      <label htmlFor="email">Email</label>
      <input id="email" type="email" name="email" required />

      <label htmlFor="message">Message</label>
      <textarea id="message" name="message" rows={6} required />

      <input
        type="text"
        name="_gotcha"
        tabIndex={-1}
        autoComplete="off"
        style={{ display: "none" }}
      />

      <button type="submit" disabled={state === "sending"}>
        Send message
      </button>
      <p role="status">{message}</p>
    </form>
  );
}

Keeping action and method on the form matters here too. The exported HTML contains them, so the form can be submitted even before React has finished loading in the browser.

Hugo

Hugo's Markdown renderer leaves out raw HTML by default, so pasting a form into a content file often produces nothing. A shortcode avoids the problem. Save the form markup from the first section as layouts/shortcodes/contact-form.html, then use it in any content file:

{{< contact-form >}}

Put the fetch script in static/contact-form.js and load it from your base template with a <script src="/contact-form.js" defer></script> tag.

Before you publish

  • Test with JavaScript off. Disable it in your browser's developer tools and submit once. You should see the hosted thank-you page or your redirect.
  • Test a failure. Change the form id in the action to one that does not exist and submit. The message "This form does not exist." should appear under the form. The JavaScript and AJAX guide covers the error format.
  • Know your limits. The Free plan accepts 250 submissions a month and keeps them for 30 days. Paid plans start at 2,500 a month with unlimited retention. See pricing.
  • Plan for spam. The honeypot handles basic bots. For more, see how to stop contact form spam.

Next steps

The quickstart covers creating your first form and endpoint, and HTML forms lists what the endpoint accepts. When you are ready to wire up your own site, create a free account and replace your-form-id in the examples above.

Your form can be livebefore your coffee is cold.

Create a form, paste one URL and send yourself a test. The Free plan covers 250 submissions a month, with no credit card required.