An Astro contact form needs three pieces: an HTML form, an Astro Action that validates the input on the server, and an email API call inside that action. The API key lives in a server secret, the form works without JavaScript, and the rest of your site can stay static. This guide uses current Astro (Actions, astro:env and Zod 4 from astro/zod) and sends through Mailcandor; any email API works the same way.
Before you start: an adapter and on-demand rendering
Actions run on the server, so your project needs an adapter for wherever you host it, for example:
npx astro add node # or vercel, netlify, cloudflare
Pages are still prerendered by default. Only the contact page needs on-demand rendering, because Astro’s docs state that pages must be rendered on demand when calling actions with a form action. You will set that on the page below.
Step 1: declare the API key as a secret
// astro.config.mjs
import { defineConfig, envField } from 'astro/config';
import node from '@astrojs/node';
export default defineConfig({
adapter: node({ mode: 'standalone' }),
env: {
schema: {
MAILCANDOR_KEY: envField.string({ context: 'server', access: 'secret' }),
},
},
});
Set MAILCANDOR_KEY in .env for development and in your host’s environment variables in production. A server secret is read at runtime and can only be imported in server code from astro:env/server. Avoid import.meta.env for secrets: Vite replaces those values at build time, as the Astro environment variables docs explain.
Step 2: define the action
// src/actions/index.ts
import { defineAction, ActionError } from 'astro:actions';
import { z } from 'astro/zod';
import { MAILCANDOR_KEY } from 'astro:env/server';
export const server = {
contact: defineAction({
accept: 'form',
input: z.object({
name: z.string().max(100).optional(),
email: z.email(),
message: z.string().min(1).max(5000),
website: z.string().max(0).optional(), // honeypot: must stay empty
}),
handler: async ({ name, email, message }) => {
const res = await fetch('https://api.mailcandor.com/v1/emails', {
method: 'POST',
headers: {
Authorization: `Bearer ${MAILCANDOR_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
from: 'Acme website <hello@acme.com>',
to: 'team@acme.com',
reply_to: email,
subject: `Contact form: ${name || email}`,
text: message,
}),
});
if (!res.ok) {
const { error } = await res.json();
console.error('email failed', error.type, error.message);
throw new ActionError({ code: 'INTERNAL_SERVER_ERROR', message: 'Could not send your message.' });
}
return { sent: true };
},
}),
};
Notes on the action:
accept: 'form'tells Astro to parseFormDataand validate it against the Zod schema before your handler runs. Invalid input never reaches the handler.z.email()is the Zod 4 way to validate an address. Astro 6 and later ship Zod 4.- The hidden
websitefield is a honeypot. Bots fill every input; people never see it. A filled value fails validation. - The email goes to your team with the visitor in
reply_to, so the form cannot be used to send mail to anyone else.
Step 3: the contact page
---
// src/pages/contact.astro
export const prerender = false;
import { actions, isInputError } from 'astro:actions';
const result = Astro.getActionResult(actions.contact);
const error = result?.error;
const inputErrors = isInputError(error) ? error.fields : {};
---
{result?.data?.sent ? (
<p>Thanks, we will reply soon.</p>
) : (
<form method="POST" action={actions.contact}>
<label>Name <input name="name" autocomplete="name" /></label>
<label>Email <input name="email" type="email" required autocomplete="email" /></label>
{inputErrors.email && <p>Please enter a valid email address.</p>}
<label>Message <textarea name="message" required></textarea></label>
{inputErrors.message && <p>Please add a message.</p>}
<input name="website" tabindex="-1" autocomplete="off" hidden />
{error && !isInputError(error) && <p>{error.message}</p>}
<button>Send</button>
</form>
)}
When the form is posted, Astro runs the action and renders the page again. Astro.getActionResult returns data on success, error on failure, or undefined if the action was not called on this request. isInputError separates validation errors, with per-field messages, from errors thrown in the handler.
For a no-reload experience, you can also call the action from a client script with await actions.contact(new FormData(form)), which returns the same { data, error } shape.
Option for static hosting: a separate function
If you want no on-demand pages at all, keep the form static and point its action at a serverless function on your host, such as a Vercel Function or a Cloudflare Worker. The function runs the same fetch call and redirects back to a thank-you page. See sending email from Vercel or from Cloudflare Workers for that code.
Should you email the visitor a copy?
It is tempting to send the visitor a “we got your message” email. Be careful: anyone can type someone else’s address into a public form, so an auto-reply turns your form into a way to send unwanted mail from your domain, and the complaints count against your sender reputation. If you do send one, keep it short, include none of the submitted text, add a CAPTCHA, and rate limit by IP address. Showing a clear thank-you message on the page is usually enough.
Make it reliable
- Test with a real inbox. Submit the form, check the email arrives and that replying goes to the visitor.
- Log failures. The API returns
{"error": {"type", "message", "field"}}. Keep that in your server logs, not on the page. - Rate limit the route if your host supports it. A contact form is a public endpoint, and each submission costs one email.
Before you send: verify your domain
The from address must be on a domain you have verified with your email provider, with SPF, DKIM and DMARC records published. Without them, your own contact form messages can end up in your spam folder. The SPF, DKIM and DMARC setup guide shows how.
Sending with Mailcandor
The action above works with Mailcandor’s email API as written, with no SDK to install. The free Starter plan includes 3,000 emails a month and 100 a day, which covers most contact forms. Access is by request through the pricing page.