Docs

Next.js recipe

Native ATM test checkout and notification verification with Next.js route handlers.

Closed beta@atmosphere-money/app-nodeSDK beta: 0.0.0-beta.3ATM API beta: 2026-0671 published lexicons

Compatible with the closed-beta ATM app APIs and versioned ATM event headers. Check atm-api-version on every webhook or XRPC receiver event.

Install SDK

Use route handlers for checkout creation and the canonical XRPC receiver, or explicitly select signed HTTP. Keep ATM SDK calls in server files, never in client components.

Install the pinned native build supplied for your integration and keep its integrity hash in your lockfile. Older npm betas may not include the native checkout helpers.

sh
# For example, a supplied package tarball:
npm install ./atmosphere-money-app-node-<version>.tgz

Configure attempts

Every recipe shares one durable attempt store. An attempt keeps the exact native request and idempotency key, ATM's response and the latest canonical status, so a retry never builds a second request.

ts
import {
  createAtmCheckoutAttempts,
  type AtmCheckoutAttempt,
  type AtmDurableStore,
} from "@atmosphere-money/app-node";

// Implement AtmDurableStore with compare-and-swap in your database. Serverless
// and edge filesystems are not durable; createAtmFileStore suits one server only.
declare const attemptStore: AtmDurableStore<AtmCheckoutAttempt>;

export const attempts = createAtmCheckoutAttempts({
  // Your assigned test configuration: app DID, test broker DID and checkout origin.
  appDid: "did:plc:aaaaaaaaaaaaaaaaaaaaaaaa",
  brokerDid: "did:plc:bbbbbbbbbbbbbbbbbbbbbbbb",
  brokerUrl: "https://your-assigned-test-checkout.example",
  store: attemptStore,
  // A NEW token per call, signed by your PDS via com.atproto.server.getServiceAuth.
  getServiceAuthToken: ({ lxm, aud }) => mintMyAppServiceAuthJwt({ lxm, aud }),
});

Create checkout route

Create the order and its attempt once, with a unique attempt ID that also serves as the idempotency key. The checkout route runs only after an authorized Buy click: it captures that stored request, sends it, and returns only the checkout URL. A repeat click or a retry recovers the same operation. The status token stays on your server.

ts
// app/orders/[id]/checkout/route.ts. Server only.
import type { AtmCreateCheckoutInput } from "@atmosphere-money/app-node";

export async function POST(request: Request, context: { params: Promise<{ id: string }> }) {
  // Your session and CSRF checks run first; load the order by its owner.
  const order = await loadOwnedOrder(request, (await context.params).id);
  if (!order) return Response.json({ error: "OrderNotFound" }, { status: 404 });

  await attempts.capture(order.attemptId, order.request);
  const attempt = await attempts.recover(order.attemptId);
  return Response.json(
    { url: attempt.checkout!.url }, // never the statusToken
    { headers: { "cache-control": "private, no-store" } },
  );
}

// Your app: the buyer's own order, with its attempt ID and request stored once.
declare function loadOwnedOrder(
  request: Request,
  orderId: string,
): Promise<{ attemptId: string; request: AtmCreateCheckoutInput } | null>;

Add event receiver

AT Protocol apps use the canonical #AtmEventReceiver / money.atmosphere.event.receiveEvent wake-up transport by default. A conventional web app can explicitly select the signed HTTP webhook shown in this recipe. Verify each delivery, claim it, and queue reconciliation before acknowledging.

ts
// app/webhooks/atm/route.ts
import { createNextWebhookRoute } from "@atmosphere-money/app-node";

export const POST = createNextWebhookRoute({
  secret: [process.env.ATM_WEBHOOK_SECRET, process.env.ATM_WEBHOOK_PREVIOUS_SECRET]
    .filter((value): value is string => Boolean(value)),
  deliveryStore: {
    claim: claimWebhookDelivery,
    complete: completeWebhookDelivery,
    release: releaseWebhookDelivery,
  },
  onEvent: async (event) => {
    if (event.environment !== "test" || event.apiVersion !== "2026-07")
      return { status: 422, body: { error: "UnexpectedEventBinding" } };
    await enqueueReconciliation(event); // the worker reads canonical status
    return { body: { ok: true } };
  },
});

Reconcile and fulfil

Fulfilment is the same in Next.js. A background worker reconciles each attempt on a schedule and whenever a notification is queued, even if the buyer never returns. Only completed status with fulfillment “fulfil” grants a direct digital purchase.

ts
// Background worker: on a schedule, and for every queued notification.
export async function reconcileOrder(
  attemptId: string,
  app: {
    grantPurchaseOnce(effectKey: string): Promise<void>;
    markUnpaid(): Promise<void>;
    pollAgainLater(): Promise<void>;
    holdForReview(): Promise<void>;
  },
) {
  const result = await attempts.reconcile(attemptId); // POSTs getCheckoutStatus
  switch (result.action) {
    case "fulfil":
      // Insert result.effectKey under a unique constraint and grant the
      // purchase in the SAME database transaction.
      return app.grantPurchaseOnce(result.effectKey!);
    case "closed": // failed, canceled or expired
      return app.markUnpaid();
    case "wait": // pending; deadlines passing are not outcomes
      return app.pollAgainLater();
    case "order": // an order owner must confirm; not used by fixed digital checkout
      return app.holdForReview();
  }
}

Run local test fixture

The examples/atm-node-app Node reference is the runnable native starter. Your tests should prove capture before any request, recovery after a restart or lost reply, status polling by POST, and a single grant for a repeated completed status. With push enabled, use signed fixtures from @atmosphere-money/testing to prove raw-body verification and duplicate delivery handling.

sh
npm run typecheck
# Then run your route tests with signed fixtures from @atmosphere-money/testing.

Runtime notes

StorageServerless and edge filesystems are not durable. Back attempts and delivery claims with your database.
Raw bodyThe route helper reads request.text() itself; do not parse the webhook body first.
XRPC receiverUse docs/developer/examples/next-xrpc-receiver-route.ts for the canonical AT Protocol receiver.
Starterexamples/atm-next-starter uses this webhook route with native test checkout, a Postgres attempt store and a cron-triggered status sweep.