Guide

Save contact form submissions to Cloudflare D1

29 November 2026 · About a 12-minute read

Most contact form tutorials end at “send an email.” That works until a message lands in spam, the mail API has a bad hour, or you want to answer “how many enquiries did we get in October?” A database fixes all three. If your site is already on Cloudflare Pages, D1 is the obvious choice: it’s SQLite, it’s bound straight into your Function (no connection strings, no driver), and it has a free allowance that an ordinary contact form fits inside.

This guide is the storage half of a contact form, done properly. You’ll create a D1 database with Wrangler, write a schema with the indexes you’ll actually use, bind it to a Pages Function at functions/api/contact.js that validates and length-limits input before a prepared INSERT, and then read, export, and expire the data. Everything below was run locally with Wrangler 4 (wrangler pages dev and a local D1) before publishing.

What you’ll end up with

public/                 # your built site
  index.html            # the form
  thanks/index.html
functions/
  api/
    contact.js          # → POST /api/contact, writes to D1
schema.sql
wrangler.toml

If you’d rather run the form endpoint as a standalone Worker (for example, because the site lives on GitHub Pages or Netlify), the D1 parts are identical; only the handler signature changes. The Turnstile tutorial shows that shape.

Step 1: Create the database

npx wrangler login
npx wrangler d1 create contact-form

Wrangler prints a [[d1_databases]] block with a database_id (recent versions offer to add it to your config for you). Two optional flags are worth knowing before you create it, because you can’t change them later without making a new database: --location weur (or enam, apac, and so on) is a hint for where the primary copy lives, and --jurisdiction eu restricts where the data is stored and processed. If your visitors are mostly in the EU and you care about where their messages sit, decide now.

Step 2: A schema you won’t regret

Keep one row per submission and one column per field you actually ask for. Add a form column even if you only have one form today; it costs nothing and lets a waitlist or quote form share the table later.

-- schema.sql
CREATE TABLE IF NOT EXISTS submissions (
  id         INTEGER PRIMARY KEY,
  created_at TEXT    NOT NULL DEFAULT (datetime('now')),
  form       TEXT    NOT NULL DEFAULT 'contact',
  name       TEXT    NOT NULL,
  email      TEXT    NOT NULL,
  message    TEXT    NOT NULL,
  page       TEXT,
  user_agent TEXT,
  status     TEXT    NOT NULL DEFAULT 'new'
);

CREATE INDEX IF NOT EXISTS idx_submissions_form_created
  ON submissions (form, created_at);

CREATE INDEX IF NOT EXISTS idx_submissions_email
  ON submissions (email);
  • INTEGER PRIMARY KEY is SQLite’s rowid alias. You get an auto-incrementing id for free, and D1 returns it as meta.last_row_id after an insert.
  • created_at defaults to datetime('now'), which is UTC in the format 2026-11-29 07:54:54. That format sorts correctly as text, so range queries and the retention job below work without date parsing. Convert to your own time zone when you display it, not when you store it.
  • (form, created_at) serves the two queries you’ll run most: “latest messages for this form” and “delete this form’s rows older than N days.” email serves “find (or delete) everything from this person.” We checked both with EXPLAIN QUERY PLAN: SQLite uses the index for each. D1 bills on rows read, so an index is also what stops a lookup from scanning the whole table as it grows.
  • No IP column. You don’t need a raw IP address to answer an enquiry. If you want one for rate limiting, use the rate limiting binding instead of storing it.

Apply it twice: once to the local copy that wrangler pages dev uses, and once to the real database.

npx wrangler d1 execute contact-form --local  --file=./schema.sql
npx wrangler d1 execute contact-form --remote --file=./schema.sql

Without --remote, Wrangler only touches the local copy in .wrangler/state. Forgetting the remote run is the single most common reason a form works on your laptop and fails in production.

If you expect the schema to change, use wrangler d1 migrations create and migrations apply instead of a loose schema.sql. D1 tracks which migrations have run, so adding a column later is one command per environment.

Step 3: Bind it in wrangler.toml

# wrangler.toml
name = "example-site"
pages_build_output_dir = "public"
compatibility_date = "2026-11-01"

[vars]
THANKS_URL = "/thanks/"

[[d1_databases]]
binding = "DB"
database_name = "contact-form"
database_id = "PASTE_ID_FROM_d1_create"

The binding name is what your code sees as env.DB. Once a Pages project has a Wrangler file with pages_build_output_dir, Cloudflare treats that file as the source of truth for its bindings, for both wrangler pages deploy and git-connected builds. If you’d rather not commit a config file, bind the database in the dashboard instead: Workers & Pages → your project → Settings → Bindings → Add → D1 database, variable name DB, for Production and Preview.

Step 4: The form

