Prompt
I'm building a Next.js app and need email delivery webhooks.
Latest observation
Oct 18, 2026
OpenAI APIWeb search: off
Sure — for a Next.js app, the usual pattern is to expose an API route that receives webhook POSTs from your email provider, verify the signature, and then process the event asynchronously.
Typical setup
1) Create a webhook endpoint
If you’re using the App Router, create:
app/api/email/webhook/route.ts
import { NextRequest, NextResponse } from "next/server";
export async function POST(req: NextRequest) {
const body = await req.text();
// 1. Verify webhook signature here
// 2. Parse event payload
// 3. Handle event types: delivered, bounced, opened, clicked, complained, etc.
console.log("Webhook body:", body);
return NextResponse.json({ received: true });
}
If you’re on the Pages Router, use pages/api/email/webhook.ts instead.
2) Verify the webhook signature
Most providers sign webhook requests. You should verify them using the raw body and a shared secret.
Examples:
- SendGrid: signed event webhook
- Postmark: HMAC signature
- Resend: signed webhooks
- Mailgun: timestamp/signature verification
- SES: SNS verification / signatures
The exact code depends on your provider.
3) Handle webhook events
Common email delivery events:
deliveredbounceddroppedopenedclickedcomplainedunsubscribed
You’ll usually:
- update your database
- mark a message as delivered/bounced
- track engagement analytics
- suppress future sends for bounced/complained recipients
4) Make it reliable
Webhooks should return quickly. Best practice:
- validate request
- enqueue work to a background job
- respond
200 OKimmediately
This avoids timeouts and retries from the provider.
Example with provider-agnostic structure
import { NextRequest, NextResponse } from "next/server";
export async function POST(req: NextRequest) {
const rawBody = await req.text();
try {
// verifySignature(rawBody, req.headers)
const event = JSON.parse(rawBody);
switch (event.type) {
case "delivered":
// update DB
break;
case "bounced":
// mark as bounced
break;
default:
console.log("Unhandled event:", event.type);
}
return NextResponse.json({ ok: true });
} catch (err) {
console.error("Webhook error:", err);
return NextResponse.json({ error: "Invalid webhook" }, { status: 400 });
}
}
Notes for Next.js
- Use
await req.text()if you need the raw payload for signature verification. - Avoid
req.json()before verifying if the provider requires raw body bytes. - Deploy the route to a public URL, e.g.:
https://yourdomain.com/api/email/webhook - Test locally with
ngrokor a similar tunnel.
If you want, I can help you with one of these:
- A Next.js webhook route for a specific provider
- Signature verification code
- A database schema for tracking delivery events
- A full working example with Resend, SendGrid, Postmark, Mailgun, or SES
If you tell me your email provider, I can give you the exact implementation.