A double opt-in SMS flow has four moving parts: a form that stores a pending record, one confirmation text asking the person to reply YES, an inbound handler that matches the reply, and a consent record you write when it matches. Only after that record exists should your code send marketing texts with consent_attested: true.
This post builds that flow in Node and TypeScript against Postgres. We make Ready, and we describe Ready's side of this exactly: Ready doesn't store a per-contact opt-in record for API sends. The attestation flag is your statement, so the record of who agreed, when and to what wording is yours to keep. That's why the database table below is the center of the design.
Why double opt-in is worth the extra step
A single opt-in means a person typed their number into a form and you started texting. Double opt-in adds a second action from the handset. The person owns the phone, so a reply from it proves the number belongs to them and that they saw your wording.
That proof matters in three places. It stops someone typing another person's number into your form. It gives you a timestamped reply to show if a consent dispute comes up. And it catches typos before you pay to text a stranger. The cost is drop-off, because some people won't reply. Our post on the double opt-in conversion tradeoff covers when that cost is worth paying, and this one covers the code once you've decided.
The flow at a glance
| Step | Who acts | What your code does |
|---|---|---|
| 1. Form POST | Visitor | Validate the number, store a pending row with the exact consent wording |
| 2. Confirmation text | Your server | Send one message: brand, what they'll get, "Reply YES to confirm" |
| 3. Reply | Visitor | Texts YES from their phone |
| 4. Inbound handler | Your server | Match the reply to the pending row, write the consent record |
| 5. First real text | Your server | Send with consent_attested: true |
Each step writes to the same table, so you can answer "what happened to this number" with one query.
The consent table
Keep the schema boring. This is a sketch, and our consent record schema for developers goes deeper on what to store and for how long.
CREATE TABLE sms_consent (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
phone_e164 text NOT NULL,
status text NOT NULL DEFAULT 'pending',
wording text NOT NULL,
page_url text NOT NULL,
form_ip inet,
requested_at timestamptz NOT NULL DEFAULT now(),
confirmed_at timestamptz,
reply_text text,
confirmed_via text
);
CREATE UNIQUE INDEX one_open_request_per_phone
ON sms_consent (phone_e164) WHERE status = 'pending'; The partial unique index keeps a double-click or a bot from opening ten pending rows for one number. Store the wording as a string copy, not a pointer to a template, because the template will change and the record has to show what this person saw.
Step 1 and 2: the form handler and confirmation text
The form handler normalizes the number to E.164, inserts the pending row, and sends one confirmation. The confirmation needs the brand name, a plain description of what they'll receive, how often, and how to leave. Registered 10DLC campaigns are reviewed against this wording, so match what you registered. The consent language that passes registration post has examples.
import express from "express";
import { randomUUID } from "node:crypto";
import { Pool } from "pg";
const db = new Pool();
const app = express();
app.use(express.urlencoded({ extended: false }));
const WORDING =
"I agree to get appointment reminders and offers from Acme Dental by text. " +
"Msg frequency varies. Reply STOP to opt out.";
async function readyPost(path: string, payload: object, key: string) {
const res = await fetch(`https://api.tryready.com${path}`, {
method: "POST",
headers: {
"X-API-Key": process.env.READY_API_KEY ?? "",
"Content-Type": "application/json",
"Idempotency-Key": key,
},
body: JSON.stringify(payload),
signal: AbortSignal.timeout(10_000),
});
if (!res.ok) throw new Error(`send failed: ${res.status}`);
return res.json();
}
app.post("/signup/sms", async (req, res) => {
const phone = toE164(String(req.body.phone ?? ""));
if (!phone || req.body.agree !== "on") {
return res.status(400).send("Enter a valid number and tick the box.");
}
// A request that never got a YES must not lock the number out for good.
await db.query(
`UPDATE sms_consent SET status = 'expired'
WHERE phone_e164 = $1 AND status = 'pending'
AND requested_at < now() - interval '24 hours'`,
[phone],
);
const { rows } = await db.query(
`INSERT INTO sms_consent (phone_e164, wording, page_url, form_ip)
VALUES ($1, $2, $3, $4)
ON CONFLICT (phone_e164) WHERE status = 'pending' DO NOTHING
RETURNING id`,
[phone, WORDING, req.get("referer") ?? "unknown", req.ip],
);
if (rows[0]) {
// The confirmation is the one text this form request earns. The ticked box beside WORDING
// is the consent for it; the row stays pending, so no marketing text goes out until YES.
try {
await readyPost(
"/v1/messages",
{
to: phone,
body: "Acme Dental: reply YES to get appointment reminders and offers. Msg frequency varies. Reply STOP to opt out.",
consent_attested: true,
},
`confirm-${rows[0].id}`,
);
} catch (err) {
// Free the number so the visitor can resubmit, and tell them now instead of hanging.
await db.query(`UPDATE sms_consent SET status = 'send_failed' WHERE id = $1`, [rows[0].id]);
console.error("confirmation send failed", rows[0].id, err);
return res.status(503).send("We couldn't send the confirmation text. Try again in a minute.");
}
}
res.status(202).send("Check your phone and reply YES.");
});
function toE164(raw: string): string | null {
const digits = raw.replace(/\D/g, "");
if (digits.length === 10) return `+1${digits}`;
if (digits.length === 11 && digits.startsWith("1")) return `+${digits}`;
return null;
} Notice that the confirmation carries consent_attested: true. Ready asks for the flag on every API send, with no exception for confirmations. A send without it goes out with a warning until January 20, 2027, but from that date it is refused with a 403 api_consent_attested_required, and a flow that leaves it out stops sending confirmations that day. The flag is honest here because it covers this one text: the visitor ticked a box beside wording that names texts from you, and the pending row keeps that wording, the page and the IP. It is not consent to marketing yet, which is why the row stays pending until the YES. The idempotency key is derived from the pending row, so a retried request can't send the confirmation twice. Whether a single confirmation text is allowed on a form submission alone is a question for your counsel, and keeping it to one message with an easy STOP is the conservative reading.
Step 3 and 4: the inbound YES handler
Replies reach you through a webhook. We don't invent event names or field names here. The handler below uses generic names, fromNumber, text and messageId, that you map to whatever your provider documents. The API quickstart shows the real webhook setup, and our post on receiving SMS through inbound webhooks covers the receiving side. Verify the signature the way SMS API authentication and webhook signing describes before you trust the body.
// Generic shape. Rename fields to match your provider's documented payload.
type InboundReply = { fromNumber: string; text: string; messageId: string };
const YES = new Set(["yes", "y", "yes."]);
app.post("/webhooks/inbound-sms", express.json(), async (req, res) => {
// 1. Verify the provider's signature here. Reject on failure.
const msg = req.body as InboundReply;
if (!YES.has(msg.text.trim().toLowerCase())) return res.sendStatus(200); // STOP is handled for you upstream
// Store the YES before acknowledging. If the database is down, answer 500 so the sender redelivers.
let rows;
try {
({ rows } = await db.query(
`UPDATE sms_consent
SET status = 'confirmed', confirmed_at = now(),
reply_text = $2, confirmed_via = $3
WHERE phone_e164 = $1 AND status = 'pending'
AND requested_at > now() - interval '24 hours'
RETURNING id`,
[msg.fromNumber, msg.text, msg.messageId],
));
} catch (err) {
console.error("could not store YES", msg.messageId, err);
return res.sendStatus(500);
}
res.sendStatus(200);
if (!rows[0]) return; // no open request, or it expired: do nothing
try {
await readyPost(
"/v1/messages",
{
to: msg.fromNumber,
body: "Acme Dental: you're in. Msg frequency varies. Reply STOP to opt out.",
consent_attested: true,
},
`welcome-${rows[0].id}`,
);
} catch (err) {
// The consent is already recorded; log the id so the welcome can be re-sent by hand.
console.error("welcome send failed", rows[0].id, err);
}
}); Three details carry the weight. The UPDATE ... WHERE status = 'pending' makes the handler safe against duplicate webhook deliveries, because the second delivery matches no row. The 24-hour window keeps an old pending row from being confirmed by a stray YES next month. And consent_attested: true appears only after the consent row has flipped to confirmed.
Ready handles STOP and clear opt-out phrases itself, so your handler doesn't need a STOP branch for compliance. It's still worth marking the consent row as revoked when you learn of an opt-out, so your record matches reality. GET /v1/opt-outs/:phone answers the question for a single number before any later send.
What to test before launch
- A YES with different capitalization and a trailing space confirms the row.
- A second YES after confirmation does nothing and sends nothing.
- A YES from a number with no pending row is ignored.
- A YES 25 hours after the form is ignored.
- Two form submits in a row open one pending row and send one confirmation.
- A failed confirmation send can be retried by resubmitting.
- A resubmit 25 hours later sends a fresh confirmation.
Where to go next
Wire the table into whatever sends your marketing texts, and make the send path check status = 'confirmed' rather than trusting a flag on the contact. That one query is what keeps consent_attested: true honest. Compliance stays with the sender, so have counsel read your wording and retention period. For the full request reference, see the messages docs.