Authaz logoAuthaz
DocumentationAPI Reference
  • Get Started

    • Authaz
    • Core Concepts
    • Set up your app
    • Quickstart — cURL
  • Authentication

    • Authentication Settings
    • Signup
    • Invitations
    • Password Authentication
    • Multi-Factor Auth
    • Magic Link
    • OAuth / Social Login
    • Passkey (WebAuthn)
    • SAML SSO
    • Machine-to-Machine (M2M)
    • API Keys
  • Authorization

    • Authorization
    • Resources
    • Policies
    • Roles
    • Access Explorer
  • Tenancy

    • Multi-tenancy
    • Tenancy Customization
  • Brand & Host

    • Branding
    • Custom Domains
    • Communications & Email Templates
  • Operate

    • Users
    • Analytics
    • Audit Logs
    • Application Settings
  • SDK Quickstarts

    • Quickstart — Next.js
    • Quickstart — React SPA
    • Quickstart — Hono
    • Quickstart — .NET (Authaz.Sdk)
  • Recipes

    • Recipes & Cookbook
    • Next.js — first integration
    • Next.js — B2B SaaS (multi-tenant)
    • Hono — first integration
    • Hono — B2B SaaS (multi-tenant)
    • React SPA — first integration
    • React SPA — B2B SaaS (multi-tenant)
    • .NET — first integration
    • .NET — B2B SaaS (multi-tenant)
  • Reference

    • Tokens
    • API Reference
    • Errors & Troubleshooting
  • Documentation

    • How Authaz is Built
  1. Authaz
  2. Docs
  3. Recipes
  4. Next.js — B2B SaaS (multi-tenant)

Recipes

Next.js — B2B SaaS (multi-tenant)

3 min read·Updated Jun 19, 2026

← All recipes · First time? Set up your app (60 seconds — keys + redirect URI)

A Next.js app where each customer is a tenant, users may belong to multiple tenants, and roles are scoped per tenant. Builds on the single-tenant recipe — read that first; this page only shows the deltas.

1. What you'll build#

A Next.js B2B SaaS app where the user signs in, picks a tenant (Authaz Sign-In handles this UI), and your /dashboard reads tenant_id from the access token to scope every query.

2. Application setup#

Create the app as multi-tenant, shared pool:

POST https://your-app.authaz.io/api/v1/applications
X-API-Key: mgmt_01h...
Content-Type: application/json
 




Previous
Next.js — first integration
Next
Hono — first integration
{
"name": "my-saas",
"tenancy_type": "multi_tenant",
"tenancy_mode": "shared"
}

Provision a tenant (one per customer):

POST https://your-app.authaz.io/api/v1/tenants
X-API-Key: mgmt_01h...
 
{ "name": "Acme Corp" }

Note the returned tenant_id. Invite the customer's first user:

POST https://your-app.authaz.io/api/v1/tenants/{tenantId}/invitations
X-API-Key: mgmt_01h...
 
{ "email": "founder@acme.com", "roles": ["admin"] }

3. Install#

Same as single-tenant, plus jose for decoding the access token to read tenant claims:

pnpm add @authaz/next jose

4. Configure#

.env.local adds nothing tenant-specific — tenant binding happens at login time, not in env vars:

AUTHAZ_CLIENT_ID=app_01h...
AUTHAZ_CLIENT_SECRET=secret_...
AUTHAZ_ORGANIZATION_ID=0199...
AUTHAZ_API_KEY=mgmt_01h...

5. Wire it up#

The catch-all handler, callback page, and middleware are identical to the single-tenant recipe. The only delta is reading the tenant.

When a user belongs to multiple tenants, Authaz Sign-In shows a tenant picker after primary authentication. The chosen tenant is bound into the access token's tenant_id claim — your app doesn't need to render any tenant-selection UI.

6. Read the user and tenant#

Decode the access token in a server component to pull the tenant_id claim. lib/session.ts:

import { getAccessToken } from "@authaz/next";
import { decodeJwt } from "jose";
 
type AuthazClaims = {
  sub: string;
  email?: string;
  tenant_id?: string;
  roles?: string[];
};
 
export async function getSession() {
  const token = await getAccessToken();
  if (!token) return null;
  const claims = decodeJwt(token) as AuthazClaims;
  return {
    userId: claims.sub,
    email: claims.email,
    tenantId: claims.tenant_id ?? null,
    roles: claims.roles ?? [],
    accessToken: token,
  };
}

app/dashboard/page.tsx:

import { redirect } from "next/navigation";
import { getSession } from "@/lib/session";
 
export default async function Dashboard() {
  const s = await getSession();
  if (!s) redirect("/api/auth/login");
  if (!s.tenantId) {
    return <p>Sign in again to pick a tenant.</p>;
  }
  return (
    <main>
      <h1>Hello, {s.email}</h1>
      <p>Tenant: <code>{s.tenantId}</code></p>
    </main>
  );
}

Verify the JWT signature in production. decodeJwt only parses; pair it with jwtVerify against your application's JWKS at https://your-app.authaz.io/.well-known/jwks.json. The middleware-level cookie check is enough for the redirect gate; signature verification protects against tampered tokens reaching your business logic.

7. Tenant-scoped permission check#

Always pass tenant_id into authorization checks. Use the SDK's built-in management proxy at /api/auth/...:

// app/api/invoices/route.ts
import { withAuth, getAccessToken } from "@authaz/next";
import { decodeJwt } from "jose";
 
export const POST = withAuth(async (req) => {
  const claims = decodeJwt(await getAccessToken() as string) as {
    sub: string; tenant_id?: string;
  };
  if (!claims.tenant_id) {
    return Response.json({ error: "no_tenant" }, { status: 403 });
  }
 
  const check = await fetch("https://your-app.authaz.io/api/v1/authz/check", {
    method: "POST",
    headers: {
      "X-API-Key": process.env.AUTHAZ_API_KEY!,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      user_id: claims.sub,
      permission: "invoices:create",
      tenant_id: claims.tenant_id,
    }),
  }).then(r => r.json());
 
  if (!check.allowed) return Response.json({ error: "forbidden" }, { status: 403 });
 
  // …create the invoice scoped to claims.tenant_id…
  return Response.json({ ok: true });
});

8. Common gotchas#

  • Never read tenant_id from a query string, header, or request body. It must come from the access token. Anything else is a cross-tenant escalation vector.
  • Pass tenant_id to every authorization check. A check without it falls back to a global scope, which is almost never what a B2B SaaS wants.
  • Tenant switching = new login. A user changing tenants must go back through /api/auth/login. The token is bound to one tenant_id for its lifetime.
  • Don't cache the tenant in your own session store keyed only by user. Key it by (user_id, tenant_id).
  • Verify the JWT signature server-side before trusting any claim in production code paths.

9. Next steps#

  • Multi-tenancy guide — shared vs isolated pools, tenant lifecycle
  • Architecture — tenant isolation — JWT binding, RLS, cryptographic isolation per organization
  • Authorization — Zeratul checks, tenant-scoped role assignment