← Back to dashboard

SendGrid Integration Guide

What is SendGrid?

The real model

@sendgrid/mail 8.1.6 on the Node runtime; verify webhooks with ECDSA over timestamp + raw bytes.

Share one @sendgrid/client via sgMail.setClient() (setDataResidency('eu') for EU subusers on Pro). Mail Send has no idempotency key, so key retries on an outbox row and put its id in customArgs. Send marketing mail with an ASM unsubscribe group so SendGrid adds List-Unsubscribe + List-Unsubscribe-Post (RFC 8058). Event Webhooks must be HTTPS, retry for 24 h, and each has its own key pair; dedupe on sg_event_id and skip sg_machine_open opens. Inbound Parse is now signable through webhook security policies, but @sendgrid/eventwebhook decodes bodies as UTF-8 and fails on binary attachments, so verify multipart with node:crypto. Pick Resend unless the client needs subusers, IP pools, or EU residency.

Five SendGrid primitives

The pieces you touch on a client project that chose SendGrid over Resend.

Text
███████╗███████╗███╗   ██╗██████╗  ██████╗ ██████╗ ██╗██████╗
██╔════╝██╔════╝████╗  ██║██╔══██╗██╔════╝ ██╔══██╗██║██╔══██╗
███████╗█████╗  ██╔██╗ ██║██║  ██║██║  ███╗██████╔╝██║██║  ██║
╚════██║██╔══╝  ██║╚██╗██║██║  ██║██║   ██║██╔══██╗██║██║  ██║
███████║███████╗██║ ╚████║██████╔╝╚██████╔╝██║  ██║██║██████╔╝
╚══════╝╚══════╝╚═╝  ╚═══╝╚═════╝  ╚═════╝ ╚═╝  ╚═╝╚═╝╚═════╝

SendGrid Integration Guide

Focus: When and how codeAmani uses Twilio SendGrid as the alternative to its primary email provider, Resend. Covers sending with @sendgrid/mail (Mail Send v3), dynamic templates, domain authentication and link branding, DMARC and the Gmail/Yahoo/Microsoft bulk-sender rules, the signed Event Webhook, signed Inbound Parse, suppressions and unsubscribe groups, subusers, IP pools, and EU data residency.

Overview

Twilio SendGrid is a high-volume email platform: Web API v3 and SMTP, Handlebars dynamic templates, Marketing Campaigns, subusers, dedicated IPs, and a detailed event pipeline. It is advertised as an email option on motionstackstudios.com.

Resend + React Email is codeAmani's primary email provider (see ../resend/). It has cleaner DX, React-rendered templates, a permanent free tier, and fewer moving parts. Use SendGrid only when a client project needs something Resend doesn't give you:

  • the client already runs a SendGrid account and won't migrate,
  • subusers: per-tenant sending with isolated reputation, stats, and credit limits (Pro and up),
  • dedicated IPs and IP pools to split transactional from marketing reputation (Pro includes 1 IP),
  • EU data residency for email event data (Pro and up, EU subuser),
  • consolidating SMS, WhatsApp, Verify, and email on one Twilio account and bill.

What changed since the last review (details in NOTES.md):

ChangeDateImpact
Free plan retired; new accounts get a 60-day trial (100 emails/day)Trial from 25 Mar 2025; retirement announced 27 May 2025No free tier for side projects. Budget Essentials $19.95/mo minimum
Event Webhook must be HTTPSNew configs from Oct 2025; existing ones by 11 Feb 2026HTTP webhooks have stopped receiving events
Event Webhook security: OAuth 2.0 option alongside ECDSA signing; multiple webhooks per account (1 / 2 / 5 by plan)currentEach webhook has its own key pair
Signed Inbound Parse via webhook security policiescurrentInbound Parse can now be verified. The old "Inbound Parse is unsigned" advice is out of date
EU data residency (api.eu.sendgrid.com) GA15 Jul 2025client.setDataResidency('eu') in the Node SDK
v2 Mail Send capped at 1,000 recipients per request9 Jul 2025Use v3 anyway
Email Activity API limited to 6 requests/minute9 Dec 2025Use the Event Webhook for status, not polling
"Send to Coworker" removed from domain authentication setup3 Aug 2026Hand DNS records to whoever owns DNS yourself

