How to Build a Contact Form for Your Website with Ease
A contact form is small at the UI layer, but the submission path still needs careful boundaries. The browser needs an accessible form and useful feedback; the server needs to validate the request and protect credentials; and the submitted data needs a durable home before anyone tries to send an email.
This guide uses a simple split: your website owns the visitor-facing form and a same-origin server route, while Dashier stores the submission as a record. A Dashier record.created email hook can then render a saved plain-text template and send it through Resend. The browser never sees either server credential.
The architecture
The request flow looks like this:
- The visitor submits name, email, subject, and message to
/api/contacton your website. - Your server route validates the JSON and forwards the expected fields to Dashier’s
POST /api/v1/{data-source-slug}endpoint. - Dashier validates the payload against the data-source schema, writes the record, and queues the
record.creatednotification. - The hook renders a plain-text template and sends it to its configured recipient through Resend.
Dashier provides the data source, record-management UI, REST API, and notification hook. It does not generate or host the public contact form. You write that small UI in the framework your site already uses. The current hook supports the record.created event and plain-text templates; it is not a general workflow engine and does not provide HTML templates or attachments.
What you need before starting
You need:
- A Dashier data source and permission to create a project API key and edit the source’s API policy.
- A server-rendered or server-routed website where secrets can remain on the server.
- A Resend account with a verified domain. Resend documents the setup in its verified domains guide.
The website and Dashier server have different responsibilities. The website uses a write-scoped Dashier key to create a record. The Dashier server uses RESENDAPIKEY and RESENDFROMEMAIL to send mail.
Model the submission in Dashier
Create a data source such as Contact submissions. Add the fields that your form will send, using stable keys:
name— textemail— emailsubject— textmessage— textarea
The keys are part of the contract. Dashier validates the incoming record against the source schema, and the notification template resolves variables using those same keys. Keeping the model small also limits how much personal information is stored and copied into email.
Protect the create endpoint
Create a project API key with the write scope. In the source’s API settings, enable POST and choose the Authenticated policy. Your website’s server route will send that key with the create request, normally in the x-api-key header.
Do not put the key in a NEXTPUBLIC variable, a browser bundle, or an HTML form. Avoid making the create endpoint public unless you have deliberately assessed anonymous access and added abuse controls. Dashier’s API has policy-level rate limiting, but a public website route still needs its own request throttling, size limits, and spam strategy.
Configure server-only environment variables
On the website deployment, set:
DASHIER_API_ORIGIN=https://your-dashier.example
DASHIER_CONTACT_API_KEY=your-write-scoped-key
On the Dashier server deployment, set:
RESEND_API_KEY=your-resend-key
RESEND_FROM_EMAIL=Website <notify@your-verified-domain.example>
RESENDFROMEMAIL must use a sender address on a verified Resend domain. Keep all four values out of source control. In local development, use the framework’s ignored environment file or a secret manager; in production, use the hosting provider’s server-side environment settings.
Create the plain-text template and hook
In the data source’s Email hooks area, create a plain-text template. A subject such as New website enquiry from {{name}} is enough. In the body, include only the fields the recipient needs, for example:
Name: {{name}}
Email: {{email}}
Subject: {{subject}}
{{message}}
Record: {{record.id}}
Template variables are checked against the source’s field keys. The implementation also supports source.name, source.slug, record.id, and record.created_at; an unknown token is rejected rather than silently producing an incomplete message. Rendered record values remain plain text, not HTML.
Create a hook for a new record, select the template, and enter the fixed inbox address. You can select the source’s email field as Reply-to, so replies go to the visitor while delivery still goes to the configured inbox. The recipient is a saved hook setting: the form payload cannot choose an arbitrary destination.
The hook requires both Resend server variables before it can send. If they are missing, the delivery is marked blocked and can be retried after configuration is fixed. Delivery history records status without copying the message text into the log. A successful record insert is not rolled back when notification delivery fails.
Build the visitor-facing form
The client component only talks to your own same-origin route. It has labels, native browser validation, and explicit sending, success, and error states:
"use client";
import { useState } from "react";
import type { FormEvent } from "react";
export function ContactForm() {
const [status, setStatus] = useState<"idle" | "sending" | "sent" | "error">("idle");
async function submit(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
setStatus("sending");
const form = event.currentTarget;
const values = Object.fromEntries(new FormData(form).entries());
try {
const response = await fetch("/api/contact", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(values),
});
if (!response.ok) throw new Error("Submission failed");
form.reset();
setStatus("sent");
} catch {
setStatus("error");
}
}
return (
<form onSubmit={submit}>
<label htmlFor="name">Name</label>
<input id="name" name="name" autoComplete="name" required maxLength={120} />
<label htmlFor="email">Email</label>
<input id="email" name="email" type="email" autoComplete="email" required maxLength={254} />
<label htmlFor="subject">Subject</label>
<input id="subject" name="subject" required maxLength={160} />
<label htmlFor="message">Message</label>
<textarea id="message" name="message" required maxLength={5000} rows={6} />
<button type="submit" disabled={status === "sending"}>
{status === "sending" ? "Sending…" : "Send message"}
</button>
{status === "sent" && <p role="status">Thanks. Your message has been received.</p>}
{status === "error" && <p role="alert">We could not submit your message. Please try again.</p>}
</form>
);
}
These limits improve the browser experience, but they are not a security boundary. A caller can bypass client-side validation, so the server route must validate again. Before exposing the form widely, add rate limiting and spam protection to your website route as well as the Dashier endpoint limits.
Validate and forward the request on the server
Create a POST handler at /api/contact. Parse unknown input safely, validate every field on the server, trim the values you forward, and return a generic error to the visitor when the upstream request fails. The Dashier API returns 201 after creating the record and 422 when the source validation fails.
This Next.js Route Handler is a complete example:
import { NextResponse } from "next/server";
function validEmail(value: unknown): value is string {
return typeof value === "string" && value.length <= 254 &&
/^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/.test(value);
}
export async function POST(request: Request) {
const body: unknown = await request.json().catch(() => null);
if (!body || typeof body !== "object" || Array.isArray(body)) {
return NextResponse.json({ error: "Invalid request." }, { status: 400 });
}
const input = body as Record<string, unknown>;
if (
typeof input.name !== "string" || !input.name.trim() || input.name.length > 120 ||
!validEmail(input.email) ||
typeof input.subject !== "string" || !input.subject.trim() || input.subject.length > 160 ||
typeof input.message !== "string" || !input.message.trim() || input.message.length > 5000
) {
return NextResponse.json({ error: "Check the form fields and try again." }, { status: 400 });
}
const origin = process.env.DASHIER_API_ORIGIN?.replace(/\/+$/, "");
const key = process.env.DASHIER_CONTACT_API_KEY;
if (!origin || !key) {
return NextResponse.json({ error: "Contact form is not configured." }, { status: 503 });
}
try {
const response = await fetch(`${origin}/api/v1/contact-submissions`, {
method: "POST",
headers: { "Content-Type": "application/json", "x-api-key": key },
body: JSON.stringify({
name: input.name.trim(),
email: input.email.trim(),
subject: input.subject.trim(),
message: input.message.trim(),
}),
cache: "no-store",
});
if (!response.ok) {
return NextResponse.json({ error: "We could not save your message." }, { status: 502 });
}
return NextResponse.json({ ok: true }, { status: 201 });
} catch {
return NextResponse.json({ error: "We could not save your message." }, { status: 502 });
}
}
contact-submissions is an illustrative source slug. Replace it with the slug in your project. Keep the API origin and key on the server, and do not log the submitted message or secret header. A production route may also need a timeout, structured request logging, and a gateway-level limiter, but those additions should not expose the visitor’s message or credentials.
Test the whole path
Start with one controlled submission and verify the boundaries in order:
- The website route rejects malformed JSON, missing fields, invalid email, and overlong values.
- Dashier creates a record with the expected field keys and returns a successful response.
- The Email hooks history shows the delivery status.
- Resend accepts the request from the verified sender and the destination mailbox receives it, including its spam folder.
- A failed email leaves the record in Dashier so it can be investigated or retried.
Also test a disabled hook, missing Resend settings, a sender-domain error, an invalid reply-to value, and an API request with a missing or wrong key. A 401 or 403 usually points to the key, write scope, POST setting, or endpoint policy; a validation response means the JSON does not match the source schema.
Automatic notification processing is bounded to 25 deliveries per request. The Email hooks processing route uses the same bound when retrying pending, failed, or blocked deliveries, so a large backlog is handled in batches. Each hook also has a rolling limit of 50 successful sends per hour. Resend requests include a stable Idempotency-Key for the delivery; that helps make retries safer, but it is not a permanent exactly-once guarantee.
A few rules worth keeping
- Keep the form on your site, but submit to a same-origin server route.
- Treat the data-source field keys as the contract between the form, API, and template.
- Keep Dashier and Resend credentials server-only.
- Use an authenticated, write-scoped create endpoint and add public-route abuse controls.
- Deliver to a fixed operator-configured inbox; use Reply-to for the visitor’s address.
- Keep the email plain text and include only the information the recipient needs.
- Test persistence, delivery, failure handling, and bounded retries separately.
For product-specific details, see Dashier’s API reference, notification guide, and integration guide. For sender setup, consult Resend’s verified domains documentation.