<form method="post" action="/api/contact">
  <label>Name <input name="name" required maxlength="80" autocomplete="name"></label>
  <label>Email <input name="email" type="email" required maxlength="254" autocomplete="email"></label>
  <label>Message <textarea name="message" required minlength="10" maxlength="5000"></textarea></label>
  <div style="position:absolute;left:-10000px" aria-hidden="true">
    <label>Leave this empty <input name="website" tabindex="-1" autocomplete="off"></label>
  </div>
  <button type="submit">Send</button>
</form>

The browser’s maxlength and required are for the visitor’s convenience. Bots don’t run your HTML, so the Function enforces the same limits again. The hidden website field is a honeypot: people never see it, and naive bots fill it in.

Step 5: The Pages Function

This is the whole handler. It accepts a normal form post or JSON, drops honeypot hits, validates and length-limits every field, writes one row with a prepared statement, and answers with a 303 redirect for plain HTML forms or JSON for fetch callers.

// functions/api/contact.js  →  POST /api/contact
const LIMITS = { name: 80, email: 254, message: 5000, page: 300, ua: 300 };
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

export async function onRequestPost({ request, env }) {
  const wantsJson = (request.headers.get("Accept") || "").includes("application/json");

  let data;
  try {
    data = await readBody(request);
  } catch {
    return reply(wantsJson, request, env, 400, { ok: false, error: "Could not read the form." });
  }

  // Honeypot: bots fill every field. Pretend it worked, store nothing.
  if (data.website) {
    return reply(wantsJson, request, env, 200, { ok: true });
  }

  const name = clean(data.name);
  const email = clean(data.email).toLowerCase();
  const message = clean(data.message, true);

  const errors = {};
  if (!name || name.length > LIMITS.name) errors.name = "Enter your name (up to 80 characters).";
  if (!EMAIL_RE.test(email) || email.length > LIMITS.email) errors.email = "Enter a valid email address.";
  if (message.length < 10 || message.length > LIMITS.message) errors.message = "Write between 10 and 5000 characters.";
  if (Object.keys(errors).length) {
    return reply(wantsJson, request, env, 422, { ok: false, errors });
  }

  const page = (request.headers.get("Referer") || "").slice(0, LIMITS.page) || null;
  const ua = (request.headers.get("User-Agent") || "").slice(0, LIMITS.ua) || null;

  try {
    const result = await env.DB.prepare(
      "INSERT INTO submissions (form, name, email, message, page, user_agent) " +
      "VALUES (?1, ?2, ?3, ?4, ?5, ?6)"
    ).bind("contact", name, email, message, page, ua).run();

    return reply(wantsJson, request, env, 201, { ok: true, id: result.meta.last_row_id });
  } catch (err) {
    console.error("D1 insert failed", err);
    return reply(wantsJson, request, env, 500, { ok: false, error: "Could not save your message. Please try again." });
  }
}

async function readBody(request) {
  const type = request.headers.get("Content-Type") || "";
  if (type.includes("application/json")) {
    const body = await request.json();
    return body && typeof body === "object" ? body : {};
  }
  const form = await request.formData();
  return Object.fromEntries([...form].filter(([, v]) => typeof v === "string"));
}

function clean(value, multiline = false) {
  let s = typeof value === "string" ? value : "";
  s = s.replace(/\r\n?/g, "\n").replace(/\u0000/g, "");
  if (!multiline) s = s.replace(/\s+/g, " ");
  return s.trim();
}

function reply(wantsJson, request, env, status, body) {
  if (wantsJson) {
    return Response.json(body, { status });
  }
  if (body.ok) {
    return Response.redirect(new URL(env.THANKS_URL || "/thanks/", request.url), 303);
  }
  const text = body.errors ? Object.values(body.errors).join("\n") : body.error;
  return new Response(text + "\n\nGo back and try again.", {
    status,
    headers: { "Content-Type": "text/plain; charset=utf-8" },
  });
}

The parts that matter:

  • .prepare(...).bind(...), never string concatenation. The SQL text is fixed; the visitor’s input travels separately as parameters. In our test, a name of Robert'); DROP TABLE submissions;-- was stored as exactly that string, and the table survived. ?1, ?2 are numbered placeholders; plain ? works too.
  • Length limits on everything you store, including headers like Referer and User-Agent that you didn’t ask the visitor for. A single row in D1 has a maximum size, and you don’t want a bot to discover it for you.
  • Newlines are normalized. Browsers send textarea line breaks as \r\n in form posts. Converting them to \n keeps stored messages consistent and makes the 5000-character limit mean the same thing for every client.
  • The honeypot pretends to succeed. Returning an error teaches a bot which field gave it away.
  • A failed insert returns 500 with a generic message. The real error goes to the log (console.error), where you can see it with wrangler pages deployment tail or in the dashboard. Don’t send database errors to the browser.
  • Status codes are honest. 201 for a stored row, 422 for invalid fields, 400 for an unreadable body. A fetch caller can show field errors next to the inputs; a plain form gets a readable text page and the back button.

