Email preferences look like a settings screen and are really a data model question: what is the unit of consent, where does it live, and what happens to a message that was due while it was off.
Nakodo sends a brand a handful of emails about its outreach campaigns. Six of them can be turned off, and this is the whole of how that works.
The registry is a 49-line file with no logic in it
export const NOTIFICATION_EMAILS = [
"first_results",
"daily_digest",
"needs_you",
"after_intro",
"setup_reminder",
"plan_limit",
] as const;
export type NotificationEmail = (typeof NOTIFICATION_EMAILS)[number];
Beside the list is the copy that the settings screen renders, one label and one sentence per kind. The sentence has a shape that turned out to be the most useful rule in the feature:
daily_digest: {
label: "A day's news",
text: "One email a day while a campaign is running: who Nakodo wrote to, who wrote back, and anything waiting on you. A quiet day sends nothing. Off, the same is on your campaigns.",
},
Every one of the six ends with where the same information waits if you switch the email off. "Off, they show on the campaign as they're found." "Off, they wait under Needs you on the campaign's Outreach tab." "Off, your draft waits under Campaigns."
That sentence is a constraint on the product, not a description of it. An email is allowed to be switchable only if the thing it tells you is also somewhere in the app. Write the copy first and you find out quickly which emails you have no right to make optional.
The column is an array of what is off
// Emails about campaigns the user turned off under Settings → Emails
// (src/lib/notification-emails.ts). Empty: all of them come.
emailsOff: text({ enum: NOTIFICATION_EMAILS })
.array()
.notNull()
.default(sql`'{}'::text[]`),
Storing what is off rather than what is on means the default is "all of them", a new kind of email arrives switched on for everyone without a backfill, and the common row is an empty array.
Flipping one is a single statement that also copes with a profile row that does not exist yet:
const without = sql`array_remove(${profiles.emailsOff}, ${kind}::text)`;
await db
.insert(profiles)
.values({ id: userId, emailsOff: on ? [] : [kind] })
.onConflictDoUpdate({
target: profiles.id,
set: { emailsOff: on ? without : sql`array_append(${without}, ${kind}::text)` },
});
array_append(array_remove(...)) rather than array_append alone is what makes the write idempotent. Switching the same email off twice leaves one entry, not two, which matters because the switch sends a request on every flip and the network is not a well-behaved queue.
Two enforcement shapes, because two kinds of sender
The obvious way to use this is a function call, and two of the six senders do exactly that:
if (!to || !(await wantsEmail(thread.userId, "needs_you"))) return;
Those two handle one conversation at a time, so one extra query costs nothing.
The other four are batch jobs that select everyone who is due. For them the check is a column in the query that was already being run:
off: sql<boolean>`coalesce('first_results' = any(${profiles.emailsOff}), false)`,
coalesce is load-bearing: the join to profiles is a left join, and 'x' = any(NULL) is NULL rather than false, so without it a user with no profile row would be neither on nor off and the filter would silently drop them.
An email switched off is not an email deferred
Here is the decision I would defend hardest. In the batch senders the "off" flag does not remove anyone from the batch. It only decides whether sendEmail is called:
await tx.insert(auditLog).values(
ready.map((r) => ({
userId: r.userId,
actor: "system" as const,
action: "campaign.results_emailed" as const,
entityType: "campaign" as const,
entityId: r.id,
metadata: r.off ? { fit: r.fit, off: true } : { fit: r.fit },
})),
);
// The first good fits, whether or not the email goes: a step of the funnel.
for (const c of due) if (c.userId) track(c.userId, "campaign.first_fits", { ... });
for (const c of due.filter((r) => !r.off)) {
// ...compose and send
}
The audit row is written for everybody, including the people whose email did not go, with off: true recorded on it. The analytics event fires either way, because "this campaign reached its first results" is a fact about the campaign and not about the mail.
The payoff is what does not happen. The "already emailed" guard is a query against that audit action, so recording the moment means the email can never be sent later. Turn the switch back on tomorrow and you do not receive a backlog of things that happened while you were not listening. You start receiving the next one.
The alternative design, where an off email is skipped and leaves no trace, has a subtle failure: the guard never fires, so the condition stays true, and the first thing the user sees after switching back on is a week of news they already read in the app.
The emails that are not in the list
The registry's header comment names them:
// Emails that always go out aren't here: signing in and passwords, Stripe's
// receipts, the email saying someone said yes (notifyYes in
// src/lib/outreach/notify.ts), and notices about the account or the terms.
Every switchable email carries a footer with a one-line reason and a link to the settings screen. The yes email carries the reason and deliberately passes no link:
reason: "You get this when someone says yes to your outreach.",
settings: false,
A footer offering to turn off an email that cannot be turned off is worse than no footer. The flag is one word in one object, and it is the difference between a promise you keep and one you break in small print.
Product news is a different kind of consent
The last switch on the settings screen is not in the array at all, because marketing consent is not a user preference. It is a record about an address:
export const emailPreferences = pgTable("email_preferences", {
email: text().primaryKey(), // lowercased
userId: uuid().references(() => authUsers.id, { onDelete: "set null" }),
marketing: boolean().notNull().default(false),
unsubscribeToken: uuid().notNull().defaultRandom(),
source: text({ enum: ["onboarding", "settings", "admin"] }).notNull().default("settings"),
unsubscribedAt: timestamp({ withTimezone: true }),
...
});
Four differences from the array column, each of them deliberate:
-
The key is the address, not the account. A subscriber need not have an account, and an address stays unsubscribed after an account is deleted. The foreign key is
on delete set null, so the suppression survives the user. - The default is false. Campaign emails default to on because you asked for the product; product news defaults to off because you did not.
-
The row is never deleted. Unsubscribing sets
marketingto false and keeps the row. Deleting it would let the next sign-up with that address re-create a default, and a suppression that can be undone by somebody else is not a suppression. -
The user ID is only ever filled in.
coalesce(existing, new)on conflict, so an address that subscribed before the account existed keeps its history.
There is a matching asymmetry in the audit trail. Flipping a campaign email writes emails.changed with the kind and the new value. Flipping product news writes its own entry, with a comment saying why: what someone agreed to and when is the one thing in this app that might have to be shown to a regulator.
The screen itself is eight lines
<Switch
checked={checked}
disabled={pending}
onCheckedChange={(next) =>
start(async () => {
setChecked(next);
notify(await save(next));
})
}
/>
useOptimistic holds checked, so the switch moves under your finger, and if the server action fails React discards the optimistic value and the switch snaps back to what the page says is saved. The toast reuses the label from the registry, so the confirmation and the row you just flipped cannot disagree about what the email is called.
What came out of it
- The registry has no test. Nothing asserts that every kind has copy, that every kind is checked by exactly one sender, or that no sender checks a kind that no longer exists. Adding a seventh email to the array compiles, renders, and sends unconditionally, because the switch and the sender are joined by a string.
- The privacy notice is behind the code. The "Emails we send you" section lists the account emails, the first-results email, the needs-you email, the yes email and the after-introduction email. It does not mention the daily digest, the setup reminder or the plan-limit email. Three of the six are missing from the page that is supposed to enumerate them, which is the kind of drift that happens when copy lives in a page and truth lives in an array.
-
Two enforcement shapes is one too many. The SQL version exists because those senders need the row anyway. It is the right optimisation and the wrong number of ways to express one rule, and the honest fix is a helper that generates the predicate so the string
'first_results'appears once.
The product side of all this is visible from outside: what the plans do and do not include is on the pricing page, what the app does between those emails is on how it works, and the consent model is described in plain words in the privacy notice.
Top comments (0)