Skip to content
BuildBase

Going to Production

Everything between the 5-minute quickstart and a production-ready SaaS app.

The quickstart gets you a working demo. Here is what to configure before real users sign in.

1. Environment variables

Create a .env.local file in your project root. Never commit this file.

# BuildBase
NEXT_PUBLIC_BUILDBASE_SERVER_URL=https://api.console.buildbase.app
NEXT_PUBLIC_BUILDBASE_ORG_ID=your-org-id
NEXT_PUBLIC_BUILDBASE_CLIENT_ID=your-client-id
NEXT_PUBLIC_BUILDBASE_REDIRECT_URL=http://localhost:3000/callback

# Server-only - never expose with a NEXT_PUBLIC_ prefix
BUILDBASE_CLIENT_SECRET=your-client-secret

# Session secret (used to sign httpOnly cookies)
SESSION_SECRET=run-openssl-rand-hex-32

Production leaves NEXT_PUBLIC_BUILDBASE_ENVIRONMENT out, or empty: with no environment set, the SDK talks to production. A development or staging deployment sets it to that environment's key (Environments), which needs @buildbase/sdk 1.0.0 or later: an older SDK ignores the key and talks to production.

Update your provider to read from env:

<SaaSOSProvider
  serverUrl={process.env.NEXT_PUBLIC_BUILDBASE_SERVER_URL!}
  version={ApiVersion.V1}
  orgId={process.env.NEXT_PUBLIC_BUILDBASE_ORG_ID!}
  auth={{
    clientId: process.env.NEXT_PUBLIC_BUILDBASE_CLIENT_ID!,
    redirectUrl: process.env.NEXT_PUBLIC_BUILDBASE_REDIRECT_URL!,
    callbacks: { /* ... */ },
  }}
>

2. Auth callback API route

The quickstart shows fetch('/api/auth/token') - here's the actual implementation. This route calls BuildBase's token endpoint (POST /api/v1/auth/token) to exchange the auth code for a session, then sets an httpOnly cookie. The exchange requires your clientSecret, which is why it runs on your backend - the secret must never reach the browser.

// app/api/auth/token/route.ts
import { cookies } from 'next/headers';

export async function POST(req: Request) {
  const { code } = await req.json();

  // Exchange the auth code for a session
  const res = await fetch(
    `${process.env.NEXT_PUBLIC_BUILDBASE_SERVER_URL}/api/v1/auth/token`,
    {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        code,
        orgId: process.env.NEXT_PUBLIC_BUILDBASE_ORG_ID,
        clientId: process.env.NEXT_PUBLIC_BUILDBASE_CLIENT_ID,
        clientSecret: process.env.BUILDBASE_CLIENT_SECRET,
      }),
    }
  );

  if (!res.ok) {
    // Pass on the platform's reason and status ("Invalid client secret",
    // "Invalid or expired authorization code"), never the secret itself.
    const refusal = (await res.json().catch(() => null)) as {
      message?: unknown;
      code?: unknown;
    } | null;
    return Response.json(
      {
        error: 'Sign-in failed',
        ...(typeof refusal?.message === 'string'
          ? { message: refusal.message }
          : {}),
        ...(typeof refusal?.code === 'string' ? { code: refusal.code } : {}),
      },
      { status: res.status }
    );
  }

  const { data } = await res.json(); // { sessionId, user }

  // Set httpOnly cookie, Secure whenever the request came over https
  const cookieStore = await cookies();
  cookieStore.set('bb-session-id', data.sessionId, {
    httpOnly: true,
    // From the request, not NODE_ENV: a production build on a plain-http
    // host (a staging box) would set a Secure cookie the browser drops.
    secure: new URL(req.url).protocol === 'https:',
    sameSite: 'lax',
    path: '/',
    maxAge: 60 * 60 * 24 * 30, // 30 days
  });

  return Response.json({ sessionId: data.sessionId });
}

A development or staging deployment sends the environment's id, <orgId>-<key>, as orgId. From SDK 1.0.0, environmentId() from @buildbase/sdk builds it for you, and returns the bare org id in production: environmentId(process.env.NEXT_PUBLIC_BUILDBASE_ORG_ID!, process.env.NEXT_PUBLIC_BUILDBASE_ENVIRONMENT). See From your own server routes.

// app/api/auth/session/route.ts
import { cookies } from 'next/headers';

export async function GET() {
  const cookieStore = await cookies();
  const sessionId = cookieStore.get('bb-session-id')?.value ?? null;
  return Response.json({ sessionId });
}
// app/api/auth/signout/route.ts
import { cookies } from 'next/headers';

export async function POST() {
  const cookieStore = await cookies();
  cookieStore.delete('bb-session-id');
  return Response.json({ ok: true });
}

3. Project structure

A typical Next.js + BuildBase project:

app/
├── api/
│   └── auth/
│       ├── verify/route.ts     ← exchanges code for session
│       ├── session/route.ts    ← returns session from cookie
│       └── signout/route.ts    ← clears session cookie
├── (auth)/
│   ├── login/page.tsx          ← public pages
│   └── register/page.tsx
├── (app)/
│   ├── layout.tsx              ← wraps in BuildBaseProvider
│   ├── dashboard/page.tsx      ← protected pages
│   ├── settings/page.tsx
│   └── billing/page.tsx
├── layout.tsx                  ← root layout (fonts, global styles)
└── providers.tsx               ← BuildBaseProvider component

