Skip to content
James Ross
articlePublished Updated 8 min read

Better Auth in a multi-tenant SaaS: what the core covers and what you build

By James Ross

Better Auth handles sign-up, email verification, password reset, sessions and rate limiting for a Next.js SaaS, and it has an organizations plugin for tenants. We used the core only and built the tenant layer ourselves, because folder-scoped client viewers did not fit the plugin. Authentication proves who the user is; a cookie checked against a membership table decides which account they act in, and a scoped database client enforces it.

Abstract locked door opening onto separate rooms with a single key, illustrating Better Auth in a multi-tenant SaaS.

Better Auth is a good fit for a Next.js SaaS, and the useful question is how much of it to use. In TrackSERPs, a multi-tenant rank tracker, it handles the identity half of the problem: sign-up, email verification, password reset, sessions and request rate limits. The tenant half, meaning accounts, roles, invitations and the rule that one customer can never see another’s data, is built on top of it. This article lays out where that line sits and why, with the code paths that enforce it. The billing side of the same product is in the hold/charge credit ledger.

What does Better Auth cover?

The core covers authentication and sessions; plugins cover structure. The core in this project provides email and password sign-in with required verification, reset emails, session handling, change of email with verification and a rate limiter, using the Prisma adapter against PostgreSQL. The auth configuration is one file with a single plugin, the Next.js cookie plugin.

Better Auth’s Next.js documentation says the handler goes in a catch-all route and that the cookie plugin exists because server actions do not set cookies through the normal response path: it “will automatically set cookies for you whenever a Set-Cookie header is present”, and it should be the last plugin (Better Auth: Next.js integration). The same page is explicit about sessions: a cookie-existence check is for fast redirects and “only checks for the existence of a session cookie”, so protected pages and actions must validate the session on the server.

That is how the app does it. Every server entry point calls the session API with the request headers, then looks up whether the user is a platform super-admin from a separate table, and only for a verified email. The route that mounts the handler also returns 404 for requests that do not arrive on the application host, so the auth endpoints are not reachable from the marketing host.

What are the Better Auth organizations?

The organizations plugin adds multi-tenant structure: organizations, members, invitations, roles and permissions, and an active organization stored on the session. The documentation lists three default roles (owner, admin, member), custom permissions through an access-control statement, optional teams, and a schema option to rename models and fields (Better Auth: organization plugin).

For many products that is the right answer and it should be the default. It removes the invitation flow, the membership table and the role checks from your backlog.

Did we use the Better Auth organizations plugin?

No, and the decision log records the reason. The first design mapped the plugin onto our tables: organization to Account, member to Membership and invitation to Invite, with field remaps. In Phase 1 the plan changed: “Better Auth core only… The organization plugin is not used. Our own code manages Account, Membership and Invite, because CLIENT_VIEWER folder scoping doesn’t fit the plugin” (from the decision log).

The requirement was a fourth role, client_viewer, for an agency’s customers. A client viewer is a member of the agency’s account who can see only specific folders of projects, stored as a list of folder ids on the membership. A role in the plugin is a set of permissions on resource types, and the scope we needed was a set of instances. Expressing that through the plugin would have meant either dynamic roles per client or custom checks everywhere anyway.

Concern Plugin would provide What we built
Tenant record Organization Account, with plan, billing and branding fields
Membership Member Membership with role string and folder ids
Invitations Invitation flow Invite with token, expiry and status
Active tenant Active organization on the session A cookie checked against memberships
Roles Owner, admin, member plus custom owner, admin, member, client_viewer as strings

Two details of that decision are worth copying. Roles are plain strings, not a database enum, because the auth library writes role strings and validation happens in application code. And Better Auth’s own account table, which stores credentials and provider links, is renamed AuthAccount through the modelName option, so it cannot be confused with the tenant Account. The Better Auth database documentation describes modelName and fields as the way to rename tables and columns, and notes that type inference keeps using the original names (Better Auth: database).

How does multi tenant authentication work in the app?

In three steps on every request. First, validate the session and load the user. Second, resolve the active account: read the ts-account cookie, load the user’s memberships, and use the cookie’s account only if the user has a membership there, falling back to the oldest membership. Third, build a database client scoped to that account.

The cookie is a preference, not a credential. If it names an account the user does not belong to, it is ignored. A role check follows: callers can pass a list of allowed roles, and a mismatch redirects to the dashboard. A user with no memberships goes to onboarding, except a super-admin, who goes to the admin area to avoid a redirect loop.

Impersonation follows the same shape with more restrictions. A signed ts-imp cookie, valid for one hour, carries the account id and expiry with an HMAC. It is honored only for super-admins, it yields an admin-level context in the target account, and it forces the context read-only, so every mutation refuses while it is set. The token comparison uses a constant-time check and rejects a different length.

A simplified version of the account resolution shows how little code the rule needs:

const memberships = await prisma.membership.findMany({ where: { userId } });
const wanted = cookies().get("ts-account")?.value;
const active = memberships.find((m) => m.accountId === wanted) ?? memberships[0];
if (!active) redirect("/onboarding");
return { account: active.account, db: forAccount(active.accountId) };

