Direct mail for growth teams, with an API underneath. Read the docs →

Direct mail API for Typeform

Direct mail API for Typeform: a webhook sends each completed response to a small endpoint you host, the endpoint checks Typeform's signature, maps the answers to an address and merge fields, and Mailr prints and mails a postcard or letter. The response token is the idempotency key, so a redelivered webhook never mails twice.

What to mail from Typeform

When this happensMail this
form_response on a client onboarding formA welcome letter from the founder, addressed to the person and company on the form. (Welcome letter)
form_response on a catalog or sample request formA postcard in your own design to the address they entered.
form_response where a hidden field marks the lead (for example tier=enterprise)A letter from sales in your own design, sent only for that segment.

Set it up

  1. Build the form and set refs. Add Short text questions for the person's name and company, and an Address question. Give the name and company questions refs you choose (Share or Publish > the gear icon > Block references). Without a ref, Typeform sends a generated one that changes with every payload, so code can't rely on it.
  2. Deploy the endpoint. Use the Next.js route below on Vercel or any Node host. Set TYPEFORM_SECRET to a long random string and MAILR_API_KEY to a test key, as environment variables only.
  3. Add the webhook. In the form, open Connect > Webhooks > Add a webhook, paste the endpoint URL and save. Click Edit to set the same secret, then switch the webhook on: new webhooks start off. Or register it with the Webhooks API (the second tab).
  4. Map the address fields. The Address question sends Address, Address line 2, City/Town, State/Region/Province and ZIP/Postal code as separate answers, and you can't set refs on those parts in the builder. Submit one test response, open View deliveries, copy each part's field id from the payload into FIELDS, and redeploy.
  5. Test, then go live. Submit a response with your own address. The letter appears in your Mailr dashboard and moves through every status in about 8 minutes, free. Save a return address in Mailr Settings (requests then leave out from), add funds and switch to your mlr_live_ key.

The endpoint and the webhook

// Next.js route handler. Env: MAILR_API_KEY, TYPEFORM_SECRET.
import { createHmac, timingSafeEqual } from "node:crypto";

// Each Mailr field and the Typeform question it comes from: a ref you set, or a field id from a test payload.
const FIELDS = {
  name: "full_name",
  company: "company",
  line1: "<field id of Address>",
  line2: "<field id of Address line 2>",
  city: "<field id of City/Town>",
  state: "<field id of State/Region/Province>",
  zip: "<field id of ZIP/Postal code>",
};

export async function POST(req: Request) {
  const raw = Buffer.from(await req.arrayBuffer());
  // Typeform-Signature: "sha256=" + base64 HMAC SHA-256 of the raw body, keyed with your secret.
  const expected = "sha256=" + createHmac("sha256", process.env.TYPEFORM_SECRET!).update(raw).digest("base64");
  const signature = req.headers.get("typeform-signature") ?? "";
  if (signature.length !== expected.length || !timingSafeEqual(Buffer.from(signature), Buffer.from(expected))) {
    return new Response("bad signature", { status: 401 });
  }

  const event = JSON.parse(raw.toString("utf8"));
  if (event.event_type !== "form_response") return new Response("ignored"); // e.g. partial responses
  const r = event.form_response;
  const get = (key: string) => answer(r.answers ?? [], key);

  const state = stateCode(get(FIELDS.state));
  const zip = get(FIELDS.zip);
  if (!get(FIELDS.line1) || !state || !/^\d{5}(-?\d{4})?$/.test(zip)) {
    console.log("Typeform response without a US address", r.token);
    return new Response("no US address, skipped"); // 200: a retry wouldn't fix it
  }
  const name = get(FIELDS.name);

  const res = await fetch("https://api.mailr.dev/v1/flats", {
    method: "POST",
    headers: {
      Authorization: "Bearer " + process.env.MAILR_API_KEY,
      "Content-Type": "application/json",
      "Idempotency-Key": "typeform-" + r.token, // the response id: one letter per response
    },
    body: JSON.stringify({
      size: "8.5x11",
      template: "tmpl_welcome",
      to: { name: name.slice(0, 40), company: get(FIELDS.company).slice(0, 40) || undefined, line1: get(FIELDS.line1), line2: get(FIELDS.line2) || undefined, city: get(FIELDS.city), state, zip },
      merge: {
        first_name: name.split(" ")[0].slice(0, 14),
        company: (get(FIELDS.company) || "your team").slice(0, 24),
        founder_name: "Sam",
      },
      description: "Typeform " + r.form_id + " " + r.token,
    }),
  });
  if (res.ok) return new Response("mailed");

  const err = await res.json().catch(() => ({}));
  console.error("Mailr", res.status, r.token, err.error?.message);
  // Never 404 or 410: Typeform turns the webhook off on those. A 500 is retried on a backoff
  // (5, 10 and 20 minutes, then 1 to 4 hours apart), so a short outage or a low balance sorts itself out.
  const retry = res.status >= 500 || res.status === 402 || res.status === 409;
  return new Response("not mailed", { status: retry ? 500 : 200 });
}

