Record paid orders in a Next.js route handler

A practical Next.js App Router pattern for sending one paid-order event to Butters after a verified payment webhook, with duplicate-delivery and failure handling.

3 min read

A customer lands on a success page. That page can refresh, reopen, or never load at all. If you want a reliable record that an order was paid, report it from the server path that confirms payment, after your payment provider's webhook has been verified and your order changes state.

Here is a Next.js App Router route handler that sends a paid-order event to Butters. It fits into an existing checkout integration: your app supplies the webhook verifier and order update functions.

Keep payment verification first

Install @getbutters/js and add a secret event key plus project ID to your server environment:

BUTTERS_API_KEY=ev_your_secret_key
BUTTERS_PROJECT_ID=your_project_id

Do not use NEXT_PUBLIC_ for the secret. Next.js exposes variables with that prefix to browser bundles. The Butters server client belongs in a route handler or other server-only module.

Create app/api/payment-webhook/route.ts:

import { Butters } from '@getbutters/js/server'
import { verifyPaymentWebhook, markOrderPaidIfNew } from '@/lib/orders'

const butters = new Butters({
  key: process.env.BUTTERS_API_KEY!,
  project: process.env.BUTTERS_PROJECT_ID!,
})

export async function POST(request: Request) {
  // Your verifier must check the provider's signature using the raw body.
  const payment = await verifyPaymentWebhook(request)
  if (payment.type !== 'order.paid') {
    return new Response(null, { status: 204 })
  }

  // Return null when this order was already marked paid.
  const order = await markOrderPaidIfNew(payment.orderId)
  if (!order) return new Response(null, { status: 204 })

  try {
    await butters.track('orders', 'Order paid', {
      user_id: order.customerId,
      metadata: { order_id: order.id, amount_cents: order.totalCents },
    })
  } catch (error) {
    console.error('Could not report paid order', { orderId: order.id, error })
  }

  return new Response(null, { status: 204 })
}

verifyPaymentWebhook and markOrderPaidIfNew are your application's functions. The verifier must reject invalid signatures before anything changes. The state transition should be atomic: two webhook deliveries for the same order must not both return a newly paid order. Adapt payment.type to your provider's real event name.

Choose useful event fields

The category and title make the feed scan well. user_id attaches the event to the customer your app already knows; do not call the server client's identify() once at module scope to set a request-specific user. Metadata keeps the order ID and amount in minor currency units. If your team works in more than one currency, add a currency code too.

Avoid placing a customer email, card details, or the full webhook payload in the event. The feed is for operational context, not a second copy of your payment database. If you include an event URL, point it to a stable internal order page without tokens in the query string.

Understand the delivery trade-off

This example treats Butters as a best-effort activity feed. If reporting fails, the order still stays paid and the webhook returns success. That avoids asking the provider to redeliver a business event solely because a telemetry call failed. The logged order ID gives you a way to investigate, but this code does not replay the missed feed event automatically.

If every paid order must appear in the feed, write an outbox row in the same database transaction that marks the order paid. A worker can send pending rows to Butters. Give each row a stable order ID and track delivery state. Since a timeout can occur after the API accepted an event, design that worker for possible duplicates too.

Test the awkward cases

Send one valid test webhook and check for one “Order paid” event. Send the exact webhook again: the route should return 204 and add no new event. Try an invalid signature: the verifier should reject it without touching the order or the feed. Finally, make the Butters call fail in a test environment and confirm the order remains paid and your error log includes its ID.

Next.js documents the App Router route handler convention and reading request bodies. The Butters JavaScript SDK guide covers the server client and supported event fields.