Use Submitry with Astro
This page gives you an Astro component for a contact form. It posts to your Submitry Worker, shows errors next to the right field, and still works without JavaScript.
Submitry has no special attributes: the action address and the name of each field are all it needs. See Add your first form for the background.
What you need first
Section titled “What you need first”- A client site and a form in the admin screen. Open the form’s Embed tab and note the form address.
- Form settings with the fields
name,email(type email) andmessagerequired, and the honeypotwebsite. After you add the component you can use Import from HTML to read the fields. - For Turnstile: a free site key from the Cloudflare dashboard, and the matching secret saved as a Turnstile connection in Submitry.
1. Add the component
Section titled “1. Add the component”Save this as src/components/ContactForm.astro.
---/** * Submitry contact form for Astro. Copy this file into src/components/. * * Usage: * <ContactForm action="https://YOUR_WORKER/f/FORM_ID" turnstileSiteKey="YOUR_SITE_KEY" /> * * Form settings in Submitry: fields name, email (type email) and message are required, honeypot "website". * Without JavaScript the browser posts the form and Submitry redirects to your thank-you page. * With JavaScript the script below sends it with fetch and shows the answer on the page. */interface Props { /** The form address from the Submitry admin screen (Embed tab). */ action: string /** Cloudflare Turnstile site key. Leave out if the form does not use Turnstile. */ turnstileSiteKey?: string /** Must match "honeypot" in the form settings. */ honeypot?: string submitLabel?: string /** Prefix for field ids, so two forms on one page do not clash. */ idPrefix?: string}
const { action, turnstileSiteKey, honeypot = 'website', submitLabel = 'Send message', idPrefix = 'contact',} = Astro.props---
<form class="contact-form" action={action} method="post" data-submitry> <div class="contact-form__field"> <label class="contact-form__label" for={`${idPrefix}-name`}>Name</label> <input class="contact-form__input" id={`${idPrefix}-name`} name="name" type="text" autocomplete="name" required /> <p class="contact-form__error" id={`${idPrefix}-name-error`} hidden></p> </div>
<div class="contact-form__field"> <label class="contact-form__label" for={`${idPrefix}-email`}>Email</label> <input class="contact-form__input" id={`${idPrefix}-email`} name="email" type="email" autocomplete="email" required /> <p class="contact-form__error" id={`${idPrefix}-email-error`} hidden></p> </div>
<div class="contact-form__field"> <label class="contact-form__label" for={`${idPrefix}-message`}>Message</label> <textarea class="contact-form__input contact-form__input--area" id={`${idPrefix}-message`} name="message" rows="6" required></textarea> <p class="contact-form__error" id={`${idPrefix}-message-error`} hidden></p> </div>
<div class="contact-form__trap" aria-hidden="true"> <label for={`${idPrefix}-${honeypot}`}>Leave this field empty</label> <input id={`${idPrefix}-${honeypot}`} name={honeypot} type="text" tabindex="-1" autocomplete="off" /> </div>
{ turnstileSiteKey && ( <> <script is:inline src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer /> <div class="cf-turnstile contact-form__turnstile" data-sitekey={turnstileSiteKey} /> </> ) }
<button class="contact-form__button" type="submit">{submitLabel}</button>
<p class="contact-form__status" role="status" aria-live="polite" data-submitry-status></p></form>
<style is:global> .contact-form { --contact-form-gap: 1rem; --contact-form-border: currentColor; --contact-form-error: #b00020; --contact-form-focus: Highlight; display: grid; gap: var(--contact-form-gap); max-width: 36rem; } .contact-form__field { display: grid; gap: 0.35rem; } .contact-form__label { font-weight: 600; } .contact-form__input { width: 100%; padding: 0.65rem 0.8rem; border: 1px solid var(--contact-form-border); border-radius: 0.25rem; background: transparent; color: inherit; font: inherit; } .contact-form__input--area { resize: vertical; } .contact-form__input:focus-visible, .contact-form__button:focus-visible { outline: 3px solid var(--contact-form-focus); outline-offset: 2px; } .contact-form__input[aria-invalid='true'] { border-color: var(--contact-form-error); } .contact-form__error, .contact-form__status--error { color: var(--contact-form-error); } .contact-form__error, .contact-form__status { margin: 0; font-size: 0.95rem; } /* Hidden from people but still in the DOM, so bots fill it. Do not use display: none. */ .contact-form__trap { position: absolute; left: -9999px; width: 1px; height: 1px; overflow: hidden; } .contact-form__button { justify-self: start; padding: 0.7rem 1.4rem; border: 0; border-radius: 0.25rem; background: CanvasText; color: Canvas; font: inherit; font-weight: 600; cursor: pointer; } .contact-form__button:disabled { opacity: 0.6; cursor: progress; }</style>
<script> const reasons: Record<string, string> = { required: 'This field is required.', invalid_email: 'Enter a valid email address.', too_long: 'This is too long.', }
declare global { interface Window { turnstile?: { reset: () => void } } }
interface SubmitryAnswer { ok?: boolean code?: string message?: string fields?: Record<string, string> }
document.querySelectorAll<HTMLFormElement>('form[data-submitry]').forEach((form) => { const status = form.querySelector<HTMLElement>('[data-submitry-status]')! const button = form.querySelector<HTMLButtonElement>('button[type="submit"]')!
const clear = () => { status.textContent = '' status.classList.remove('contact-form__status--error') form.querySelectorAll('[aria-invalid]').forEach((el) => { el.removeAttribute('aria-invalid') el.removeAttribute('aria-describedby') }) form.querySelectorAll<HTMLElement>('.contact-form__error').forEach((el) => { el.hidden = true el.textContent = '' }) }
const showFieldErrors = (fields: Record<string, string>) => { let first: HTMLElement | null = null for (const [name, reason] of Object.entries(fields)) { const input = form.elements.namedItem(name) if (!(input instanceof HTMLElement) || !input.id) continue const note = document.getElementById(`${input.id}-error`) if (!note) continue note.textContent = reasons[reason] ?? 'Check this field.' note.hidden = false input.setAttribute('aria-invalid', 'true') input.setAttribute('aria-describedby', note.id) first ??= input } first?.focus() }
form.addEventListener('submit', async (event) => { event.preventDefault() clear() button.disabled = true status.textContent = 'Sending...' try { const response = await fetch(form.action, { method: 'POST', headers: { Accept: 'application/json' }, body: new FormData(form), }) const result: SubmitryAnswer = await response.json() if (response.ok) { status.textContent = result.message ?? 'Thank you. Your message was sent.' form.reset() } else if (result.fields) { showFieldErrors(result.fields) status.textContent = 'Please check the highlighted fields.' status.classList.add('contact-form__status--error') } else { status.textContent = result.message ?? 'Something went wrong. Please try again.' status.classList.add('contact-form__status--error') } } catch { status.textContent = 'Could not reach the server. Please try again.' status.classList.add('contact-form__status--error') } finally { window.turnstile?.reset() button.disabled = false } }) })</script>2. Use it on a page
Section titled “2. Use it on a page”---import ContactForm from '../components/ContactForm.astro'---
<ContactForm action="https://YOUR_WORKER/f/FORM_ID" turnstileSiteKey="YOUR_TURNSTILE_SITE_KEY"/>Leave out turnstileSiteKey if the form does not use Turnstile. If you put two forms on one page, give the second a different idPrefix so the field ids do not clash.
Styling
Section titled “Styling”The component ships with plain BEM styles (contact-form__input and so on). The values at the top of .contact-form are custom properties, so you can point them at your own design tokens, or delete the <style> block and write your own.
Without JavaScript
Section titled “Without JavaScript”If the script does not run, the browser posts the form normally. Submitry then sends the visitor to the successRedirect page you set in the form settings, so set one.