// The value of one answer, found by ref or field id. Choices come back as { label }.
function answer(answers: any[], key: string): string {
  const a = answers.find((x) => x.field?.ref === key || x.field?.id === key);
  if (!a) return "";
  return String(a.type === "choice" ? a.choice?.label ?? "" : a[a.type] ?? "").trim();
}

const STATES = "AL Alabama,AK Alaska,AZ Arizona,AR Arkansas,CA California,CO Colorado,CT Connecticut,DE Delaware,DC District of Columbia,FL Florida,GA Georgia,HI Hawaii,ID Idaho,IL Illinois,IN Indiana,IA Iowa,KS Kansas,KY Kentucky,LA Louisiana,ME Maine,MD Maryland,MA Massachusetts,MI Michigan,MN Minnesota,MS Mississippi,MO Missouri,MT Montana,NE Nebraska,NV Nevada,NH New Hampshire,NJ New Jersey,NM New Mexico,NY New York,NC North Carolina,ND North Dakota,OH Ohio,OK Oklahoma,OR Oregon,PA Pennsylvania,RI Rhode Island,SC South Carolina,SD South Dakota,TN Tennessee,TX Texas,UT Utah,VT Vermont,VA Virginia,WA Washington,WV West Virginia,WI Wisconsin,WY Wyoming";
const BY_NAME = new Map(STATES.split(",").map((s) => [s.slice(3).toLowerCase(), s.slice(0, 2)]));

// The Address question takes free text, so "Arizona", "az" and "AZ" all become "AZ".
function stateCode(input: string): string {
  const s = input.trim().replace(/\.$/, "");
  if (/^[A-Za-z]{2}$/.test(s)) return s.toUpperCase();
  return BY_NAME.get(s.toLowerCase()) ?? "";
}
  • Typeform waits 30 seconds for a 2xx. A 404 or 410 switches the webhook off at once, so a renamed route or a typo in the URL disables it; the endpoint never returns either. 429, 408, 503 and 423 are retried every 2 to 3 minutes for 10 hours, and other failures on a backoff over several hours.
  • Typeform turns off a webhook whose deliveries all fail (more than 300 attempts in 24 hours, or 100 in 5 minutes). If Mailr answers 402 because your balance is short, top up promptly: the endpoint asks for retries and they count.
  • Typeform can deliver the same response more than once and says to compare the token. The endpoint uses typeform-{token} as the Idempotency-Key, so a repeat within 24 hours returns the first letter instead of printing another.
  • Verify the signature against the raw bytes before parsing JSON. Typeform's own samples compare with ===; the route uses a constant-time comparison.
  • Template merge values have caps: first_name 14 characters, company 24, founder_name 16. The route trims them, and a value over the cap would fail with a 422 naming the field.
  • Typeform's pricing lists webhooks from the Basic plan up, and partial responses need Basic or higher. The route ignores anything that isn't a completed form_response.

What it costs

Each live piece is paid from your Mailr balance, printing and postage included: a 4x6 postcard is $0.85, a 6x9 $0.89 and an 8.5x11 letter $0.95 on pay as you go, less on a plan. Test pieces are free. All prices.

Templates that fit: Welcome letter (8.5x11).

Questions

Can I do this without hosting code?

Yes, with Zapier: Typeform's new-response trigger, then a Code by Zapier step that sends the same request with fetch and an Idempotency-Key of typeform- plus the response token. The key then lives in the Zap. For volume, the endpoint above is cheaper to run and easier to debug.

Why does the code map some fields by id and others by ref?

Refs are names you set on a question, and they stay the same across edits. The parts of an Address question can't get refs in the builder, so the route matches those by field id, which is also stable for the life of the question. Typeform's webhook FAQ describes setting them through the Retrieve form and Update form API if you want refs on them too.

Can we mail everyone who already filled in the form?

Yes. Pull the responses with Typeform's Responses API, map them with the same answer() function, drop the ones without a US address, and send them to POST /v1/batches in groups of up to 1,000. A batch is all or nothing: every address is checked before anything prints, so clean the list first.

Where does the Mailr key go?

Only in the endpoint's environment variables. Never in hidden fields, the embed code or the page around the form: all of that reaches the browser.

How do we follow delivery?

Each letter is in the Mailr dashboard with its status. Mailr doesn't send webhooks yet, so poll GET /v1/flats/{id} or list pieces with keyset pagination if you want statuses in your CRM.

The code on this page is written against the Mailr API as it works today. Test it with your test key first; nothing prints until you use a live key.
TYPEFORM

Mail from Typeform today

Get a free test key, send one postcard to yourself and watch it move through every status.

  • Postcards, flats and folded mailers
  • A proof before anything prints
  • Free test mode: nothing prints, nothing charges
  • A status for every piece

Download the template kit?

mailr-kit.zip · about 310 KB · 65 text files

Only HTML, JSON and Markdown files. No programs, scripts or macros, nothing that installs or runs.