Only onRequestPost is exported, so a GET to /api/contact never reaches this code; Pages serves your static site as usual for that path.

Optional: submit without a page reload

The form already works with JavaScript off. If you want an inline “thanks” message, add this; it sends Accept: application/json so the Function answers in JSON instead of redirecting.

// Optional: submit without a page reload. The form still works without JS.
const form = document.querySelector('form[action="/api/contact"]');
form?.addEventListener("submit", async (event) => {
  event.preventDefault();
  const button = form.querySelector("button");
  button.disabled = true;
  try {
    const res = await fetch(form.action, {
      method: "POST",
      headers: { Accept: "application/json" },
      body: new FormData(form),
    });
    const data = await res.json();
    if (data.ok) {
      form.outerHTML = "<p>Thanks! Your message is saved. We’ll reply by email.</p>";
      return;
    }
    alert(data.errors ? Object.values(data.errors).join("\n") : data.error);
  } catch {
    alert("Network error. Please try again.");
  } finally {
    button.disabled = false;
  }
});

Step 6: Test it locally

npx wrangler pages dev public

# in another terminal
curl -i -X POST http://localhost:8788/api/contact \
  -d name=Ana -d email=ana@example.com \
  --data-urlencode "message=Hello from curl, testing D1"
# → HTTP/1.1 303 See Other, Location: http://localhost:8788/thanks/

curl -X POST http://localhost:8788/api/contact -H "Accept: application/json" \
  -d name=Bo -d email=bo@example.com -d "message=Second message please"
# → {"ok":true,"id":2}

Those are the actual responses from our local run. When it works locally, deploy with npx wrangler pages deploy (or push to your connected repo) and send one real message through the live form before you rely on it.

Step 7: Read your submissions

You don’t need an admin panel on day one. wrangler d1 execute runs any SQL against the live database:

# Latest 20 messages, with a preview
npx wrangler d1 execute contact-form --remote --command \
  "SELECT id, created_at, name, email, substr(message, 1, 60) AS preview
   FROM submissions WHERE form = 'contact'
   ORDER BY created_at DESC LIMIT 20"

# One full message
npx wrangler d1 execute contact-form --remote --command \
  "SELECT message FROM submissions WHERE id = 42"

# Mark it handled
npx wrangler d1 execute contact-form --remote --command \
  "UPDATE submissions SET status = 'done' WHERE id = 42"

# Messages per day, last 30 days
npx wrangler d1 execute contact-form --remote --command \
  "SELECT date(created_at) AS day, count(*) AS n FROM submissions
   WHERE created_at >= datetime('now', '-30 days')
   GROUP BY day ORDER BY day"

The dashboard works too: open the database in the D1 section and use its Console tab to run the same queries in the browser.

Step 8: Export to CSV (and back up)

wrangler d1 export writes SQL, not CSV. For a spreadsheet, ask execute for JSON and convert it. With jq:

npx wrangler d1 execute contact-form --remote --json --command \
  "SELECT id, created_at, name, email, message FROM submissions ORDER BY id" \
  | jq -r '.[0].results | (.[0] | keys_unsorted) as $cols
         | ($cols | @csv), (.[] | [.[$cols[]]] | @csv)' > submissions.csv

One caution before you open that file in Excel or Google Sheets: every cell came from a stranger. A “name” like =HYPERLINK(...) is treated as a formula. If the CSV is going into a spreadsheet, use this small Node script instead. It needs no dependencies, quotes every cell, and prefixes anything that starts with =, +, -, or @ with an apostrophe so it stays text:

// export-csv.mjs — usage: wrangler d1 execute ... --json | node export-csv.mjs > out.csv
let input = "";
for await (const chunk of process.stdin) input += chunk;
const rows = JSON.parse(input)[0].results;
if (!rows.length) process.exit(0);