Check first. Before wiring SendGrid into a build, query the codeAmani-tech-stack MCP (search_guides / get_guide) and confirm Resend can't meet the requirement. SendGrid adds a second vendor and a second deliverability footprint.

Official Documentation

More links in RESOURCES.md; API cheatsheet in reference/api-cheatsheet.md; plans in reference/limits-and-pricing.md.


SDK Setup

Bash
npm install @sendgrid/mail@8.1.6 @sendgrid/client@8.1.6 @sendgrid/eventwebhook@8.0.0 -E

Versions (npm, 2026-10-20): @sendgrid/mail and @sendgrid/client 8.1.6 (published Sep 2025, still latest), @sendgrid/eventwebhook and @sendgrid/helpers 8.0.0. They ship from the sendgrid-nodejs monorepo and share the v8 major. Types are bundled. @sendgrid/client uses axios under the hood, so these packages are Node-only: run send and webhook routes on the Node runtime, not Edge. From an Edge or Workers runtime, call POST https://api.sendgrid.com/v3/mail/send with fetch instead.

Initialize the client

TypeScript
// lib/sendgrid.ts  (server-only)
import sgMail from '@sendgrid/mail';
import client from '@sendgrid/client';

const apiKey = process.env.SENDGRID_API_KEY;
if (!apiKey) throw new Error('SENDGRID_API_KEY is not set');

client.setApiKey(apiKey);
// client.setDataResidency('eu'); // EU subuser on Pro+: routes to https://api.eu.sendgrid.com/
sgMail.setClient(client);
sgMail.setTimeout(10_000);

export { sgMail, client };

Create the key under Settings → API Keys as Restricted Access with only Mail Send for the app. Keep a separate key with suppression or webhook scopes for admin scripts.


Core Patterns

Send with a dynamic template

Dynamic templates are Handlebars templates built in the dashboard (Email API → Dynamic Templates). You reference one by templateId (always d-…) and pass dynamicTemplateData. The template owns the subject and body, so don't set subject or html.

TypeScript
import { sgMail } from '@/lib/sendgrid';

const [res] = await sgMail.send({
  to: 'user@example.com',
  from: { email: 'no-reply@mail.client.example', name: 'Client App' },
  templateId: 'd-0123456789abcdef0123456789abcdef',
  dynamicTemplateData: { userName: 'Amani', dashboardUrl: 'https://app.client.example' },
  customArgs: { user_id: 'usr_123', kind: 'welcome' }, // strings only; echoed on every event
  categories: ['welcome'],
  trackingSettings: { clickTracking: { enable: false, enableText: false }, openTracking: { enable: false } },
});

// 202 Accepted. Store the message id so webhook events can be matched back.
const messageId = String(res.headers['x-message-id'] ?? '');

Full route with input validation and error handling: examples/send-email.ts. Turn click and open tracking off for transactional mail (receipts, password resets): rewritten links and pixels hurt trust and add nothing.

Errors

The SDK rejects with a ResponseError. Field-level detail is in err.response.body.errors[] ({ message, field, help }). Log the messages, never the API key or recipient list.

Many recipients without leaking the list

A bare to: [...] puts everyone in one To: header. Use personalizations (one per recipient, up to 1,000 per request) or pass true as the second argument to send (isMultiple), which does the same thing.

TypeScript
await sgMail.send({
  from: { email: 'news@mail.client.example', name: 'Client' },
  templateId: 'd-...',
  personalizations: recipients.map((r) => ({ to: [{ email: r.email }], dynamicTemplateData: { name: r.name } })),
  asm: { groupId: 12345, groupsToDisplay: [12345] }, // unsubscribe group: see Bulk-sender rules
});

Other Mail Send fields worth knowing

Field (SDK name)UseLimit
sendAtSchedule (Unix seconds)At most 72 hours ahead
batchIdGroup a scheduled send so you can cancel or pause itCreate via POST /v3/mail/batch
ipPoolNameSend from a dedicated IP pool2–64 chars
categoriesStats groupingMax 10, each ≤ 255 chars
customArgsCorrelation ids returned on events≤ 10,000 bytes
asmUnsubscribe group (groupId, groupsToDisplay ≤ 25)
mailSettings.sandboxModeValidate without sending (CI)
mailSettings.bypassListManagementSkip suppressions. Only for legally required notices (for example a security alert)Can't combine with other bypass flags
replyToListSeveral reply-to addresses≤ 1,000

