Skip to Content
Baseera Docs

Next.js

Use Baseera in the Next.js App Router, with a client provider and a token route handler.

Baseera works in the App Router. The React and UI packages start with "use client", so a client component can import them. Your layout stays a server component, and the token is signed in a route handler.

1. The token route handler

app/api/baseera-token/route.ts
import { signUserToken } from "@baseera/node";

export const dynamic = "force-dynamic";

const NO_STORE = { "cache-control": "no-store" } as const;

export async function POST(request: Request) {
  // Only accept a same-origin request, so another site cannot ask a visitor's browser for a token.
  const origin = request.headers.get("origin");
  const host = request.headers.get("host");
  let sameOrigin = false;
  try {
    sameOrigin = !!origin && !!host && new URL(origin).host === host;
  } catch {
    sameOrigin = false;
  }
  if (!sameOrigin) return Response.json({ error: "forbidden" }, { status: 403, headers: NO_STORE });

  const user = await getCurrentUser(request); // your own session check
  if (!user) return Response.json({ error: "unauthorized" }, { status: 401, headers: NO_STORE });

  const secretKey = process.env.BASEERA_SECRET_KEY;
  if (!secretKey) return Response.json({ error: "not_configured" }, { status: 500, headers: NO_STORE });

  const token = await signUserToken(
    { userId: user.id, tenantId: user.orgId, name: user.name, locale: user.locale },
    secretKey,
  );
  return Response.json({ token }, { headers: NO_STORE });
}

BASEERA_SECRET_KEY has no NEXT_PUBLIC_ prefix, so Next.js keeps it on the server. Set cache-control: no-store so a CDN never caches a token.

2. The client provider

app/providers.tsx
"use client";
import "@baseera/ui/baseera.css";
import { BaseeraProvider } from "@baseera/react";
import { BaseeraSurface } from "@baseera/ui/connected";
import type { ReactNode } from "react";

async function getUserToken(): Promise<string> {
  const res = await fetch("/api/baseera-token", { method: "POST" });
  if (!res.ok) throw new Error(`The token route answered ${res.status}.`);
  return ((await res.json()) as { token: string }).token;
}

export function Providers({ locale, children }: { locale: "ar" | "en"; children: ReactNode }) {
  return (
    <BaseeraProvider
      publishableKey={process.env.NEXT_PUBLIC_BASEERA_KEY!}
      baseUrl={process.env.NEXT_PUBLIC_BASEERA_URL!}
      getUserToken={getUserToken}
      theme="system"
    >
      {children}
      <BaseeraSurface locale={locale} />
    </BaseeraProvider>
  );
}

3. The layout

app/layout.tsx
import type { ReactNode } from "react";
import { Providers } from "./providers";

export default function RootLayout({ children }: { children: ReactNode }) {
  return (
    <html lang="ar" dir="rtl">
      <body>
        <Providers locale="ar">{children}</Providers>
      </body>
    </html>
  );
}

Register tools and context per page

Hooks run in client components. Mount a small component that calls them, and render it in a server page:

app/invoices/[id]/page.tsx
import { InvoiceTools } from "@/components/invoice-tools";
import { PageContext } from "@/components/page-context";

export default async function Page({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const invoice = await loadInvoice(id);
  return (
    <>
      <PageContext page={`/invoices/${id}`} entity={{ type: "invoice", ref: id, title: invoice.number }} />
      <InvoiceTools />
      <InvoiceView invoice={invoice} />
    </>
  );
}
components/page-context.tsx
"use client";
import { useBaseeraContext, type BaseeraContextInput } from "@baseera/react";

export function PageContext(context: BaseeraContextInput) {
  useBaseeraContext(context);
  return null;
}

Server component notes

  • Do not call a Baseera hook in a server component. Hooks, BaseeraProvider and every component from @baseera/ui need the browser.
  • Props that cross from a server to a client component must be serializable. A tool's run function lives in the client component, not in a server page.
  • signUserToken, verifyFinish, verifyWebhook and createBaseera belong in route handlers or server actions, never in a client component.
  • The provider reads nothing from window while rendering, so server rendering and hydration are safe. The session id is read from sessionStorage after mount.

If your page sets a Content Security Policy, allow connect-src for your runtime URL. Allow img-src blob: if the agent has an uploaded logo.

Next steps

On this page