The cookie can only choose among memberships the user already holds, so tampering with it can at worst select another of their own accounts.

How do you stop one tenant reading another’s data?

Do not rely on remembering a filter. The session helper returns a tenant-scoped database client, built from the account id, and application code uses that client for tenant data. Scoping is by model: 13 models carry an account id and are filtered directly, nine more, such as keywords, runs and snapshots, are scoped through their parent relation (counted from the tenant module). The result is that a query for a keyword always carries the project’s account, even though the keyword table has no account column.

Shared infrastructure that is not tenant data, such as the SERP result cache, sits outside the scoped client by design and is described in multi tenant architecture for a shared SERP cache.

The rule behind this is the one the tenancy articles keep repeating: isolation fails in the join and the forgotten WHERE clause, so the safe design makes the scoped path the only convenient one.

How is sign-in protected against abuse?

With two limiters at different layers. Better Auth’s own rate limiter is per client IP. Its documentation says the default in production is 100 requests per 10-second window, that custom rules can be set per path, and that custom storage “must check and increment in one operation” so concurrent requests cannot pass the same stale counter (Better Auth: rate limit). The app supplies Redis storage using one atomic script, so counters are shared by every web instance and survive a deploy. If Redis is unreachable it falls back to a per-process counter instead of blocking every sign-in. Stricter rules apply to the password-reset and verification-mail paths: five requests per 15 minutes.

The second limiter is per account. After 10 wrong passwords for one email within 15 minutes, sign-in for that email is refused until the window ends, whatever the source IP. It is wired through the before and after hooks: the before hook checks the lock and the after hook records a failure on a 401 or clears the count on success (from the throttle module and auth configuration).

The IP source matters as much as the limits. The documentation warns that Better Auth counts by X-Forwarded-For by default, which clients can forge, and says to list only a header your proxy sets itself. Production is reachable only through a tunnel that sets a client-IP header and overwrites any client-supplied value, so the configuration trusts that header alone; development accepts both.

Password rules sit in the same hook. A common-password check runs on every path that sets a password: sign-up, reset, change and set. Minimum length is enforced by Better Auth itself.

What broke and what we changed

  • The plugin did not fit the viewer role. The first design mapped the organizations plugin onto our tables. Folder-scoped client viewers could not be expressed as plugin roles, so the plan moved to core-only with our own membership layer, recorded in the decision log.
  • Table name collision. Better Auth’s account model collided in meaning with the tenant Account. It is now AuthAccount.
  • Rate-limit counters were per process. The default in-memory counter does not survive a deploy or span instances. Redis storage with an atomic check-and-increment replaced it, with an in-process fallback if Redis is down.
  • Forged client-IP header. Reading X-Forwarded-For in production would let a client choose its own bucket. Production reads only the tunnel’s client-IP header.
  • Tests collided on shared counters. Parallel suites sharing one test Redis produced false 429 responses. The web suite now runs on its own Redis database index and flushes it between runs (from the decision log).
  • The built-in OAuth plugins did not exist in the installed version. For the remote MCP server, the installed Better Auth version (1.7.18) included neither mcp nor oidcProvider, so a small OAuth 2.1 server was built in the app instead of upgrading the library (from the decision log). That story is in the OAuth 2.1 MCP server article.

When should you use the plugin instead?

When your tenant model matches it. If members are users with an organization-wide role, the plugin’s organizations, invitations and access-control statements save real work, and teams cover finer grouping. Reach for the core-only approach when a tenant rule needs data the plugin’s role model does not carry, as the folder scope did here. In either case, the monorepo layout that keeps the auth, database and tenant modules separate is described in what 24 TypeScript packages buy a SaaS product.

Frequently asked questions

What is Better Auth?

Better Auth is a TypeScript authentication library with a plugin system. The core provides email and password, sessions, email verification and password reset, rate limiting and database adapters, including Prisma. Plugins add features such as organizations, teams and roles. It mounts in Next.js as a catch-all route handler.

Should you use the Better Auth organizations plugin for a multi-tenant app?

Use it when its model fits yours. It provides organizations, members, invitations, roles, permissions and an active organization stored on the session. If your tenant model has rules the plugin does not express, such as members scoped to specific folders, the core plus your own membership table is less work than bending the plugin.

How do you make multi tenant authentication safe?

Authentication and tenancy are separate checks. Authentication says who the user is. Authorization says which account they are acting in, and it must be validated on the server against a membership row on every request, never trusted from a cookie alone. Then scope every query by account id so one forgotten filter cannot leak data.

How do you add nextjs auth with Better Auth?

Mount the handler in a catch-all route under the auth path with the Next.js handler helper, add the Next.js cookies plugin last so server actions can set cookies, and validate sessions on the server with the session API rather than only checking that a cookie exists. Cookie-only checks are fine for redirects, not for authorization.

Does Better Auth rate limiting work behind a proxy?

Only if you configure the client IP header. By default it reads X-Forwarded-For, which a client can forge. Behind a proxy that sets its own header and overwrites any client value, list only that header. For several instances, use shared storage, with a single check-and-increment operation.