You can't override To, From, Subject, Reply-To, CC, BCC, Content-Type, DKIM-Signature, or the x-sg-* headers through headers.


Deliverability depends on authentication. An unauthenticated send lands in spam or shows "via sendgrid.net". Authenticate the domain before sending anything real. codeAmani manages DNS in Porkbun or Cloudflare (see ../porkbun/ and ../domain-portfolio/).

  1. Settings → Sender Authentication → Authenticate Your Domain. Use a sending subdomain (for example mail.client.example). Keep automated security on: SendGrid then gives you CNAMEs and rotates DKIM keys and manages SPF behind them. API: POST /v3/whitelabel/domains.
  2. Add the three CNAMEs exactly as listed: em#### (return path, which carries SPF), s1._domainkey, and s2._domainkey. Don't hand-write an SPF include on the apex. The "Send to Coworker" button was removed on 3 Aug 2026, so send the records to the DNS owner yourself.
  3. Link branding (POST /v3/whitelabel/links) rewrites tracked links and the List-Unsubscribe URL onto your domain instead of sendgrid.net. Do it whenever click tracking or subscription tracking is on. If you put the branded link host behind a CDN for SSL click tracking, the CDN must allow POST from non-browser user agents, or one-click unsubscribes never reach SendGrid.
  4. DMARC is yours to publish. SendGrid doesn't create it.
Text
# Porkbun / Cloudflare records (host part only; Cloudflare: DNS-only, grey cloud)
CNAME  em1234          u1234567.wl123.sendgrid.net
CNAME  s1._domainkey   s1.domainkey.u1234567.wl123.sendgrid.net
CNAME  s2._domainkey   s2.domainkey.u1234567.wl123.sendgrid.net
CNAME  url5678         sendgrid.net                  # link branding (values come from the dashboard)
CNAME  1234567         sendgrid.net
TXT    _dmarc          v=DMARC1; p=none; rua=mailto:dmarc@client.example; fo=1

Start DMARC at p=none, read the aggregate reports, then move to p=quarantine and p=reject. Give SendGrid its own subdomain: Porkbun won't let a CNAME share a host with other records, and a separate subdomain keeps SendGrid's reputation apart from Resend's or the client's mailbox provider.

Bulk-sender rules (Gmail, Yahoo, Microsoft)

These rules are the same whichever provider sends the mail; see ../domain-portfolio/ for the full table and ../resend/ for the Resend side. They apply once a domain sends about 5,000 messages a day to a provider's consumer inboxes (Gmail counts all subdomains together, and bulk status never expires):

  • SPF and DKIM pass, plus a DMARC record (at least p=none) aligned with the From domain.
  • RFC 8058 one-click unsubscribe on marketing mail: List-Unsubscribe + List-Unsubscribe-Post: List-Unsubscribe=One-Click. Honor unsubscribes within 2 days.
  • Spam-complaint rate below 0.3% (aim for under 0.1%).
  • Microsoft (Outlook.com, Hotmail, Live) has rejected non-compliant bulk mail with 550 5.7.515 since 5 May 2025. Gmail has been ramping up enforcement (temporary 4.7.x and permanent 5.7.x errors) since November 2025.

How SendGrid meets the unsubscribe rule: turn on subscription tracking (Settings → Tracking) or send with an ASM unsubscribe group (asm.groupId). Either way, SendGrid inserts both List-Unsubscribe (an HTTPS URL on your link-branding domain plus a mailto:) and List-Unsubscribe-Post, and processes the unsubscribe for you. Marketing Campaigns always adds them unless you use a custom unsubscribe link. If neither is on, you must add both headers yourself in headers and handle the POST. Transactional mail (receipts, resets) doesn't need one-click unsubscribe.


Event Webhook (signed)

