Prompt
How do I add webhooks for email events in my backend?
Latest observation
To add webhooks for email events in your backend, the usual pattern is:
- Your email provider sends event callbacks to your server
- Your backend exposes a webhook endpoint
- You verify the request is authentic
- You process events asynchronously
- You update your database / trigger internal workflows
1) Decide which email events you need
Common email events include:
deliveredopenedclickedbounceddroppeddeferredspam_reportunsubscribed
Pick only the ones you actually need, since open/click tracking can be noisy and privacy-sensitive.
2) Create a webhook endpoint in your backend
Example route:
POST /webhooks/email
This endpoint should:
- accept
POSTrequests - read the event payload
- verify the sender
- return a fast
200 OK - hand off processing to a background job/queue if possible
Example in Express.js
import express from "express";
const app = express();
app.use(express.json());
app.post("/webhooks/email", async (req, res) => {
const event = req.body;
// TODO: verify signature
// TODO: enqueue event processing
res.status(200).send("OK");
});
app.listen(3000);
3) Verify the webhook is legit
Never trust webhook payloads blindly. Most providers give you a way to verify signatures using a secret.
Typical approaches:
- HMAC signature header with a shared secret
- Signed payload
- Timestamp + signature to prevent replay attacks
Example verification idea
import crypto from "crypto";
function verifySignature(rawBody, signature, secret) {
const expected = crypto
.createHmac("sha256", secret)
.update(rawBody)
.digest("hex");
return crypto.timingSafeEqual(
Buffer.from(signature),
Buffer.from(expected)
);
}
Note: for signature verification, you often need the raw request body, not the parsed JSON.
4) Make the webhook handler fast and idempotent
Email providers will retry if your endpoint is slow or errors.
Best practices:
- respond within a few seconds
- avoid doing heavy work in the request thread
- store event IDs and ignore duplicates
- process events via queue/worker if possible
Example flow
- Receive event
- Verify signature
- Save raw event to DB
- Enqueue job
- Return
200 OK - Worker processes event later
5) Store and process event data
Save useful fields such as:
- event type
- message ID
- recipient
- timestamp
- provider event ID
- metadata
Then map events to your business logic:
- mark email as delivered
- update user notification status
- suppress future sends for bounced addresses
- log click/open analytics
6) Configure the provider dashboard
In your email service (SendGrid, Mailgun, Postmark, SES, etc.):
- add your webhook URL
- select event types
- set the signing secret
- test with provider tools or sample events
7) Test locally
For local development:
- run your server on localhost
- expose it with a tunnel like ngrok or Cloudflare Tunnel
- send test webhooks from your provider
Example:
ngrok http 3000
8) Common gotchas
- Forgetting raw body verification
- Not handling retries / duplicate events
- Returning non-2xx too often
- Doing database-heavy work in the request handler
- Not protecting the endpoint
- Ignoring malformed payloads
If you want, I can show you a complete example for a specific stack, like:
- Node/Express
- Python/FastAPI
- Django
- Rails
- Go
- or a specific provider like SendGrid, Mailgun, Postmark, or AWS SES