Skip to Content
better-auth-nuvion

TanStack Start and Router

Use the plugin in a TanStack Start app, with the server route, a server function for checkout, and the client in a route.

TanStack Start runs on the server and the client from one codebase, so the whole plugin fits: the Better Auth handler (and with it the Nuvion webhook) is a server route, checkout can be a server function, and the typed client works in your routes.

This page was checked against a small app on TanStack Start 1.169 and TanStack Router 1.170 (Vite 8): the handler route, a server function that creates a payment, the sign-in and connect flow in the browser, and an unsigned webhook answering 401. TanStack Start is moving quickly, so if a name below differs in your version, follow its release notes and keep the shape.

Mount the handler

A server route under /api/auth/$ passes every request to Better Auth. The Nuvion webhook is handled inside it, at /api/auth/nuvion/webhook, with the raw request body the signature check needs.

src/routes/api/auth/$.ts
import { createFileRoute } from "@tanstack/react-router";
import { auth } from "../../../lib/auth";

export const Route = createFileRoute("/api/auth/$")({
  server: {
    handlers: {
      GET: ({ request }: { request: Request }) => auth.handler(request),
      POST: ({ request }: { request: Request }) => auth.handler(request),
    },
  },
});

Add the plugin

Add tanstackStartCookies() as the last plugin, so calls to auth.api inside server functions can set cookies.

src/lib/auth.ts
import { betterAuth } from "better-auth";
import { tanstackStartCookies } from "better-auth/tanstack-start";
import { apiKey } from "@better-auth/api-key";
import { organization } from "better-auth/plugins";
import { nuvion } from "@umohpyro/better-auth-nuvion";
import { db } from "./db";

export const auth = betterAuth({
  database: db,
  emailAndPassword: { enabled: true },
  plugins: [
    organization(),
    apiKey(),
    nuvion({
      apiKey: process.env.NUVION_API_KEY!,
      webhookSecret: process.env.NUVION_WEBHOOK_SECRET!,
    }),
    tanstackStartCookies(), // keep it last
  ],
});

Create the tables with your usual migration (Installation).

The client

The typed client is the same as anywhere (Client). Use it in your routes for sign-in, organizations, binding and listing payments.

src/lib/auth-client.ts
import { nuvionClient } from "@umohpyro/better-auth-nuvion/client";
import { organizationClient } from "better-auth/client/plugins";
import { createAuthClient } from "better-auth/react";

export const authClient = createAuthClient({
  plugins: [organizationClient(), nuvionClient()],
});
src/routes/payments.tsx
import { useEffect, useState } from "react";
import { createFileRoute } from "@tanstack/react-router";
import { authClient } from "../lib/auth-client";

export const Route = createFileRoute("/payments")({ component: Payments });

function Payments() {
  const orgs = authClient.useListOrganizations();
  const org = orgs.data?.[0];
  const [payments, setPayments] = useState<{ id: string; status: string }[]>(
    [],
  );

  useEffect(() => {
    if (!org) return;
    authClient.nuvion.payments
      .list({ query: { organizationId: org.id } })
      .then((r) => setPayments(r.data?.payments ?? []));
  }, [org]);

  return (
    <ul>
      {payments.map((p) => (
        <li key={p.id}>{p.status}</li>
      ))}
    </ul>
  );
}

Checkout as a server function

A server function keeps the call on the server and gives the page only the checkout address. Pass the request headers to auth.api so the plugin sees the signed-in user.

src/lib/checkout.functions.ts
import { createServerFn } from "@tanstack/react-start";
import { getRequestHeaders } from "@tanstack/react-start/server";
import { auth } from "./auth";

export const startCheckout = createServerFn({ method: "POST" })
  .validator((d: { organizationId: string; redirectUrl: string }) => d)
  .handler(async ({ data }) => {
    const payment = await auth.api.createPayment({
      headers: getRequestHeaders(),
      body: {
        organizationId: data.organizationId,
        amountMinor: 100,
        currency: "GBP",
        redirectUrl: data.redirectUrl,
      },
    });
    return { checkoutUrl: payment.checkoutUrl };
  });
const { checkoutUrl } = await startCheckout({
  data: { organizationId: org.id, redirectUrl: location.href },
});
if (checkoutUrl) location.href = checkoutUrl;

The validator method

In TanStack Start 1.169 the method is .validator(...). Newer releases may call it .inputValidator(...). The TypeScript compiler tells you which your version has.

For more code on checkout, hooks and refunds, see Recipes and Accept payments for an online shop: they use auth.api and authClient, which work the same here.

Environment variables

In development, TanStack Start loads .env.local into process.env for server code, so NUVION_API_KEY and NUVION_WEBHOOK_SECRET need no extra step. Only variables prefixed VITE_ are exposed to the browser, so never prefix the Nuvion key. The migration script runs under tsx, which does not load .env.local by itself: use tsx --env-file-if-exists=.env.local scripts/migrate.mts.

The webhook

Register https://<your-host>/api/auth/nuvion/webhook in Nuvion. It needs a public https address, so use a tunnel locally (Local development). To check the route is mounted correctly, send an unsigned request: it must answer 401 (Testing).

TanStack Router without Start

TanStack Router on its own is a client-side router. It can use authClient as above, but it has no server, so the Better Auth handler, the plugin and the webhook must run on a server you already have: a Start app, Hono, Express or any other (Recipes). Point createAuthClient({ baseURL }) at that server and add its address to Better Auth's trustedOrigins.

On this page