Mustlist

Transactional email for a Next.js + Postgres app

VerifiedLast verified 15 Nov 2026R@RIDAM7v1.0.0
Suggest a change

Queue each email in a Postgres outbox in the write's transaction; a worker sends it via an email API with idempotency keys, from a DMARC-aligned subdomain. Suppress bounces via verified webhooks, rate-limit per recipient, and email only hashed, single-use tokens.

Forweb-appsaase-commercemarketplace
Not formarketing-newsletters-onlystatic-site-without-backend

Must-have checklist

12 must · 3 should

Must

01

Publish SPF and DKIM (2048-bit key) for the sending domain so at least one aligns with the From domain, plus DMARC starting at p=none with reports, then quarantine or reject.

Gmail and Yahoo require SPF and DKIM plus DMARC from bulk senders and SPF or DKIM from all; Outlook.com requires all three above 5,000 a day.

Security
02

Insert an outbox row in the same transaction as the change that triggers the email and send from a worker; never await the provider inside the request.

Provider latency, 429s and outages then never fail sign-up, and no committed change can lose its email.

Performance
03

Give each email a stable dedupe key under a unique constraint (for example receipt:<order_id>) and pass it as the provider idempotency key on every retry where supported.

Resend keeps keys 24 hours; SES SendEmail and Postmark have no key, so the outbox is your only guard against duplicates.

Data
04

Retry 429, 5xx and network errors with capped backoff and jitter, honouring Retry-After; never retry validation errors, permanent SMTP rejections, or jobs whose token expired.

Retrying a permanent failure repeats it and burns quota, and a reset email that arrives after its link expired only confuses the user.

Performance
05

Verify bounce and complaint webhooks on the raw body (Resend signature, SNS signature plus TopicArn) and store event ids once; Postmark signs nothing, so use basic auth and its IP ranges.

The webhook URL is public; an unverified event could suppress any address or hide real bounces.

Security
06

Mirror hard bounces and complaints into a Postgres suppression table keyed by normalised address, check it before every send, and record skipped sends.

Repeated sends to dead or complaining addresses raise bounce and spam rates, and providers drop them silently anyway.

Data
07

Limit emails per recipient address, per account and per IP (for example 3 reset emails per address per hour), plus a daily cap per template, as in the rate-limiting card.

Attackers submit a victim's address to public forms to flood their inbox, burning your quota and reputation.

Security
08

Return the same response and similar timing for reset and sign-in link requests whether or not the account exists; enqueue the email only for real accounts.

Security
09

Put only a random, single-use token in links, stored hashed and expiring within 24 hours (shorter for sign-in), on a configured base URL; turn off click tracking for these emails.

NIST caps emailed recovery codes at 24 hours; click tracking routes the token through a third-party redirect and its logs.

Security
10

Send a plain-text part with every HTML email; give the HTML a lang attribute, real text instead of images of text, alt text, and link text that names the action.

UX
11

Log template, recipient, provider message id, status and timestamps; never log bodies, links or tokens, and clear outbox payloads once sent or expired.

Data
12

Use separate provider keys per environment; outside production send through a capture transport or only to allowlisted addresses such as provider test addresses.

A seed script or test run with the production key emails real users and hurts domain reputation.

Security

Should

13

Send transactional mail from its own subdomain and provider stream, separate from marketing, and keep promotions out of it.

Isolates reputation. Gmail and Yahoo require one-click unsubscribe (RFC 8058) for marketing, not transactional mail; promotions change that.

UX
14

Alert on rising bounce and complaint rates, and watch the spam rate in Gmail Postmaster Tools (Gmail requires under 0.3% and asks for under 0.1%).

Gmail sends no complaint data to SES, so Gmail users' spam reports never reach those webhooks.

UX
15

Consume tokens on a POST from a confirm page, or with a typed code, never on the link's GET request.

Some mail security scanners open links before the user does and would use up single-use tokens.

UX

Decisions to make

Asked before building

01Do you already have an email provider or relay that you must use?

02How many transactional emails do you expect to send per month in year one?

03Will the same domain also send marketing email or newsletters?

04Do you already run a queue or background job runner?

05Will email carry sign-in links or one-time sign-in codes?

Options

3 compared
Recommended

Email API provider called from an outbox worker

Examples, not endorsements: Resend, Postmark, SendGrid

