Blog

Accept crypto payments in a Next.js app

CoinStackUpdated 11 min read
Integrations

To accept crypto payments in a Next.js App Router app, create the CoinStack checkout in a server action, where process.env.COINSTACK_API_KEY never reaches the browser, and call redirect() with the checkout's url. Confirm payment in a route handler at app/api/webhooks/coinstack/route.ts that reads the body with await request.text(), verifies the CoinStack-Signature HMAC with node:crypto, skips repeated event_ids and marks the order paid. The order page can also ask the API for the checkout's status when the customer returns.

What this tutorial builds and what it was tested on

Four files on top of a standard App Router project: a small API helper, a database module, a server action, and the webhook route handler, plus the order page that uses them. The code was built with next build and run with next start on Next.js 16.5, React 19.3 and Node.js 26.0 in December 2026. We submitted the pay form without JavaScript (the server action answered with a 303 to the checkout page) and posted signed sample events to the webhook route.

You need a CoinStack API key with Read and write access from the dashboard's Developers page, and the whsec_ signing secret of a webhook you add there. If the checkout fields are new to you, read the crypto payments API quickstart first; this post stays on the Next.js side.

Keep the API key on the server

Put the secrets in .env.local, which Next.js loads into process.env and which the default create-next-app template keeps out of git:

COINSTACK_API_KEY=sk_your_key
COINSTACK_WEBHOOK_SECRET=whsec_your_secret
BASE_URL=https://shop.example.com

Do not prefix any of these with NEXT_PUBLIC_. The Next.js environment variables guide says a NEXT_PUBLIC_ value is inlined at build time and "will be inlined into any JavaScript sent to the browser". Anyone could read your key from the bundle and create checkouts on your account.

The API helper starts with import "server-only". Per the Server and Client Components docs, importing such a module into a Client Component is a build-time error, so a later refactor cannot pull the key into client code by accident. Installing the server-only package is optional in Next.js; add it with npm install server-only if your linter flags the import.

// lib/coinstack.ts
import "server-only";

const API = "https://coinstack.net/api/v1";

export type Checkout = {
  checkout_id: string;
  status: "pending" | "confirming" | "partial" | "completed" | "expired" | "resolved";
  url: string;
  expires_at: string;
};

type Envelope<T> = { success: true; response: T } | { success: false; response: string };

