Skip to Content
better-auth-nuvion

Multi-tenant keys

Let each customer bring their own Nuvion key and webhook, using the plugin's fetch option and a small webhook proxy.

The plugin takes one apiKey and one webhookSecret, which is right when your platform owns the Nuvion account. If instead each of your customers connects their own Nuvion sandbox or account (as the example app does), you need a different key per request and a different webhook secret per customer. The plugin supports the first through its fetch option and the second with a small receiver in front of it.

Built in: per-tenant keys and webhook secrets

If each tenant is its own Nuvion customer, give the plugin functions instead of strings:

nuvion({
  apiKey: async (organizationId) => keyFor(organizationId),        // the key of the tenant that owns this organization
  webhookSecret: async (tenant) => secretFor(tenant),              // tenant comes from the URL, null on /nuvion/webhook
})

Register each tenant's webhook at https://your-app.example.com/api/auth/nuvion/webhook/<tenant>. Checkouts, transfers and status lookups use the paying organization's key. The receiving account's number is read with the receiving organization's key. A function that returns an empty value fails the call, so a missing key is an error, not a silent fallback.

Per-tenant secrets depend on confirmEvents (the default): a tenant that holds a valid secret could otherwise sign an event naming another tenant's payment. The plugin retrieves the checkout with the payment organization's own key before it acts, so a forged reference does not match.

The patterns below achieve the same thing outside the plugin, and still work.

Per-customer API keys

fetch is the function the plugin uses for every Nuvion call. Give it one that sets the Authorization header for the customer in context:

import { AsyncLocalStorage } from "node:async_hooks";

export const tenant = new AsyncLocalStorage<{ userId: string }>();

const nuvionFetch: typeof fetch = async (input, init) => {
  const url = new URL(typeof input === "string" || input instanceof URL ? input : input.url);
  if (url.origin !== "https://api.nuvion.dev") throw new Error("unexpected host"); // never send a key elsewhere
  const key = await loadKeyFor(tenant.getStore()?.userId); // decrypt the customer's stored key
  const headers = new Headers(init?.headers);
  headers.set("Authorization", `Bearer ${key}`);
  return fetch(input, { ...init, headers });
};

nuvion({ apiKey: "per-customer", webhookSecret: INTERNAL_SECRET, fetch: nuvionFetch });

Run your route handlers inside tenant.run({ userId }, ...) after you resolve the session, so the plugin's calls pick up the right key. Store keys encrypted on the server (for example AES-GCM), never in the browser: splits and retries are triggered by Nuvion's webhooks, when no browser is open.

Per-customer webhook secrets

Give each customer a private URL, for example /api/nuvion/webhook/<token>. That route:

  1. looks up the customer by the token and loads their signing secret,
  2. verifies the delivery itself (HMAC-SHA256 over {timestamp}.{raw body}, with a timestamp window),
  3. forwards the event to the plugin's own handler, re-signed with an internal secret, inside tenant.run({ userId }, ...).
const forward = new Request(new URL("/api/auth/nuvion/webhook", req.url), {
  method: "POST",
  headers: {
    "x-nuvion-event-id": req.headers.get("x-nuvion-event-id")!,
    "x-nuvion-event-timestamp": now,
    "x-nuvion-event-signature": hmac(INTERNAL_SECRET, `${now}.${raw}`),
  },
  body: raw,
});
return tenant.run({ userId }, () => auth.handler(forward));

The plugin's webhookSecret is then the internal secret, which only your server knows, so nobody can post straight to /api/auth/nuvion/webhook.

Why this is a pattern, not a feature

webhookSecret is a single string today. A resolver ((request) => secret) or a credentials hook in the plugin would remove the proxy. It is listed in Status.

The example's source for all of this is lib/nuvion-fetch.ts, lib/tenant.ts and app/api/nuvion/webhook/[token]/route.ts.

On this page