SendGrid POSTs batched JSON arrays of events: delivery (processed, delivered, deferred, dropped, bounce), engagement (open, click, spamreport, unsubscribe, group_unsubscribe, group_resubscribe), and account status changes.

  • HTTPS only. Required for new webhooks since Oct 2025; HTTP webhooks stopped receiving events after 11 Feb 2026.
  • Multiple webhooks: 1 on the trial, 2 on Essentials, 5 on Pro and Premier (POST /v3/user/webhooks/event/settings). Each has its own key pair, so store one public key per webhook id.
  • Security: enable signature verification (ECDSA, P-256, SHA-256 over timestamp + raw body) and/or OAuth 2.0 client credentials (SendGrid fetches a token from your token URL and sends it as Authorization: Bearer). Use at least signing.
  • Retries: any non-2xx is retried at increasing intervals for up to 24 hours (rolling, per event). Return 2xx fast and do the work afterwards.
  • Dedupe on sg_event_id. Match to your send through custom_args or sg_message_id, which can be missing on async bounces.
  • bounce with type: "bounce" is a hard bounce; type: "blocked" is temporary. bounce_classification gives the reason (Invalid Address, Technical, Content, Reputation, Frequency/Volume, Mailbox Unavailable, Unclassified).
  • open events carry sg_machine_open: true when Apple Mail Privacy Protection fetched the pixel. Don't count those as human opens.
TypeScript
// app/api/webhooks/sendgrid/route.ts
import { EventWebhook, EventWebhookHeader } from '@sendgrid/eventwebhook';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

export async function POST(req: Request): Promise<Response> {
  const rawBody = await req.text(); // exact bytes: never req.json() first, never .trim()
  const signature = req.headers.get(EventWebhookHeader.SIGNATURE()); // X-Twilio-Email-Event-Webhook-Signature
  const timestamp = req.headers.get(EventWebhookHeader.TIMESTAMP()); // X-Twilio-Email-Event-Webhook-Timestamp
  const publicKey = process.env.SENDGRID_WEBHOOK_PUBLIC_KEY;
  if (!publicKey || !signature || !timestamp) return new Response(null, { status: 400 });

  const ew = new EventWebhook();
  const valid = ew.verifySignature(ew.convertPublicKeyToECDSA(publicKey), rawBody, signature, timestamp);
  if (!valid) return new Response(null, { status: 403 });

  const events = JSON.parse(rawBody) as { sg_event_id: string; event: string; email: string }[];
  for (const e of events) {
    // dedupe on e.sg_event_id, then update status / mirror suppressions
  }
  return new Response(null, { status: 204 });
}

The full handler with typed events, hard/soft bounce handling, and machine-open filtering is examples/event-webhook-route.ts. It uses the dependency-free node:crypto verifier in examples/verify-signature.ts, which also adds a replay window and caches the key.

Gotcha: raw bytes. The signature covers the exact payload, including its trailing \r\n characters. req.text() keeps them; req.json(), Express bodyParser.json(), or .trim() break a valid signature. On Express, mount express.raw({ type: 'application/json' }) on this route only.


Inbound Parse (now signable)

Inbound Parse turns mail sent to a subdomain into a multipart/form-data POST to your app: reply-to-ticket, document intake, +tag routing.

  1. DNS: MX parse 10 mx.sendgrid.net on the receiving subdomain.
  2. Create a webhook security policy with signing on: POST /v3/user/webhooks/security/policies with { "name": "...", "signature": { "enabled": true } }. The response holds policy.signature.public_key. OAuth (client_id, client_secret, token_url, scopes) is also supported, alone or together.
  3. Create the Parse setting (Settings → Inbound Parse, or the API) and attach the policy: PATCH /v3/user/webhooks/parse/settings/{hostname} with { "security_policy": "<policy id>" }.
  4. Verify with the same headers as the Event Webhook, over the raw multipart bytes, before any form parser touches the body.

Gotcha: binary attachments. @sendgrid/eventwebhook's verifySignature() turns a Buffer into a UTF-8 string before hashing. A multipart body with binary attachments then fails verification. Our local test with a generated P-256 key confirmed it: valid on JSON, invalid on a body with non-UTF-8 bytes. Use the node:crypto verifier in examples/verify-signature.ts, which hashes the bytes directly. Full route: examples/inbound-parse-route.ts.