export async function coinstack<T>(method: "GET" | "POST", path: string, body?: unknown) {
  const response = await fetch(`${API}${path}`, {
    method,
    headers: {
      Authorization: `Bearer ${process.env.COINSTACK_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: body === undefined ? undefined : JSON.stringify(body),
  });
  const result = (await response.json()) as Envelope<T>;

  if (!result.success) {
    throw new Error(`CoinStack ${response.status}: ${result.response}`);
  }

  return result.response;
}

The Envelope type mirrors the API's response shape: success is true with an object, or false with a message string. Checkout lists only the fields this app reads; add others, such as received or metadata, when you use them.

Store orders and the checkouts made for them

The demo keeps data in node:sqlite so it runs without a database server. In a real app this module is your ORM or query layer; what matters is the shape: orders, a table that links each checkout ID to its order, and a table of handled event IDs.

// lib/db.ts
import "server-only";
import { DatabaseSync } from "node:sqlite";

export type Order = { id: number; amount: string; currency: string; status: string };

export const db = new DatabaseSync("shop.db");

db.exec(`
  CREATE TABLE IF NOT EXISTS orders (
    id INTEGER PRIMARY KEY,
    amount TEXT NOT NULL,
    currency TEXT NOT NULL,
    status TEXT NOT NULL DEFAULT 'unpaid',
    paid_at TEXT
  );
  CREATE TABLE IF NOT EXISTS checkouts (
    checkout_id TEXT PRIMARY KEY,
    order_id INTEGER NOT NULL REFERENCES orders (id),
    created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
  );
  CREATE TABLE IF NOT EXISTS webhook_events (
    event_id TEXT PRIMARY KEY,
    kind TEXT NOT NULL
  );
`);

export function getOrder(id: number) {
  return db.prepare("SELECT id, amount, currency, status FROM orders WHERE id = ?").get(id) as
    | Order
    | undefined;
}

export function markPaidIfComplete(checkout: { checkout_id: string; status: string }) {
  if (checkout.status !== "completed" && checkout.status !== "resolved") return;

  db.prepare(
    `UPDATE orders SET status = 'paid', paid_at = CURRENT_TIMESTAMP
     WHERE status <> 'paid'
       AND id = (SELECT order_id FROM checkouts WHERE checkout_id = ?)`,
  ).run(checkout.checkout_id);
}

markPaidIfComplete is the single place an order becomes paid. Both the webhook and the order page call it, and it is safe to call any number of times: it ignores every status except completed and resolved, it only matches checkouts this app recorded, and its WHERE status <> 'paid' makes a second call a no-op.

Create the checkout in a server action

// app/orders/[id]/actions.ts
"use server";

import { redirect } from "next/navigation";
import { coinstack, type Checkout } from "@/lib/coinstack";
import { db, getOrder } from "@/lib/db";

export async function payOrder(formData: FormData) {
  // Anyone can call a server action, so load the order and its amount from your own database.
  // In a real app, also check that the order belongs to the signed-in customer.
  const order = getOrder(Number(formData.get("orderId")));

  if (!order) throw new Error("Order not found");
  if (order.status === "paid") redirect(`/orders/${order.id}`);

  const { checkout } = await coinstack<{ checkout: Checkout }>("POST", "/checkouts", {
    amount: order.amount,
    currency: order.currency,
    reference: `order-${order.id}`,
    success_url: `${process.env.BASE_URL}/orders/${order.id}`,
    cancel_url: `${process.env.BASE_URL}/orders/${order.id}`,
    metadata: { order_id: String(order.id) },
  });

  db.prepare("INSERT INTO checkouts (checkout_id, order_id) VALUES (?, ?)").run(
    checkout.checkout_id,
    order.id,
  );

  redirect(checkout.url);
}

Three Next.js behaviors shape this code. A server action is reachable by anyone: the proxy reference notes that server functions "are handled as POST requests to the route where they are used" and tells you to verify authorization inside each one. That is why the action takes only an order ID from the form and reads the amount from the database.

Second, redirect() accepts an absolute URL, so it can send the customer to the CoinStack checkout page directly. According to the redirect reference, it answers a form submitted without JavaScript with a 303, and with JavaScript it navigates on the client. Third, redirect() works by throwing, so it must stay outside any try/catch; wrapped in one, your catch swallows the redirect and the customer stays put.

If you call the API from something other than a form, such as a mobile app, a route handler that returns { url } as JSON does the same job. The rules do not change: authorize the caller, take the amount from your database, and keep the key on the server.

Use the order page as the return page

Both success_url and cancel_url point back to the order page. When the customer arrives, the page asks CoinStack for the latest checkout's status, so it can show the right state even if the webhook has not landed yet.

// app/orders/[id]/page.tsx
import { notFound } from "next/navigation";
import { coinstack, type Checkout } from "@/lib/coinstack";
import { db, getOrder, markPaidIfComplete } from "@/lib/db";
import { payOrder } from "./actions";

export default async function OrderPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  let order = getOrder(Number(id));

  if (!order) notFound();

  const latest = db
    .prepare("SELECT checkout_id FROM checkouts WHERE order_id = ? ORDER BY created_at DESC LIMIT 1")
    .get(order.id) as { checkout_id: string } | undefined;

  let checkout: Checkout | undefined;

  // The customer is back before the webhook: ask CoinStack for the checkout's current status.
  if (order.status !== "paid" && latest) {
    ({ checkout } = await coinstack<{ checkout: Checkout }>("GET", `/checkouts/${latest.checkout_id}`));
    markPaidIfComplete(checkout);
    order = getOrder(order.id)!;
  }

  if (order.status === "paid") {
    return <p>Order #{order.id} is paid. Thank you.</p>;
  }

  if (checkout?.status === "confirming") {
    return <p>Your payment for order #{order.id} was detected. Refresh in a minute.</p>;
  }

  if (checkout?.status === "pending" || checkout?.status === "partial") {
    return (
      <p>
        <a href={checkout.url}>Continue to the payment page</a> for order #{order.id}.
      </p>
    );
  }

  return (
    <form action={payOrder}>
      <input type="hidden" name="orderId" value={order.id} />
      <p>
        Order #{order.id}: {order.amount} {order.currency}
      </p>
      <button type="submit">Pay with crypto</button>
    </form>
  );
}

Marking the order paid here is safe because the status comes from CoinStack over your authenticated API call, not from anything in the URL. Reaching success_url proves nothing by itself, which is why the page never trusts the visit alone.

The "Continue to the payment page" branch stops a customer who pressed Back from creating a second checkout with a second address while the first is still open. Once a checkout expires, the page offers the button again and the action creates a fresh one. One case to add for a real shop: a checkout that expired with underpaid set already holds part of the money, so resolve it or refund before you offer a full-price checkout. params is a promise in current Next.js, so the page awaits it, and a page that awaits its params and reads the database renders on each request.

Read the raw body in the webhook route handler

// app/api/webhooks/coinstack/route.ts
import crypto from "node:crypto";
import { db, markPaidIfComplete } from "@/lib/db";

function verify(header: string | null, body: string) {
  const secret = process.env.COINSTACK_WEBHOOK_SECRET!;
  const parts = Object.fromEntries(
    String(header).split(",").map((part) => part.split("=")),
  );
  const expected = Buffer.from(
    crypto.createHmac("sha256", secret).update(`${parts.t}.${body}`).digest("hex"),
  );
  const given = Buffer.from(String(parts.v1));

  return (
    given.length === expected.length &&
    crypto.timingSafeEqual(given, expected) &&
    Math.abs(Date.now() / 1000 - Number(parts.t)) <= 300
  );
}

export async function POST(request: Request) {
  const body = await request.text();

  if (!verify(request.headers.get("CoinStack-Signature"), body)) {
    return new Response("Invalid signature", { status: 400 });
  }

  const event = JSON.parse(body);

  db.exec("BEGIN IMMEDIATE");

  try {
    const inserted = db
      .prepare("INSERT INTO webhook_events (event_id, kind) VALUES (?, ?) ON CONFLICT DO NOTHING")
      .run(event.event_id, event.kind);

    if (inserted.changes === 1 && event.kind.startsWith("checkout.")) {
      markPaidIfComplete(event.data.checkout);
    }

    db.exec("COMMIT");
  } catch (error) {
    db.exec("ROLLBACK");
    throw error;
  }

  return new Response(null, { status: 200 });
}

A route handler gets a standard Web Request and nothing parses it for you. await request.text() returns the body exactly as CoinStack sent it, which is what the HMAC was computed over. Do not call request.json() and then JSON.stringify the result for the check: key order and whitespace can change, and the signature stops matching. Read the text once, verify it, then JSON.parse it.

The verify function is the one in the CoinStack webhooks guide with TypeScript types added. It reads the secret inside the function rather than at module level, so next build does not need production secrets. Route handlers run on the Node.js runtime by default, which node:crypto and node:sqlite need; do not add export const runtime = "edge" to this file.

The event ID insert and the order update share one transaction. A duplicate delivery inserts nothing and changes nothing. A crash in between rolls both back, the handler returns 500, and CoinStack retries the event later, up to 8 attempts over about a day. Answer within 10 seconds; a redirect or any non-2xx status counts as a failed delivery. Reliable payment webhooks goes further into queues and replays.

What in a Next.js app can block the webhook?

The handler can be correct and still never see an event. These are the causes to check, most of them configuration elsewhere in the project:

CauseWhat CoinStack getsFix
An auth check in proxy.ts (formerly middleware.ts) covers /apiA redirect to your sign-in page or a 401Exclude /api/webhooks in the proxy matcher
trailingSlash: true in next.config.jsA redirect from /api/webhooks/coinstack to the slashed URLRegister the URL with the trailing slash
Preview deployments behind a password or SSO wallThat wall's sign-in pagePoint the webhook at a deployment that is publicly reachable
The webhook URL uses an IP address or plain http://No deliveries, because the URL must be https:// on a domain nameUse a domain with a valid certificate

Next.js 16 renamed middleware to proxy, and the proxy page's own examples show a negative matcher that skips api, which is the pattern you want here. The trailingSlash reference confirms that with the option set, /about "will redirect to /about/", and a redirect is a failed delivery for CoinStack.

Run it locally

  1. Start next dev, expose port 3000 over HTTPS with a tunnel, and set BASE_URL in .env.local to the tunnel address.
  2. Open /orders/1 once. It returns a 404, but loading lib/db.ts creates the tables.
  3. Add a test order: sqlite3 shop.db "INSERT INTO orders (amount, currency) VALUES ('1.00', 'USD');".
  4. Add a webhook in the dashboard for https://your-tunnel-domain/api/webhooks/coinstack, put its secret in .env.local and restart next dev.
  5. Select Send test on the webhook. It sends a sample checkout.completed for a $10 checkout this app never created, so the route answers 200 and no order changes.
  6. Open /orders/1, select Pay with crypto, pay the $1 checkout, and return with Return to merchant.

The test order uses the $1 minimum because a real $1 payment is the cheapest test of the whole path: the checkout page, settlement to your wallet and the webhook that marks the order paid. Pay it with a stablecoin on a low-cost network, such as USDC on Base. How to test a crypto checkout has the cases worth trying before launch, including an underpayment.

Frequently asked questions

Can I deploy this to a serverless host?

The Next.js code, yes. The SQLite file, no: serverless functions do not share a persistent disk, so each instance would see its own empty shop.db. Replace lib/db.ts with a hosted database and keep the same rules: a unique key on event_id, the event insert and the order update in one transaction, and a conditional update that only moves an order to paid.

Can I use the Edge runtime for the webhook route?

Keep the webhook on the default Node.js runtime. This handler depends on node:crypto for the HMAC and constant-time comparison, and on a Node database module. An Edge version would need the Web Crypto API instead and a database client that runs there, which adds work and buys nothing for a request that arrives a few times per order.

How is the Pages Router version different?

An API route in pages/api parses JSON bodies by default, so the raw bytes are gone before your handler runs. Disable that with export const config = { api: { bodyParser: false } } and read the request stream yourself into a string before verifying. Checkout creation is the same server-side fetch, called from an API route instead of a server action.

Can a Client Component start the payment?

Yes, by calling the server action, as the form here does. The action runs on the server with access to the key, and the component only receives the redirect. What a Client Component must never do is call the CoinStack API itself, since that requires the key in the browser bundle. For an Express backend instead of Next.js, see the Node.js and Express tutorial.

More posts