GuidesGuides
Receive webhooks in Next.js
Build a route handler that verifies Relay signatures and processes events in the background.
This guide builds a webhook endpoint with the Next.js App Router. It verifies the signature, ignores duplicates and answers fast.
Project structure
app
api
webhooks
route.ts# the endpoint
lib
handle-event.ts
.env.local# RELAY_WEBHOOK_SECRET
Add the signing secret
Copy the endpoint's signing secret from the dashboard into .env.local:
RELAY_WEBHOOK_SECRET=whsec_C2FVsBQIhrscChlQIMVCreate the route handler
Read the body as text so the signature check sees the exact bytes Relay sent.
import { verifyWebhook, WebhookVerificationError } from "@relay/sdk";
import { after } from "next/server";
import { handleEvent } from "@/lib/handle-event";
export async function POST(request: Request) {
const payload = await request.text();
let event;
try {
event = verifyWebhook({
payload,
header: request.headers.get("relay-signature"),
secret: process.env.RELAY_WEBHOOK_SECRET!,
});
} catch (error) {
if (error instanceof WebhookVerificationError) {
return new Response("Invalid signature", { status: 400 });
}
throw error;
}
// Answer right away, process after the response is sent.
after(() => handleEvent(event));
return Response.json({ received: true });
}Handle each event type
import type { RelayEvent } from "@relay/sdk";
export async function handleEvent(event: RelayEvent) {
switch (event.type) {
case "invoice.paid":
await markInvoicePaid(event.data.invoice_id);
break;
case "invoice.payment_failed":
await notifyBilling(event.data.customer_id);
break;
default:
console.log(`Unhandled event type ${event.type}`);
}
}Send a test event
Start your app, then forward events to it with the CLI:
relay listen --forward-to http://localhost:3000/api/webhooks
relay events trigger invoice.paidafter() runs work after the response is sent and needs Next.js 15.1 or newer. For long or critical jobs, push the event to a queue (Inngest, Trigger.dev, SQS…) instead.