Best fit when
  • Most apps, including serverless deployments, because sends are plain HTTPS calls
  • You want signed bounce and complaint webhooks and a managed suppression list
  • You want provider-side idempotency keys (Resend supports them)
Avoid when
  • Volume is high enough that per-email price dominates your bill
  • Data-residency rules forbid the provider's regions
Trade-offs
  • Monthly plans cost more per email than SES at volume
  • Webhook formats, signing and idempotency support differ by provider (Postmark has neither keys nor signatures)

Amazon SES through the SESv2 SDK

Examples, not endorsements: Amazon SES

Best fit when
  • You already run on AWS and can own IAM, SNS and configuration sets
  • High volume where the lowest per-email price matters
Avoid when
  • You must launch within days (new accounts start in the sandbox; AWS gives a first answer to production-access requests within 96 hours)
  • Nobody on the team will build and watch the bounce and complaint pipeline
Trade-offs
  • No idempotency token on SendEmail; deduplicate in the outbox
  • Bounces and complaints arrive through SNS, which you subscribe to and verify yourself

SMTP relay through Nodemailer

Examples, not endorsements: Nodemailer

Best fit when
  • You must use an existing SMTP relay or want to switch providers by changing credentials
  • Local development and tests that capture mail instead of sending it
Avoid when
  • Short-lived serverless functions, which reconnect on every send and cannot keep a pool
  • You need provider idempotency keys or rich event data
Trade-offs
  • Slower than HTTPS APIs per message; pooling needs a long-running worker
  • Bounce and complaint events still come from the relay provider's webhooks, if it has them

Why this approach

Transactional email fails in ways a request handler cannot fix: providers rate-limit, time out and go down, and mailbox providers reject mail from unauthenticated domains. Writing an outbox row in the same transaction as the change and sending from a worker means a slow provider never breaks sign-up, and a retry never sends twice when the provider honours an idempotency key. An email API provider is the default because it adds signed bounce and complaint webhooks, a managed suppression list and an HTTPS API that works from serverless functions. Choose Amazon SES when you already run on AWS and per-email price matters at your volume, and SMTP through Nodemailer when you must use an existing relay.

Lenses

Treat every form that sends email as an abuse target: limit sends per recipient address, per account and per IP, because attackers submit a victim's address to flood their inbox. Return the same response for known and unknown addresses, and enqueue email only for real accounts. Links carry only a random token (for example 32 bytes from crypto.randomBytes), stored as a SHA-256 hash, used once and expiring within NIST's 24-hour cap for emailed recovery codes; sign-in links should expire much sooner. NIST SP 800-63B-4 forbids email for out-of-band authentication, so treat a magic link as a single factor. Build URLs from a configured base URL, never the Host header, and serve token pages with Referrer-Policy: no-referrer before redirecting to a token-free URL. Verify webhooks before acting: Resend signs with svix-* headers, SES events arrive as signed SNS messages, and Postmark signs nothing, so protect it with basic auth and its published IP ranges. Keep provider keys server-only, one per environment, with sending-only permission where offered.

Version notes

resend>=6.0.0 <7.0.0
  • emails.send() resolves to { data, error } without throwing, and the SDK has no retries: throw on error in the worker so the job retries.
  • Pass { idempotencyKey } as the second argument (kept 24 hours); a 409 invalid_idempotent_request means the payload changed.
  • The default limit is 10 requests per second per team; on 429 wait the retry-after seconds.
  • Since 6.2.0, resend.webhooks.verify(...) checks the raw body against the svix-* headers.
@aws-sdk/client-sesv2>=3.0.0 <4.0.0
  • SendEmail has no idempotency token, and a MessageId means accepted, not sent: deduplicate in the outbox.
  • The client already retries throttling and 5xx errors (3 attempts by default).
  • New accounts start in the sandbox per Region (verified recipients, 200 a day); request production access before launch.
Official docsContext7docs.aws.amazon.com
nodemailer>=10.0.0 <11.0.0
  • Needs Node.js 20+. Since 10.2.0, err.permanent is true for 5xx replies except 503: do not retry those.
  • Use jsonTransport: true in development and tests to build messages without sending them.
Official docsContext7nodemailer.com
react-email>=6.0.0 <7.0.0
  • Import components and render from react-email (@react-email/components is deprecated); render() returns a Promise.
  • Build the text part with toPlainText(html) or render(element, { plainText: true }).
