Every website eventually needs a contact form. It sounds trivial — a text box, a send button, done. But the moment you try to actually deliver that email, you hit a wall: you need a server. Something has to receive the POST request, validate the input, talk to an email provider, and return a response. For a static site, that means running a process somewhere, paying for it, keeping it updated, and hoping it stays up.
This post documents how opHUB’s contact form works. The site is served entirely from Cloudflare Pages — no origin server. The contact form is handled by a single JavaScript file living inside the functions/ directory, deployed automatically as a Cloudflare Pages Function. Email delivery goes through Brevo (formerly Sendinblue), which has a generous free tier and a clean REST API.
The result is a contact form that costs nothing to run, scales to zero between submissions, and requires no infrastructure to maintain.
How the pieces fit together
Before diving into code, it helps to see the full picture. There are three hops between a visitor hitting “Send” and the message arriving in your inbox.
# send
Browser → Cloudflare Pages Function → Brevo API → Send (MX)
# recive
MX → Cloudflare Mail Router → MX → Your inbox
The browser first sends a CORS preflight (OPTIONS) — an automatic browser safety check before any cross-origin POST. The Function responds with the right headers, and the browser proceeds with the actual request. The Function validates the input, calls Brevo’s SMTP API, and returns a JSON response the frontend can act on.
One detail worth highlighting: Cloudflare Pages routes requests to functions/api/contact.js automatically based on the file path. No routing config, no framework. Drop the file in the right place and it just works.
Setting up Brevo
Before writing any code, you need two things from Brevo:
A verified sender address. Brevo won’t send email from an address you haven’t proved you own. Go to Settings → Senders & IPs → Add a new sender and complete the verification. This is the address your contact emails will appear to come from.
An API key. Go to Settings → API Keys → Generate a new API key. You only need the default permissions. Store this somewhere safe — you’ll need it in a moment.
The HTML form
The form itself is standard HTML. The only non-obvious part is the honeypot — a hidden input that real users never see, but bots filling forms programmatically often do:
<form id="contactForm" action="/api/contact" method="POST">
<input type="text" name="name" placeholder="Your name" required>
<input type="email" name="email" placeholder="Your email" required>
<textarea name="message" placeholder="Your message" required></textarea>
<!-- Honeypot: hidden via CSS, never filled by real users -->
<input type="text" name="website" tabindex="-1" autocomplete="off"
style="display:none">
<button type="submit">Send</button>
</form>
For a smoother experience, intercept the submit event with JavaScript so the page doesn’t reload on send:
form.addEventListener('submit', async (e) => {
e.preventDefault();
const response = await fetch('/api/contact', {
method: 'POST',
body: new FormData(form) // sends as multipart/form-data
});
const result = await response.json();
if (result.ok && result.sent) {
// show success message
} else {
// show field-level errors from result.error
}
});
FormData is the path of least resistance here. It picks up all named inputs automatically, including the honeypot field, and the Worker knows how to parse it.
The Cloudflare Pages Function
Create functions/api/contact.js at the root of your repository. Cloudflare discovers this automatically and routes /api/contact to it — no explicit configuration needed.
your-site/
├── dist/ ← your built static output
├── functions/
│ └── api/
│ └── contact.js ← handles /api/contact
└── wrangler.toml
The Function exports a single onRequest handler that receives the full request context:
export async function onRequest(context) {
const { request, env } = context;
const origin = request.headers.get("Origin");
const allowedOrigins = env.ALLOWED_ORIGINS.split(',').map(o => o.trim());
if (request.method === "OPTIONS") return handlePreflight(origin, allowedOrigins);
if (request.method === "GET") return handleHealthCheck(env, origin, allowedOrigins);
if (request.method !== "POST") return methodNotAllowed();
return handlePost(request, env, origin, allowedOrigins);
}
How requests are handled
The Worker branches on method early, before doing any real work:
OPTIONS → CORS preflight response
GET → health check JSON
POST → origin check → honeypot check → validation → Brevo API
other → 405 Method Not Allowed
CORS: why it matters here
Because the form submits to /api/contact on the same domain, you might wonder why CORS is relevant at all. Same-origin requests don’t trigger preflight. But it’s worth handling it anyway — if you ever embed the form on a staging domain or test locally on a different port, the missing headers will cause mysterious failures with no useful error message.
The key detail is Vary: Origin. Without it, a CDN or shared cache might serve one user’s CORS response to a different origin:
function handlePreflight(origin, allowedOrigins) {
const headers = {
"Vary": "Origin",
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type",
};
if (allowedOrigins.includes(origin)) {
headers["Access-Control-Allow-Origin"] = origin;
}
return new Response(null, { status: 200, headers });
}
Parsing the request body
The Worker accepts both application/json and multipart/form-data. This flexibility means you can test the endpoint with curl using JSON without touching the frontend:
async function readBody(request) {
const ct = request.headers.get("content-type") || "";
if (ct.includes("application/json")) {
return request.json();
}
if (ct.includes("form")) {
const fd = await request.formData();
return Object.fromEntries(fd.entries());
}
throw new Error("Unsupported content type");
}
Sanitizing input
Before doing anything with user-supplied strings, strip control characters and trim whitespace. Control characters (null bytes, carriage returns, etc.) can cause subtle problems downstream — in log parsers, email headers, or databases — and there is no reason to let them through:
function sanitize(v) {
return (v ?? "").toString()
.replace(/[\u0000-\u001F\u007F]/g, "") // strip control characters
.trim();
}
This is intentionally lightweight. The content ends up in an email body, not rendered back into a web page, so HTML-escaping output is less critical here. If you were storing submissions in a database or displaying them anywhere, you would want a more thorough pass.
The honeypot
A real user never sees or fills the website field — it’s hidden with CSS. Bots filling forms programmatically often populate every visible field, including hidden ones. Rather than returning an error (which tells the bot it was detected and needs to adapt), return a fake success:
const honeypot = (body.website || "").toString().trim();
if (honeypot) {
return new Response(
JSON.stringify({ ok: true, sent: true }),
{ status: 200, headers }
);
}
This technique is sometimes called “silent drop.” The bot thinks it succeeded. It moves on. No arms race.
Validation
After sanitization and bot filtering, check that the required fields are present and that the email address is plausible:
if (!name || !email || !message) {
return new Response(
JSON.stringify({ ok: false, error: "Missing required fields" }),
{ status: 400, headers }
);
}
if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) {
return new Response(
JSON.stringify({ ok: false, error: "Invalid email" }),
{ status: 400, headers }
);
}
The regex is deliberately simple — one @, something before and after, a dot somewhere in the domain. Full RFC 5321 compliance is not the goal; catching obvious typos is.
Sending via Brevo
Brevo’s transactional email endpoint is POST /v3/smtp/email. Authentication uses the api-key header rather than the more common Authorization: Bearer pattern — something that trips people up the first time:
const payload = {
sender: { email: env.BREVO_EMAIL_SENDER, name: "Website Contact" },
replyTo: { email, name }, // reply goes to the visitor
to: [{ email: env.BREVO_EMAIL_RECIPIENT }],
subject: `New contact from ${name}`,
htmlContent: `<p><strong>${name}</strong> <${email}></p>
<p>${message.replace(/\n/g, "<br>")}</p>`,
textContent: `From: ${name} <${email}>\n\n${message}`,
};
const brevoRes = await fetch("https://api.brevo.com/v3/smtp/email", {
method: "POST",
headers: {
"api-key": env.BREVO_API_KEY,
"content-type": "application/json",
},
body: JSON.stringify(payload),
});
Setting replyTo to the visitor’s address is the most important usability detail in this entire setup. Without it, hitting Reply in your mail client sends back to your own sender address — and you have to manually copy the visitor’s email from the body. With replyTo, the thread starts naturally.
Environment variables
The Worker reads four values from its environment:
| Variable | Purpose |
|---|---|
BREVO_API_KEY | Your Brevo API key |
BREVO_EMAIL_SENDER | Verified sender address in Brevo |
BREVO_EMAIL_RECIPIENT | Where contact messages are delivered |
ALLOWED_ORIGINS | Comma-separated list of allowed request origins |
Local development with Wrangler
Wrangler reads secrets from a .dev.vars file in the project root. This file should never be committed — add it to .gitignore and keep a .dev.vars.example with placeholder values instead:
BREVO_API_KEY=xkeysib-...
BREVO_EMAIL_SENDER=hello@yourdomain.com
BREVO_EMAIL_RECIPIENT=inbox@yourdomain.com
ALLOWED_ORIGINS=https://yourdomain.com,http://localhost:8787
Build your site, then serve the output with Wrangler:
npx wrangler pages dev ./dist --port 8787
Production
Set the same variables in the Cloudflare dashboard under Pages → your project → Settings → Environment variables. Mark BREVO_API_KEY as encrypted so it is redacted in logs and not exposed through the dashboard API.
The health check
The GET handler on the same endpoint serves as a lightweight health check. It validates that all environment variables are present and makes a real API call to Brevo to confirm the key is valid — without sending any email:
curl https://yourdomain.com/api/contact
{
"status": "ok",
"brevo": {
"configured": true,
"apiStatus": "valid",
"sender": "he***@yourdomain.com",
"recipient": "in***@yourdomain.com"
}
}
The addresses are masked so the endpoint is safe to leave public. This has saved a lot of debugging time — when something stops working, the first step is hitting this endpoint to rule out configuration drift between environments.
Deploying to Cloudflare Pages
Connect your repository in the Cloudflare dashboard, configure your build command and output directory for your static site generator of choice, and push. Cloudflare discovers the functions/ directory automatically and deploys it alongside the static assets — no separate deployment step.
A minimal wrangler.toml to point Cloudflare at your build output:
name = "your-site"
compatibility_date = "2025-09-30"
pages_build_output_dir = "./dist"
On every push to the connected branch, Pages builds the site and deploys both static files and functions atomically.
Cloudflare Email Routing: inbound without a mail server
Brevo handles outbound mail from the contact form. For inbound mail — people emailing contact@yourdomain.com directly — Cloudflare has a separate free feature called Email Routing.
Enable it in the dashboard under Email → Email Routing. Cloudflare updates your domain’s MX records to point at its own mail infrastructure. You then create routing rules: any message sent to an address on your domain gets forwarded to a destination address of your choice.
contact@yourdomain.com → yourpersonal@gmail.com
hello@yourdomain.com → yourpersonal@gmail.com
*@yourdomain.com → catch-all forwarding
This means you can publish a professional email address on your site without running a mail server or paying for a hosted mailbox. The forwarded messages land in whatever inbox you already use. Combined with the contact form Worker, you have both inbound and outbound covered with no additional infrastructure.
What works well — and what to watch
This setup has been running in production since late 2024 with no operational issues. A few things worth knowing before you copy it:
The free tier is generous. Brevo’s free plan allows 300 emails per day. For a contact form on a consulting or portfolio site, you are unlikely to get close to that limit from legitimate use.
Cloudflare Functions have cold starts. Not as pronounced as Lambda, but the first request after a period of inactivity can take a few hundred milliseconds longer. For a contact form this is imperceptible, but worth knowing.
The honeypot is not a complete spam solution. Sophisticated bots ignore hidden fields entirely, or parse CSS to identify them. For high-traffic sites, you’d want to add rate limiting at the Cloudflare level (cf-connecting-ip header + a KV-backed counter) and possibly a CAPTCHA. For a low-traffic site, the honeypot handles the realistic threat model.
replyTo is not sender spoofing. Some people worry that setting replyTo to user-supplied email addresses is a spoofing risk. It isn’t — the From address is always your verified sender. replyTo only affects where a reply goes, and it’s the visitor’s own address, so there’s no harm in it.