Sub topic 14
Designing and building a preference centre
This chapter assumes you have the subscribers and consent_events tables, the make_token and verify_token helpers, and the unsubscribe flow from earlier chapters. It also assumes you can read a small Flask-style handler.
What a preference centre is for
A preference centre is a page where a confirmed subscriber chooses what they receive. Many people who click "unsubscribe" only want less mail, or only one kind of mail. If the page offers that choice, you keep some of them. If it hides the full unsubscribe, you get spam complaints instead.
Three rules guide the design:
- Reach the page from a signed link in every email, with no login.
- Put "Unsubscribe from everything" on the same page, visible without scrolling.
- Save changes only on POST, never on GET, for the same scanner reasons as the confirmation page.
Storing the choices
Store the record from the data model chapter as one JSONB column. Topics will change often, and you never need to join on them.
CREATE TABLE preferences (
subscriber_id BIGINT PRIMARY KEY REFERENCES subscribers(id),
data JSONB NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
);Saving the form
The handler uses a token with the purpose "preferences". A confirmation token will not work here, because verify_token checks the purpose. The handler also whitelists every field. Never store form input as it arrives.
import json
from datetime import date
ALLOWED_TOPICS = {"product_updates", "weekly_digest", "events"}
ALLOWED_FREQUENCIES = {"daily", "weekly", "monthly"}
def clean_preferences(form: dict) -> dict:
"""Build a safe preference record from raw form data."""
chosen = set(form.get("topics", []))
frequency = form.get("frequency", "weekly")
if frequency not in ALLOWED_FREQUENCIES:
raise ValueError("bad frequency")
paused = form.get("paused_until") or None
if paused:
date.fromisoformat(paused) # raises ValueError if malformed
return {
"topics": {t: t in chosen for t in sorted(ALLOWED_TOPICS)},
"frequency": frequency,
"paused_until": paused,
}
def save_preferences(db, token: str, form: dict, ip: str, user_agent: str):
"""Handle POST. `render` is the same template helper used earlier."""
email = verify_token(token, "preferences")
if email is None:
return render("link_invalid_or_expired.html")
try:
data = clean_preferences(form)
except ValueError:
return render("preferences_error.html", token=token)
db.execute(
"INSERT INTO preferences (subscriber_id, data) "
"SELECT id, %s FROM subscribers "
"WHERE email = %s AND status = 'confirmed' "
"ON CONFLICT (subscriber_id) DO UPDATE "
"SET data = EXCLUDED.data, updated_at = now()",
(json.dumps(data), email),
)
db.execute(
"INSERT INTO consent_events "
"(subscriber_id, event_type, source, consent_text, ip_address, user_agent) "
"SELECT id, 'preferences_updated', 'preference_centre', %s, %s, %s "
"FROM subscribers WHERE email = %s AND status = 'confirmed'",
(json.dumps(data), ip, user_agent, email),
)
return render("preferences_saved.html", token=token)Both statements filter on status = 'confirmed'. A pending or unsubscribed address cannot use an old link to create preferences.
Applying preferences at send time
Saving a choice does nothing until the sender reads it. When you build a send, select subscribers who are confirmed, are not suppressed, have the topic set to true, and have no paused_until date in the future. Then apply the frequency cap. Run the suppression check last and let it override everything else.
Common errors
- Reusing the confirmation token. It lets anyone holding an old confirmation email edit preferences. Use a separate purpose.
- Saving on GET. A scanner that opens the link can change a subscriber's settings.
- Making full unsubscribe hard to find. Hiding it raises complaints and can violate the rules covered earlier.
- Trusting form values. An unvalidated topic name pollutes your data and can break segmentation queries.
- Ignoring pauses. A pause date that the sender never reads sends mail the subscriber asked you to hold.
Exercise
A subscriber opens the preference centre, then clicks "Unsubscribe from everything". Which parts of the system must change, and why must the preference record alone not be used to record this?
Show answer
Set subscribers.status to 'unsubscribed', add the address to the suppression list, and log an 'unsubscribe' event in consent_events. The preference record only controls which mail a confirmed subscriber receives. The send-time suppression check reads status and the suppression list, so setting every topic to false would not reliably stop mail and would leave no audit trail of the withdrawal.