# Send contact inquiries with Cloudflare Pages and Resend

The visitor submits the existing HTML form to your own site. A Pages Function validates the request and asks Resend to email your team. Astro can keep building static pages. The instructions below are optional and the demo form starts disabled.

## 1. Prepare a sender and inbox

In Resend, add a sending domain you control, copy its required DNS records into your DNS provider, and wait for Resend to show the domain as verified. Create a sending-only API key scoped to that domain where available. Choose a From address on that domain and a destination inbox that someone monitors. The visitor's address belongs in Reply-To. [Domain setup](https://resend.com/docs/dashboard/domains/introduction)

## 2. Configure your Pages project

In Workers & Pages, open your Pages project → Settings → Variables and Secrets. Set these runtime bindings for **Preview** first. Use a test inbox there. Configure Production separately when ready, then redeploy for binding changes to apply.

| Binding | Type | Value |
| --- | --- | --- |
| RESEND_API_KEY | Secret | Resend sending key |
| CONTACT_FROM | Variable | Sender on your verified domain |
| CONTACT_TO | Variable or secret | Monitored recipient for this environment |

Enter the API key directly in Cloudflare. Never paste it into an AI prompt, a PUBLIC_ variable, site.ts, or browser code. For local Wrangler testing use an ignored .dev.vars file.

## 3. Add the server handler

Create functions/api/contact.js at the repository root beside src/. This example accepts the native URL-encoded form. It sends plain text to a fixed recipient. Before opening it to public traffic, configure abuse protection, for example a Cloudflare rate-limit rule for POST /api/contact on the serving hostname. Confirm the rule actually covers the hostname, including any reachable pages.dev alias. If your plan or hostname cannot enforce that rule, add server-verified Turnstile or a supported rate limiter before enabling the form. An Origin check alone does not stop scripted submissions.

```js
export async function onRequestPost({ request, env }) {
  const reply = (text, status) => new Response(text, {
    status,
    headers: { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store" }
  });
  if (request.headers.get("Origin") !== new URL(request.url).origin)
    return reply("Please use the contact form on this site.", 403);
  const type = request.headers.get("Content-Type")?.split(";")[0];
  if (type !== "application/x-www-form-urlencoded") return reply("Unsupported form format.", 415);
  if (!env.RESEND_API_KEY || !env.CONTACT_FROM || !env.CONTACT_TO)
    return reply("Online inquiries are temporarily unavailable.", 503);

  const reader = request.body?.getReader();
  if (!reader) return reply("No form received.", 400);
  const decoder = new TextDecoder();
  let size = 0, body = "";
  while (true) {
    const { done, value } = await reader.read();
    if (done) break;
    size += value.byteLength;
    if (size > 65536) {
      await reader.cancel();
      return reply("Please shorten your inquiry.", 413);
    }
    body += decoder.decode(value, { stream: true });
  }
  const fields = new URLSearchParams(body + decoder.decode());
  const name = fields.get("name")?.trim();
  const email = fields.get("email")?.trim();
  const message = fields.get("message")?.trim();
  if (!name || name.length > 120 || !email || email.length > 254 ||
      !/^[^\s@,;<>]+@[^\s@,;<>]+\.[^\s@,;<>]+$/.test(email) ||
      !message || message.length > 4000)
    return reply("Check your name, email and project details.", 400);

  try {
    const sent = await fetch("https://api.resend.com/emails", {
      method: "POST",
      headers: { Authorization: "Bearer " + env.RESEND_API_KEY, "Content-Type": "application/json" },
      body: JSON.stringify({
        from: env.CONTACT_FROM, to: [env.CONTACT_TO], reply_to: email,
        subject: "Website project inquiry", text: name + "\n" + email + "\n\n" + message
      })
    });
    if (sent.ok && (await sent.json()).id)
      return reply("Thank you. Your inquiry was accepted for sending.", 200);
  } catch {
    // Keep credentials, visitor details and upstream errors out of the response.
  }
  return reply("We could not confirm sending. Please contact the team by email.", 502);
}
```

## 4. Connect the form and deploy

Keep the existing field names name, email and message. In src/config/site.ts set formEndpoint to the **full HTTPS URL on the same origin as the site**, ending in /api/contact. The current starter requires an absolute URL. Also set site.url to the corresponding domain. For a Pages preview with a different hostname, build with that environment's matching origin or first adapt the starter to support a validated root-relative endpoint. A preview pointing to production is a configuration error.

Keep the browser policy form-action 'self'. The server calls Resend, so this integration needs no browser access to api.resend.com. Update privacy copy with the actual provider and retention practices.

Run npm run qa. For local function tests run npx wrangler pages dev dist from the repository root after building; Astro preview alone serves static files. For deployment use Pages Git integration (build command npm run build, output dist) or Wrangler Pages deployment from the repository root. Dashboard drag-and-drop of dist alone omits the Functions directory. [Cloudflare routing](https://developers.cloudflare.com/pages/functions/routing/) · [Bindings](https://developers.cloudflare.com/pages/functions/bindings/) · [Resend email API](https://resend.com/docs/api-reference/emails/send-email)

## 5. Verify one inquiry end to end

Send a uniquely labeled test from the preview contact page. Check the browser response, then Resend's event log, then the destination inbox and spam folder. Use Reply and confirm the visitor is addressed. Provider acceptance and delivery to the receiving mail server are distinct from inbox receipt. If tracking leads, record acceptance server-side once per accepted inquiry and keep visitor details out of analytics.

| Symptom | First check |
| --- | --- |
| 404 or an HTML site page from /api/contact | Verify Functions were included and the handler filename matches the route. |
| Form disabled or browser blocks submission | Check formEndpoint, rebuild and compare its origin with the open page. |
| 503 | Check all three runtime bindings in the environment serving the request; redeploy. |
| 502 | Check Resend key permissions, sender verification and provider logs before retrying. |
| Accepted but inbox empty | Check recipient, provider delivery status, bounces and spam filtering. |

## Copy these prompts into Codex

**Implement the integration**
> Read this guide, AGENTS.md, src/config/site.ts, ContactForm.astro and public/_headers. Add a same-origin Cloudflare Pages Function for the existing form using Resend over fetch. Use only binding names in code. Keep sender and recipient server-controlled. Ask which abuse protection covers both preview and production. Preserve static Astro and the disabled default for an unconfigured site. Mock Resend for tests covering valid input, invalid fields, missing bindings and provider rejection.

**Prepare my Cloudflare preview**
> My preview hostname is [hostname], my production hostname is [hostname], and my sending domain is [verified domain]. Give me a dashboard checklist showing exactly which bindings go in Preview and Production. Check that the form posts to the current environment, the server function will deploy, and previews cannot send to the production inbox. Show any proposed code changes. Do not request key values or change DNS.

**Verify delivery**
> Run local checks with mocked email. Then give me one labeled browser test for [preview URL], the expected HTTP result and what to inspect in Resend and the test inbox. Separate what you observed from what still needs account access. Report duplicate-send risk on retries and whether lead tracking is configured.

## Use this with Codex

> Read skills/connect-verify-inquiries/SKILL.md. Configure a preview-only inquiry flow with mocked provider tests. Tell me which Cloudflare bindings to enter without requesting secret values.
