๐Ÿช

Webhook Receiver

๐Ÿ‘จโ€๐Ÿณ Chefโฑ๏ธ 25 minutes

๐Ÿ“‹ Suggested prerequisites

  • โ€ขNext.js API
  • โ€ขWebhooks

What you'll build

An endpoint that receives and processes events from external services like Stripe, GitHub, or any API that sends webhooks. You'll implement HMAC signature verification to ensure events are authentic, logging of received events, robust error handling, and asynchronous processing. When finished, you'll have a secure webhook receiver that can trigger actions in your app when external events occur, like activating a subscription when Stripe confirms a payment.


Step 1: Ask an AI for the receiver

I need a webhook receiver with:
- HMAC signature verification
- Event logging
- Error handling
- Retry logic
- Save to database
- Next.js App Router

Give me the code for Stripe webhooks.

Code

// app/api/webhooks/stripe/route.ts
import Stripe from 'stripe'

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!)

export async function POST(request: Request) {
  const body = await request.text()
  const signature = request.headers.get('stripe-signature')!

  let event: Stripe.Event

  try {
    event = stripe.webhooks.constructEvent(
      body,
      signature,
      process.env.STRIPE_WEBHOOK_SECRET!
    )
  } catch (err) {
    return new Response('Invalid signature', { status: 400 })
  }

  // Process event
  switch (event.type) {
    case 'checkout.session.completed':
      // Activate subscription
      break
  }

  return new Response('OK')
}

Next step

โ†’ Cache with Redis