Treat every inbound field as untrusted: sanitize html with DOMPurify before rendering, check the SPF and dkim fields if sender identity matters, and size-limit attachments. On an unsigned (legacy) Parse setting, at least use a hard-to-guess path; SendGrid recommends signing over IP allowlists because its webhook IPs change.


Suppressions and Unsubscribe Groups

SendGrid won't deliver to an address on a suppression list (bounces, blocks, spam reports, invalid emails, global unsubscribes, group unsubscribes). Mirror these locally from the Event Webhook so your app never queues a dead address, and use @sendgrid/client to read or clear entries.

TypeScript
import client from '@sendgrid/client';

client.setApiKey(process.env.SENDGRID_API_KEY ?? '');

// Clear a bounce after the user fixes a typo
await client.request({ method: 'DELETE', url: `/v3/suppression/bounces/${encodeURIComponent('user@example.com')}` });

// Add an address to an unsubscribe group from your own preference centre
await client.request({ method: 'POST', url: '/v3/asm/groups/12345/suppressions', body: { recipient_emails: ['user@example.com'] } });

More (global unsubscribe check, subuser-scoped calls): examples/suppressions.ts. Create one unsubscribe group per mail type (product news, digest, offers) so recipients can opt out of one without losing receipts. Never remove an unsubscribe or spam report on your own: it's a CAN-SPAM obligation and a reputation risk.


Subusers, IP Pools, and Data Residency

FeatureWhat it gives youAPIPlan
SubusersSeparate reputation, stats, suppressions, and credit limits per tenant or brand. Parent keys act as a subuser with the on-behalf-of: <username> header (client.setImpersonateSubuser() in the SDK)POST /v3/subusersPro+
Domain auth per subuserAssign an authenticated domain (up to 5) or a branded link to a subuserPOST /v3/whitelabel/domains/{id}/subuser:add, POST /v3/whitelabel/links/{id}/subuserPro+
Dedicated IPsYour own sending reputation; automated warmupIP Address Management APIPro includes 1; more as add-ons
IP poolsGroup IPs (for example transactional vs marketing) and pick one per send with ipPoolNamePOST /v3/send_ips/pools (newer) or POST /v3/ips/pools (legacy)Pro+
EU data residencyMail and event data processed and stored in the EU; host https://api.eu.sendgrid.comclient.setDataResidency('eu')Pro+, EU subuser and EU IP

Warm a new dedicated IP gradually. A fresh IP at full volume gets throttled. Under roughly 100k emails a month, shared IPs usually deliver better than a cold dedicated one.


SendGrid vs Resend (primary)

ConcernResend (primary)SendGrid (alternative)
When to pickDefault. Start hereA client requires it, or you need subusers, IP pools, or EU residency
Free tier3,000 emails/mo, permanentNone. 60-day trial at 100/day, then Essentials from $19.95/mo
TemplatesReact Email (.tsx) in your repoHandlebars dynamic templates in the dashboard (d-…)
SDKresend (works on Edge)@sendgrid/mail + @sendgrid/client (Node only; axios)
Webhook signingSvix (HMAC)ECDSA P-256 via @sendgrid/eventwebhook or node:crypto; OAuth 2.0 optional
Inboundemail.received webhookInbound Parse (multipart), signable
One-click unsubscribeAdd the headers yourself / Broadcasts add themSubscription tracking or ASM group adds them
Multi-tenantOne account; domains per projectSubusers with isolated reputation
Dedicated IPsScale add-onPro includes 1, plus IP pools

Environment Variables

Secrets (store in the vault, .env.local, and Vercel; never in the client bundle):

Bash
SENDGRID_API_KEY=SG.xxxxxxxxxxxxxxxxxxxxxx.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Non-secret settings (plain config):

VariableExampleNotes
SENDGRID_FROM_EMAILno-reply@mail.client.exampleMust be on an authenticated domain
SENDGRID_WEBHOOK_PUBLIC_KEYMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE…Public key for one Event Webhook. Not secret, but keep it in config, not code
SENDGRID_INBOUND_PUBLIC_KEYMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE…From the Inbound Parse security policy
SENDGRID_WELCOME_TEMPLATE_IDd-…Dynamic template ids
SENDGRID_DIGEST_TEMPLATE_IDd-…
SENDGRID_UNSUBSCRIBE_GROUP_ID12345ASM group for marketing sends