const cols = Object.keys(rows[0]);
const cell = (v) => {
  let s = v == null ? "" : String(v);
  if (/^[=+\-@\t\r]/.test(s)) s = "'" + s; // stop spreadsheet formula injection
  return '"' + s.replace(/"/g, '""') + '"';
};
const lines = [cols.map(cell).join(",")];
for (const row of rows) lines.push(cols.map((c) => cell(row[c])).join(","));
process.stdout.write(lines.join("\r\n") + "\r\n");
npx wrangler d1 execute contact-form --remote --json --command \
  "SELECT id, created_at, name, email, message FROM submissions ORDER BY id" \
  | node export-csv.mjs > submissions.csv

For a full backup you can restore from, export SQL:

npx wrangler d1 export contact-form --remote --output=backup-2026-11-29.sql

D1 also has Time Travel, which can restore the database to an earlier point within a limited window. It’s your undo button for a bad DELETE, but it isn’t a substitute for an occasional export kept somewhere else.

Retention and privacy

A contact form collects personal data: a name, an email address, and whatever people choose to write. Practical habits (not legal advice):

  • Store only what you use. The schema above has no IP and no extra profile fields. Add a column when you have a reason, not “just in case.”
  • Say how long you keep messages, in a line next to the form or in your privacy notice, and then actually delete them on that schedule.
  • Handle deletion requests in one query: DELETE FROM submissions WHERE email = 'person@example.com'. The email index keeps it cheap. Remember the CSVs you already downloaded, and that Time Travel can still restore the old state for its window.
  • Lock down who can read it. Anyone with access to your Cloudflare account can query the database. If you build an admin page, put it behind Cloudflare Access or a strong secret.

Pages Functions don’t run on a schedule, so automatic retention needs a tiny separate Worker with a cron trigger, bound to the same database:

# retention/wrangler.toml
name = "contact-form-retention"
main = "worker.js"
compatibility_date = "2026-11-01"

[triggers]
crons = ["17 3 * * *"]   # every day at 03:17 UTC

[vars]
KEEP_DAYS = "180"

[[d1_databases]]
binding = "DB"
database_name = "contact-form"
database_id = "PASTE_THE_SAME_ID"
// retention/worker.js — a separate Worker, bound to the same D1 database
export default {
  async scheduled(controller, env, ctx) {
    const days = Number(env.KEEP_DAYS || 180);
    const result = await env.DB.prepare(
      "DELETE FROM submissions WHERE form = ?1 AND created_at < datetime('now', ?2)"
    ).bind("contact", `-${days} days`).run();
    console.log(`retention: deleted ${result.meta.changes} contact rows older than ${days} days`);
  },
};
cd retention && npx wrangler deploy

It deletes only contact rows, so a waitlist in the same table can follow its own rule, and the (form, created_at) index means it reads only the rows it deletes. We tested it with wrangler dev --test-scheduled: a row dated 200 days ago was removed and newer rows were kept.

Common errors

  • D1_ERROR: no such table: submissions: SQLITE_ERROR. The schema was applied to one database but not the one your code is talking to. Usually you ran execute without --remote, or your local dev state lives in a different folder. Re-run the schema with the right flag.
  • TypeError: Cannot read properties of undefined (reading 'prepare'). env.DB doesn’t exist. The binding name doesn’t match your code (DB vs db), the binding is only set for Production while you’re testing a Preview URL, or a dashboard binding is being ignored because a Wrangler file is now the source of truth.
  • A placeholder or stale database_id. Copy the real one from npx wrangler d1 list. Local dev doesn’t care what the ID is, so this mistake only shows up after you deploy.
  • D1_ERROR: Wrong number of parameter bindings for SQL query. Or, worse, no error and values in the wrong columns. The number of ? placeholders must match the .bind() arguments, in order. Numbered placeholders (?1…?6) make mismatches easier to spot.
  • D1_TYPE_ERROR: Type 'undefined' not supported for value 'undefined'. D1 accepts strings, numbers, null, and binary data, but not undefined. Pass null for missing optional values, as the handler above does with || null.
  • The form “works” but nothing is stored. Check whether you filled in the honeypot while testing with browser autofill or a password manager. The response looks like success by design.
  • A 405 instead of the redirect. Pages answers a POST to a path with no Function with 405. Check the form’s action and that the file is at functions/api/contact.js at the project root (it must not be inside your output folder).

Before you call it done

Storing the message is only half a contact form. Someone has to notice it: send yourself an alert after the insert with the email guide or a Discord or Slack webhook, inside context.waitUntil() so the visitor isn’t kept waiting. And a public endpoint that writes to your database needs more than a honeypot: add Turnstile and a rate limit before you put the form on a busy page.

The ready-made version

Formharbor is the larger version of this, built as a standalone Worker rather than a Pages Function. Submissions go into a D1 database in your own Cloudflare account, with an indexed schema, and you get a dashboard with search, filters, a spam flag, delete, and CSV export, so you’re not living in wrangler d1 execute. It also handles Turnstile, a honeypot, a timing trap, rate limits, notifications (Resend, Discord, Slack), a referral waitlist, and R2 uploads, for $19 once. It doesn’t delete old rows automatically yet, so if you want a retention schedule, the cron Worker above works with it too (adjust the table and form names). If one contact form is all you need, the code on this page is complete.

More guides

Want this already built?

Formharbor is a $19 one-time kit: contact forms, referral waitlists, and file uploads on your Cloudflare free tier.

Get Formharbor