A static Astro site can’t process a form on its own, because there’s no server to receive the POST. To add an Astro contact form, point the form at something that can: a hosted form service (Formspree, Web3Forms and similar), your host’s built-in forms (Netlify Forms), a serverless function next to the site (a Cloudflare Pages Function), or an Astro Action on a single on-demand route with an adapter.
This guide shows working code for each option, how to add spam protection, and how to choose between them.
Key Takeaways
- The HTML form is the same in every approach; only the
actionURL and the receiver change.- A form service is the fastest setup and keeps the site 100% static.
- Netlify Forms needs only an attribute, but ties the form to Netlify hosting.
- A Pages Function or Astro Action keeps data in your own code and lets you send email however you like.
- Add a honeypot field on day one and a challenge like Turnstile if spam continues.
The form markup every option shares
Start with a plain, accessible form. It works without JavaScript, which matters for reliability and for anyone on a slow connection.
---
// src/components/ContactForm.astro
interface Props {
action: string;
}
const { action } = Astro.props;
---
<form method="POST" action={action} class="contact-form">
<label for="name">Name</label>
<input id="name" name="name" type="text" autocomplete="name" required />
<label for="email">Email</label>
<input id="email" name="email" type="email" autocomplete="email" required />
<label for="message">Message</label>
<textarea id="message" name="message" rows="6" required></textarea>
<!-- Honeypot: hidden from people, filled in by bots -->
<div hidden>
<label for="company">Company</label>
<input id="company" name="company" type="text" tabindex="-1" autocomplete="off" />
</div>
<button type="submit">Send message</button>
</form>
Every field has a visible <label>, required gives free browser validation, and autocomplete helps people fill the form quickly. The company input is a honeypot: real visitors never see it, so any submission that fills it in can be discarded.
Option 1: A hosted form service
Form services give you an endpoint URL. The browser posts to it directly, the service stores the submission and emails it to you, then redirects back to your site.
---
// src/pages/contact.astro
import BaseLayout from '../layouts/BaseLayout.astro';
import ContactForm from '../components/ContactForm.astro';
---
<BaseLayout title="Contact" description="Get in touch with Example Studio.">
<h1>Contact us</h1>
<ContactForm action="https://formspree.io/f/your-form-id" />
</BaseLayout>
Most services let you set a redirect to your own thank-you page, such as /contact/thanks/, either in their dashboard or through a hidden field; check your provider’s docs for the exact name. Create that page as a normal static Astro page.
Pros: no code to maintain, works on any static host including GitHub Pages, includes spam filtering and a dashboard. Cons: form data goes to a third party, free tiers cap monthly submissions, and branding or features may be limited until you pay.
Option 2: Netlify Forms
If the site is on Netlify, Netlify can detect forms in your built HTML and collect submissions itself. Add a name and the data-netlify attribute, plus a hidden form-name field:
---
// src/pages/contact.astro
import BaseLayout from '../layouts/BaseLayout.astro';
---
<BaseLayout title="Contact" description="Get in touch with Example Studio.">
<h1>Contact us</h1>
<form name="contact" method="POST" action="/contact/thanks/" data-netlify="true" netlify-honeypot="company">
<input type="hidden" name="form-name" value="contact" />
<label for="name">Name</label>
<input id="name" name="name" type="text" required />
<label for="email">Email</label>
<input id="email" name="email" type="email" required />
<label for="message">Message</label>
<textarea id="message" name="message" rows="6" required></textarea>
<p hidden><label>Company <input name="company" /></label></p>
<button type="submit">Send message</button>
</form>
</BaseLayout>
Netlify scans the deployed HTML, so the form must exist in static output (it does here, because the page is prerendered). Enable form detection in the site’s settings if it isn’t on. netlify-honeypot tells Netlify which field to treat as a honeypot. Submissions appear in the Netlify dashboard and can trigger email notifications.
Pros: one attribute, no third-party account, spam filtering included. Cons: only works on Netlify, and usage beyond the free allowance is billed.
Option 3: A Cloudflare Pages Function
On Cloudflare Pages, a file in functions/ becomes a serverless endpoint deployed with your static site. Your Astro build stays static, and the function handles only the POST.
// functions/api/contact.ts
interface Env {
RESEND_API_KEY: string;
CONTACT_TO: string;
}
export const onRequestPost: PagesFunction<Env> = async ({ request, env }) => {
const form = await request.formData();
if (form.get('company')) {
return Response.redirect(new URL('/contact/thanks/', request.url), 303);
}
const name = String(form.get('name') ?? '').trim();
const email = String(form.get('email') ?? '').trim();
const message = String(form.get('message') ?? '').trim();
if (!name || !email.includes('@') || message.length < 10) {
return new Response('Please fill in every field.', { status: 400 });
}
const res = await fetch('https://api.resend.com/emails', {
method: 'POST',
headers: {
Authorization: `Bearer ${env.RESEND_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
from: 'Website <[email protected]>',
to: env.CONTACT_TO,
reply_to: email,
subject: `Contact form: ${name}`,
text: message,
}),
});
if (!res.ok) {
return new Response('Could not send your message. Please try again.', { status: 502 });
}
return Response.redirect(new URL('/contact/thanks/', request.url), 303);
};
Then use <ContactForm action="/api/contact" />. The functions/ folder sits at the project root (not in src/), and Cloudflare deploys it alongside the dist/ output. Set RESEND_API_KEY and CONTACT_TO as secrets in the Pages project settings. Any transactional email API works the same way; Resend is just a short example. The Cloudflare Pages docs cover the project setup, and Cloudflare’s Pages Functions reference explains routing.
Netlify Functions and Vercel Functions follow the same pattern with their own file locations and handler signatures.
Pros: you own the data and the email flow, generous free tiers, no Astro adapter needed. Cons: you write and maintain validation, and the function is tied to that host’s API.
Option 4: Astro Actions on one on-demand route
If you want the form handled inside your Astro code with type-safe validation, use an Astro Action. Actions need an adapter, but the rest of the site can stay static: only the routes that call the action need on-demand rendering.
// src/actions/index.ts
import { defineAction, ActionError } from 'astro:actions';
import { z } from 'astro/zod';
export const server = {
contact: defineAction({
accept: 'form',
input: z.object({
name: z.string().min(1),
email: z.email(),
message: z.string().min(10),
company: z.string().optional(),
}),
handler: async ({ name, email, message, company }) => {
if (company) return { ok: true };
const sent = await sendEmail({ name, email, message });
if (!sent) {
throw new ActionError({ code: 'INTERNAL_SERVER_ERROR', message: 'Email failed' });
}
return { ok: true };
},
}),
};
---
// src/pages/contact.astro
import { actions, isInputError } from 'astro:actions';
export const prerender = false;
const result = Astro.getActionResult(actions.contact);
const fieldErrors = isInputError(result?.error) ? result.error.fields : {};
---
{result?.data?.ok && <p role="status">Thanks, we'll reply soon.</p>}
<form method="POST" action={actions.contact}>
<input name="name" required />
{fieldErrors.name && <p>{fieldErrors.name.join(', ')}</p>}
<input name="email" type="email" required />
<textarea name="message" required></textarea>
<button>Send</button>
</form>
sendEmail stands in for your email provider’s API call. The full walkthrough, including client-side submission, is in the Astro Actions guide. Without an adapter, the build stops with “Actions must be used with server output”; see the fix for that error.
Pros: typed validation with Zod, field-level errors, all in one codebase, works on any adapter host. Cons: needs an adapter and a host that runs server code.
Choosing an Astro contact form approach
| Form service | Netlify Forms | Pages Function | Astro Action | |
|---|---|---|---|---|
| Site stays fully static | Yes | Yes | Yes | No (one route on demand) |
| Works on GitHub Pages | Yes | No | No | No |
| Code to maintain | None | None | One function | One action |
| Data stays with you | No | Netlify | Yes | Yes |
| Field-level validation | Provider’s | Basic | Your code | Zod schema |
| Setup time | Minutes | Minutes | An hour | An hour |
Choose a form service if you want it working today on any host. Choose Netlify Forms if you already deploy to Netlify. Choose a Pages Function (or Netlify/Vercel Functions) if you want ownership without adding an Astro adapter. Choose Astro Actions if the site already uses an adapter or will need other server features.
Spam protection that works
- Honeypot field. Catches most automated submissions at zero cost to real visitors. All four examples above include one.
- Server-side validation. Never trust browser
requiredalone; check lengths and email shape on the receiver. - A challenge widget. Cloudflare Turnstile, hCaptcha or a provider’s built-in check adds a token that the receiver verifies. Turnstile is invisible for most visitors.
- Rate limiting. On Cloudflare, a WAF rate-limiting rule on
/api/contactstops floods before your code runs.
Improving the experience with JavaScript
A plain POST and redirect is reliable. To keep visitors on the page, intercept the submit and send the form with fetch, falling back to the normal POST if JavaScript fails:
<script>
// src/components/ContactForm.astro (script)
const form = document.querySelector<HTMLFormElement>('.contact-form');
form?.addEventListener('submit', async (event) => {
event.preventDefault();
const res = await fetch(form.action, {
method: 'POST',
body: new FormData(form),
headers: { Accept: 'application/json' },
});
form.outerHTML = res.ok
? '<p role="status">Thanks, your message was sent.</p>'
: '<p role="alert">Something went wrong. Please email us instead.</p>';
});
</script>
Astro bundles and loads this script without any framework. The same approach powers the newsletter signup tip.
Komal themes ship contact pages as static HTML forms with no backend, so you connect them to any of these options by changing the action. Browse Astro themes for sites with contact, quote and booking forms already designed.
FAQ
Can a static Astro site have a contact form?
Yes. The form is plain HTML, so it renders in a static build. The submission goes to a form service, your host’s form handling, a serverless function or an Astro Action on one on-demand route, any of which can store or email the message.
How do I send email from an Astro contact form?
Post the form to server code (a Pages Function, a Netlify or Vercel Function, or an Astro Action) and call a transactional email API from there with a secret key. Never call an email API from browser JavaScript, because the key would be public.
Does Netlify Forms work with Astro?
Yes, as long as the form is in the static HTML Netlify deploys. Add name, data-netlify="true" and a hidden form-name input, and enable form detection in the site settings.
Do Astro Actions work on a static site?
Not on a fully static site. Actions need an adapter and run on routes rendered on demand. You can keep every other page static and set export const prerender = false only on the contact page.
How do I stop spam on my Astro contact form?
Start with a hidden honeypot field and server-side validation. If spam continues, add Cloudflare Turnstile or another challenge and verify its token on the server before sending the message.