If you enable Event Webhook OAuth, the client secret you give SendGrid is a secret and belongs in the vault too. Add the variables to ENV_MASTER.md and each project's .env.example.


Common Use Cases

Use caseApproach
Default transactional emailResend + React Email. SendGrid only when the client requires it
Templated transactional sendsgMail.send with templateId + dynamicTemplateData, tracking off
Newsletter / marketingpersonalizations + asm.groupId (one-click unsubscribe headers added for you)
Delivery and bounce trackingSigned Event Webhook → verify → dedupe sg_event_id → update DB
Honor opt-outsMirror suppressions locally; check before every send
Reply or intake by emailInbound Parse + security policy + raw-bytes verification
Multi-tenant clientOne subuser per tenant, each with its own authenticated domain
Separate transactional and marketing reputationTwo IP pools (or two subusers) + ipPoolName
EU customer dataEU subuser + client.setDataResidency('eu')
CI check of payloadsmailSettings.sandboxMode.enable = true

codeAmani notes

  • Resend is primary; SendGrid is the alternative. Pick SendGrid only for the client-driven reasons listed above, and write the reason into the project's README. The lack of a free tier makes it a poor fit for prototypes.
  • Server-side only. SENDGRID_API_KEY never reaches the browser. Use a Restricted Access key (Mail Send only) in the app.
  • Webhooks: verify every Event Webhook and Inbound Parse request (ECDSA on the raw body) before acting, as with the Stripe signing secret, Svix for Clerk and Resend, and M-Pesa callback validation. Run them on the Node runtime.
  • Payments: Stripe is the default. A SendGrid receipt should be triggered from the verified Stripe webhook, keyed on the Stripe event id. For Kenya-targeted projects that use M-Pesa, key it on the CheckoutRequestID after the callback is validated.
  • AI routing: if Claude drafts email copy, generate it server-side and put the result into dynamicTemplateData. Escape it (Handlebars {{var}} escapes by default; never use {{{var}}} for model output).
  • Kenya-targeted projects: email backs up SMS and WhatsApp rather than replacing them. Keep templates light (inline CSS, few images) for 2G/3G, show KES as whole shillings, and send in EAT-friendly hours. If the client is already on Twilio for SMS or WhatsApp, SendGrid consolidates billing.
  • DNS: Porkbun or Cloudflare. Use a dedicated sending subdomain per provider so SendGrid and Resend never share SPF, DKIM selectors, or reputation.

Troubleshooting

IssueFix
401 UnauthorizedKey missing, mistyped, or revoked. Recreate it
403 "from address does not match a verified Sender Identity"Authenticate the domain (or verify a Single Sender for testing)
Sending stopped on an old free accountThe free plan was retired in 2025. Upgrade to Essentials or higher
Mail lands in spam or shows "via sendgrid.net"Finish domain authentication and link branding, publish DMARC, check alignment
550 5.7.515 from Outlook.comSPF, DKIM, or DMARC missing or not aligned for a bulk sender
Gmail shows no unsubscribe buttonTurn on subscription tracking or use an ASM group; check the CDN allows non-browser POSTs to the branded link host
Event Webhook stopped deliveringThe URL is still HTTP (blocked since 11 Feb 2026), or your endpoint has been non-2xx for 24 hours
Signature always invalidBody was parsed or trimmed before verifying; wrong key for that webhook id (each webhook has its own)
Inbound Parse signature fails only with attachmentsYou used @sendgrid/eventwebhook on a binary body. Switch to the node:crypto verifier
Duplicate event processingDedupe on sg_event_id
Open rates look inflatedExclude sg_machine_open: true
Template renders blank variablesdynamicTemplateData keys must match the Handlebars {{vars}}
Recipients see each otherUse personalizations or isMultiple, not a bare to: []
Mail to one address never arrivesIt's suppressed. Check /v3/suppression/* and /v3/asm/suppressions/global/{email}
429 on Email Activity APILimited to 6 requests/minute since Dec 2025. Use the Event Webhook
Inbound Parse never firesMX for the parse subdomain missing (mx.sendgrid.net, priority 10)