
Webhook Security in Next.js: Signature Verification, Replay Prevention, and Idempotency
Webhooks Are Trust Boundaries Your Stripe webhook fires when a payment succeeds. Your GitHub webhook fires on every push. Anyone who can send an HTTP POST to your endpoint can fake these events -- unless you verify the signature. Here's how to properly validate webhooks from Stripe, GitHub, and custom sources. Stripe Webhook Verification // app/api/webhooks/stripe/route.ts import { NextRequest , NextResponse } from ' next/server ' import Stripe from ' stripe ' const stripe = new Stripe ( process . env . STRIPE_SECRET_KEY ! ) export async function POST ( req : NextRequest ) { const body = await req . text () // Raw body REQUIRED for signature const signature = req . headers . get ( ' stripe-signature ' ) ! let event : Stripe . Event try { event = stripe . webhooks . constructEvent ( body , signature , process . env . STRIPE_WEBHOOK_SECRET ! ) } catch ( err ) { console . error ( ' Webhook signature verification failed: ' , err ) return NextResponse . json ({ error : ' Invalid signature '
Continue reading on Dev.to
Opens in a new tab