next>=16.0.0 <17.0.0
  • after() never retries: use it only to nudge the outbox worker. Keep provider keys out of NEXT_PUBLIC_ variables.
  • Build email links from a configured base URL, never from the request's host header.

Verify checks

12 checks
01

When the transaction that creates a user or order rolls back, no outbox row exists; when it commits, exactly one row exists even with the worker stopped.

integrationData
02

With the email provider mocked to time out, sign-up and password-reset requests still return their normal response in under 1 second.

integrationPerformance
03

Running the same outbox job twice, including from two workers at once, makes one provider call, or several calls that all carry the same idempotency key.

integrationData
04

A 429 with Retry-After schedules the next attempt no earlier than that delay, a 5xx retries with backoff, and a validation error or permanent SMTP rejection is not retried and is marked failed.

unitPerformance
05

A bounce webhook with a missing or wrong signature gets 400 and changes nothing; a validly signed payload with unusual JSON whitespace passes.

integrationSecurity
06

A verified hard-bounce or complaint event delivered twice adds the address to the suppression table once, and later emails for it are skipped and recorded as suppressed.

integrationData
07

Reset requests for an existing and an unknown email return the same status and body with similar timing, and only the existing account gets an outbox row.

integrationSecurity
08

An emailed token works once, fails on reuse and after expiry, the database stores only its hash, and no log line contains the raw token.

integrationSecurity
09

Opening an emailed link with GET does not consume its token; only the confirming POST does.

e2eSecurity
10

Requesting more reset emails for one address than the limit, from many IPs, enqueues no further emails and still returns the same generic response.

integrationSecurity
11

Every template renders non-empty HTML and plain-text parts, the HTML root has a lang attribute, and every image has alt text.

unitUX
12

With non-production configuration, sending to an address outside the allowlist never calls the real provider.

integrationSecurity

Common mistakes

  • Awaiting the provider call inside the sign-up or reset request, so an outage fails the request.
  • Leaving DKIM on the provider's shared domain and SPF on its return path, so neither aligns with the From domain and DMARC fails.
  • Retrying with a new idempotency key, or none, so a timeout after acceptance sends duplicates.
  • Ignoring bounce and complaint events, so sends keep hitting dead addresses until the provider pauses the account.
  • Using the production key in development, or seed scripts that email real users.
  • Adding promotions to receipts, which makes them commercial mail.

Sources

32 sources
Google: Email sender guidelinessupport.google.comGoogle: Email sender guidelines FAQsupport.google.comYahoo Sender Hub: Sender best practicessenders.yahooinc.comYahoo Sender Hub: FAQssenders.yahooinc.comMicrosoft: Outlook's new requirements for high-volume senderstechcommunity.microsoft.comRFC 9989: DMARC (obsoletes RFC 7489)www.rfc-editor.orgRFC 7208: Sender Policy Framework (SPF)www.rfc-editor.orgRFC 6376: DomainKeys Identified Mail (DKIM) Signatureswww.rfc-editor.orgRFC 8058: One-Click Unsubscribe for List Email Headerswww.rfc-editor.orgFTC: CAN-SPAM Act compliance guide for businesswww.ftc.govOWASP Forgot Password Cheat Sheetcheatsheetseries.owasp.orgNIST SP 800-63B-4: Authentication and Authenticator Managementpages.nist.govResend: Idempotency keysresend.comResend: Rate limitresend.comResend: Verify webhook requestsresend.comResend: Webhook retries and replaysresend.comResend: Email suppressionsresend.comResend: Send test emailsresend.comAmazon SES API v2: SendEmaildocs.aws.amazon.comAmazon SES: Request production access (sandbox limits)docs.aws.amazon.comAmazon SES: Account-level suppression listdocs.aws.amazon.comAmazon SES: Setting up event notificationsdocs.aws.amazon.comAmazon SNS: Verifying message signaturesdocs.aws.amazon.comAWS SDKs and Tools: Retry behaviordocs.aws.amazon.comPostmark: Webhooks overview (security and retries)postmarkapp.comPostmark: What is an idempotency key?postmarkapp.comReact Email: render utilityreact.emailReact Email: Updating React Email (6.0)react.emailNodemailer changeloggithub.comNext.js after referencenextjs.orgNext.js environment variables guidenextjs.orgSupabase: OTP verification failures (email link prefetching)supabase.com