4. Protect your routes

Wrap your authenticated layout so unauthenticated users can't access app pages:

// app/(app)/layout.tsx
'use client';

import {
  useSaaSAuth,
  WhenAuthenticated,
  WhenUnauthenticated,
} from '@buildbase/sdk/react';

export default function AppLayout({ children }: { children: React.ReactNode }) {
  const { isLoading, signIn } = useSaaSAuth();

  if (isLoading) return <LoadingSpinner />;

  return (
    <>
      <WhenAuthenticated>{children}</WhenAuthenticated>
      <WhenUnauthenticated>
        <button onClick={() => signIn()}>Sign In</button>
      </WhenUnauthenticated>
    </>
  );
}

5. Console setup checklist

Before going live, check each of these in the BuildBase console. From sign-up to a running app shows the first five screen by screen.

  1. Your organization. On the organization picker press Create organization, then pick a plan on Start free. Step by step.
  2. A sender. Messaging > Sender accounts, Add new sender: SMTP, Gmail, Mailgun or Amazon SES. Without one, no sign-in code or password reset is delivered. Step by step, and each provider.
  3. Sign-in methods. User management > Access > Authentication, Methods tab: add Email/Password, Google, Magic link or any other. Every method has a guide.
  4. An auth client, with its values. On the Settings tab of Authentication, create a client and copy the orgId, clientId and clientSecret from the dialog that shows them once. Step by step.
  5. Your production redirect URL on that client, such as https://yourapp.com/callback, with the methods ticked. Step by step.
  6. Stripe, if you sell plans. Billing > Credentials: enter your Stripe API keys (test keys for development). Until a secret key is saved, Billing shows only Credentials. See Billing.
  7. Billing currencies. Settings > General, card Billing currencies: pick the currencies you charge in. A saved currency cannot be removed.
  8. Plans. Billing > Plans: at least one plan, once Stripe is connected and a currency is set.

When your organization uses development and staging environments, Home in production shows Before production goes live: a row for each of payment credentials, auth clients and senders that is not ready yet, each with a button to the screen that fixes it. It stays dismissed in that browser once you close it.

Before production goes live on production's Home: Sign-in returns to localhost, naming the client Acme Analytics, with its Auth clients button highlighted

A method shows on the hosted login page only once it is ticked on your client, in the client's Settings tab. With Email/Password ticked, the login form has a Forgot password? link: it emails a 6-digit code, and the person sets a new password with it on the next screen. See Authentication for the details.

6. Production environment

For production, update your environment variables:

# .env.production
NEXT_PUBLIC_BUILDBASE_SERVER_URL=https://api.console.buildbase.app
NEXT_PUBLIC_BUILDBASE_ORG_ID=your-org-id
NEXT_PUBLIC_BUILDBASE_CLIENT_ID=your-client-id
NEXT_PUBLIC_BUILDBASE_REDIRECT_URL=https://yourapp.com/callback

BUILDBASE_CLIENT_SECRET=your-client-secret
SESSION_SECRET=your-production-secret

Key differences from development:

  • REDIRECT_URL must be your production domain (not localhost)
  • Add the production redirect URL in the dashboard under User management > Access > Authentication. It is an https:// (or http://) address, or a native app's own scheme such as myapp://callback. javascript:, data:, vbscript:, file:, blob:, about: and filesystem: are refused when you save, and an entry saved with one before is never used
  • Use real Stripe keys instead of test keys
  • Serve over https so session cookies are Secure (the route above sets secure from the request's protocol, so a plain-http staging host still works)

Multi-tenant apps on subdomains

If every tenant gets its own subdomain (acme.app.example.com), you do not need one redirect URL per tenant. Register a single wildcard instead:

https://*.app.example.com/callback

The * stands for exactly one label, so acme.app.example.com and globex.app.example.com both match while a.b.app.example.com does not. Everything else is still compared exactly - scheme, port and path - and the wildcard is only allowed as the first label of the domain, never in the path.

A few rules worth knowing before you rely on it:

  • https only, except on localhost, where http://*.localhost:3000/callback works so you can test tenant subdomains locally.
  • The domain must be one you could own. *.com, *.co.uk and *.vercel.app are rejected - they are public suffixes, not domains.
  • Wildcards are console-only. Clients that register themselves through Dynamic Client Registration cannot request a wildcard; an admin has to add it.

The same pattern also covers social login and magic links from tenant subdomains, so those work without extra entries too.

7. Deployment checklist

Before your first deploy:

  • Environment variables set in your hosting platform (Vercel, Railway, etc.)
  • Production redirect URL added in BuildBase dashboard
  • Auth methods enabled (email, social, magic link)
  • At least one plan created and published (if using billing)
  • Stripe connected with live keys (if using billing)
  • Email sender configured (for transactional emails)
  • Test the full sign-in → dashboard → sign-out flow in production

Next Steps

  • Authentication - Deep dive into auth methods and sessions.
  • Billing - Set up plans, checkout, and subscriptions.
  • Server SDK - Backend operations: usage recording, credits, notifications.
  • Self-Hosted - Deploy on your own infrastructure.