# Node.js and Express
Source: https://docs.zahlo.eu/integrations/node

Call the merchant API only from your server. The browser gets a session `url` (hosted) or a session ID and client token (embedded); it never gets the API key or the webhook secret.

The maintained, dependency-free example is the [website quickstart](/quickstarts/ecommerce-hosted-website) server (`snippets/code/website-node/server.mjs`). This page shows the same pieces in Express. It runs on Node 18 or later with the built-in `fetch`.

## Client

One function sets the origin, the API key, a timeout and the `Idempotency-Key`. Every POST gets one key, which is reused on each retry, so a retry can never create a second object. Retry only on a network error, `409 request_in_progress`, `429` or `5xx`, at most twice, honouring `Retry-After`.

```javascript


const apiKey = process.env.ZAHLO_API_KEY; // zk_test_… = test mode, zk_live_… = live
const apiBase = "https://merchant.zahlo.eu";

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const retryable = (status, code) =>
  status === 429 || status >= 500 || (status === 409 && code === "request_in_progress");

export async function zahlo(method, path, { body, idempotencyKey } = {}) {
  const key = method === "POST" ? (idempotencyKey ?? randomUUID()) : undefined;
  for (let attempt = 0; ; attempt += 1) {
    let response;
    try {
      response = await fetch(`${apiBase}/api/v1${path}`, {
        method,
        body: body === undefined ? undefined : JSON.stringify(body),
        headers: {
          "content-type": "application/json",
          "x-api-key": apiKey,
          ...(key ? { "idempotency-key": key } : {}),
        },
        signal: AbortSignal.timeout(15_000),
      });
    } catch (error) {
      if (attempt < 2) { await sleep(500 * 2 ** attempt); continue; }
      throw error;
    }
    if (response.ok) return response.status === 204 ? undefined : response.json();
    const payload = await response.json().catch(() => ({}));
    const code = payload?.error?.code ?? "unknown";
    if (attempt < 2 && retryable(response.status, code)) {
      await sleep(Number(response.headers.get("retry-after") ?? 0) * 1000 || 500 * 2 ** attempt);
      continue;
    }
    const error = new Error(payload?.error?.message ?? response.statusText);
    Object.assign(error, { status: response.status, code, requestId: payload?.requestId });
    throw error;
  }
}
```

## Create a checkout session

Compute the amount from your own order record, never from the request body, and derive the `Idempotency-Key` from the order so a double click reuses the same session.

```javascript


const app = express();

app.post("/checkout", express.urlencoded({ extended: false }), async (req, res, next) => {
  try {
    const order = await loadPendingOrder(req.body.orderId); // your database
    const session = await zahlo("POST", "/checkout-sessions", {
      idempotencyKey: `checkout-${order.id}`,
      body: {
        mode: "hosted",
        currency: "EUR",
        lineItems: order.lines.map((line) => ({
          name: line.name,
          unitAmountMinor: line.unitAmountMinor,
          quantity: line.quantity,
        })),
        reference: order.id,
        successUrl: `${process.env.SITE_URL}/orders/${order.id}`,
        cancelUrl: `${process.env.SITE_URL}/cart`,
      },
    });
    await saveSessionId(order.id, session.id);
    res.redirect(303, session.url);
  } catch (error) {
    next(error);
  }
});
```

For embedded checkout, send `mode: "embedded"` and return only `session.id` and `session.clientToken` to the page that mounts the [JavaScript SDK](/integrations/javascript-sdk).

## Webhook

Fulfil only from a verified webhook, never from the browser's return. Register the webhook route with `express.raw()` **before** any `express.json()`, because the signature covers the exact bytes Zahlo sent. `Zahlo-Signature` is `t=<unix>,v1=<hex>`, where `v1` is the HMAC-SHA256 of `<t>.<raw body>` with your endpoint secret. During a secret rotation two `v1` values are sent, and either may match.

```javascript


function verifyZahloEvent(rawBody, header, secret, toleranceSeconds = 300) {
  const parts = (header ?? "").split(",").map((part) => part.trim().split("="));
  const timestamp = Number(parts.find(([key]) => key === "t")?.[1]);
  const signatures = parts.filter(([key]) => key === "v1").map(([, value]) => value ?? "");
  if (!Number.isInteger(timestamp) || Math.abs(Date.now() / 1000 - timestamp) > toleranceSeconds) return null;
  const expected = Buffer.from(createHmac("sha256", secret).update(`${timestamp}.${rawBody}`).digest("hex"));
  const valid = signatures.some((signature) => {
    const given = Buffer.from(signature);
    return given.length === expected.length && timingSafeEqual(given, expected);
  });
  return valid ? JSON.parse(rawBody) : null;
}

app.post("/webhooks/zahlo", express.raw({ type: "application/json" }), async (req, res) => {
  const event = verifyZahloEvent(
    req.body.toString("utf8"),
    req.get("zahlo-signature"),
    process.env.ZAHLO_WEBHOOK_SECRET
  );
  if (!event) return res.sendStatus(400);
  // Deliveries repeat: record event.id and the order change in one transaction, and skip ids you have seen.
  if (event.type === "checkout.session.completed") {
    await markOrderPaid(event.data.object.id, event.data.object.paymentId);
  }
  res.sendStatus(200);
});

app.use(express.json()); // other routes
```

See [Webhook operations](/operations/webhooks) for event types, retries and local testing.

## Lists

Lists return one page (`{ object: "list", data, hasMore }`). Most lists, `/payments` included, page by cursor: pass the last item's `id` as `startingAfter` until `hasMore` is false. `/transactions` pages by `offset`. Every list answers an unknown query parameter or a cursor id it can't find with a 400 `parameter_invalid`.

```javascript
async function listAll(path) {
  const items = [];
  for (let startingAfter = ""; ; ) {
    const query = `limit=100${startingAfter ? `&startingAfter=${startingAfter}` : ""}`;
    const page = await zahlo("GET", `${path}?${query}`);
    items.push(...page.data);
    const last = page.data.at(-1);
    if (!(page.hasMore && last)) return items;
    startingAfter = last.id;
  }
}
```

## @zahlo/node

The `@zahlo/node` package wraps the same rules: retries with one `Idempotency-Key`, typed request bodies, typed errors, `for await` over every list, and `webhooks.constructEvent` returning an event typed by `event.type`. Use it once it is on npm. Until then, the code above is the supported path.
