skip to content

When you mount better-auth in an Express 5 app with toNodeHandler, where do users and sessions live, and what must exist first?

level: middleimportance: nice to knowfreq 22%

answer

  1. your database, its schema
  2. four core tables
  3. basePath must match the mount
  4. a named wildcard in Express 5
  5. plugins bring more tables

basics

~20 s

better-auth keeps users, sessions, linked accounts and verification tokens in your own database, in user, session, account and verification tables it defines; those tables must exist first, and the handler is mounted with app.all('/api/auth/*splat', toNodeHandler(auth)).

solid answer

~40 s

`betterAuth({ database, emailAndPassword, socialProviders, plugins })` builds an auth instance that stores everything in **your** database through an adapter or a direct connection: a `user` table, a `session` table (rows expire after 7 days by default), an `account` table (one row per sign-in method, including the password hash for email and password under `providerId: "credential"`) and a `verification` table. Its CLI's `generate` and `migrate` commands create that schema, and plugins such as `twoFactor` add columns and tables, so you re-run them after enabling one. In Express 5 you mount `app.all('/api/auth/*splat', toNodeHandler(auth))`: the wildcard needs a name, and the mount must match `basePath`, which defaults to `/api/auth`. Your routes read the session with `auth.api.getSession({ headers: fromNodeHeaders(req.headers) })`, which returns `{ session, user }` or `null`.

code

javascript · 19 lines
javascript
import express from 'express'
import { betterAuth } from 'better-auth'
import { toNodeHandler, fromNodeHeaders } from 'better-auth/node'
import { db } from './db.js'

export const auth = betterAuth({
  database: db,
  emailAndPassword: { enabled: true },
})

const app = express()
app.all('/api/auth/*splat', toNodeHandler(auth))
app.use(express.json())

app.get('/api/me', async (req, res) => {
  const data = await auth.api.getSession({ headers: fromNodeHeaders(req.headers) })
  if (!data) return res.status(401).json({ error: 'sign in first' })
  res.json({ user: data.user })
})

go deeper

for a junior

Recall that better-auth keeps user, session, account and verification tables in your own database and is mounted with toNodeHandler.

for a middle

Explain how the mount path, the named Express 5 wildcard and basePath must line up, and how getSession reads the session from request headers.

for a senior

Plan schema changes: plugins add tables and columns, migrate needs a direct connection, and late required columns need a hand-written migration.

for a principal

Weigh owning the identity data in a library-shaped schema against hand-built tables or a hosted provider, including how each plugin grows it.

## What better-auth is in an Express app **better-auth** is a TypeScript authentication library that ships its own HTTP endpoints, its own database schema and a plugin system. You create one instance with `betterAuth({...})` and expose it to Express through **`toNodeHandler`** from `better-auth/node`, which adapts its web-standard request handler to Node's `(req, res)` signature. Nothing is stored at a vendor: every record lands in a database you run. ## Where the data lives The core schema has four models, created in your database: | Table | Holds | |---|---| | `user` | One row per person: id, name, email, verification flag, timestamps | | `session` | One row per signed-in session, with a token and `expiresAt` | | `account` | One row per sign-in method linked to a user; email and password sign-up stores the password hash here with `providerId: "credential"` | | `verification` | Short-lived values such as email-verification and reset tokens | Points worth knowing about that schema: - **Session lifetime** defaults to 7 days (`session.expiresIn`, in seconds). - **Plugins extend it.** The `twoFactor` plugin adds a `twoFactorEnabled` column to `user` and its own `twoFactor` table; `organization`, `admin` and `username` add their own fields. After enabling one, regenerate or migrate. - **Adapters choose the access layer.** better-auth 1.7.7 bundles adapters for several ORMs and query builders, a document database, and an in-memory store for tests. - **The secret matters.** `BETTER_AUTH_SECRET` (or `secret`) is the key behind its signed cookies; in production it throws if left at its built-in default value. ## Creating the schema before the first sign-up better-auth's CLI has a **`generate`** command that prints or writes the schema and a **`migrate`** command that applies it. `migrate` works only when better-auth is given a database connection directly; with an ORM adapter you generate the schema and apply it with that ORM's own migration tool. Its planner refuses to add a required column without a default to a table that already has rows, so a plugin enabled late can need a hand-written migration. ## Mounting it in Express 5 1. Build the instance once in its own module and export it. 2. Mount the handler on a **named** wildcard: `app.all('/api/auth/*splat', toNodeHandler(auth))`. In Express 5, `'/api/auth/*'` throws `Missing parameter name` at registration, because path-to-regexp v8 requires every wildcard to be named. 3. Keep the mount and **`basePath`** in agreement. `basePath` defaults to `/api/auth`, and better-auth matches its routes against the full URL; mount the same handler under `/auth/*splat` without changing `basePath` and its endpoints answer 404. 4. Set `baseURL` or `BETTER_AUTH_URL` to the public origin; without it better-auth warns and derives the origin from each request. 5. Turn on the sign-in methods you want: `emailAndPassword: { enabled: true }` for passwords, `socialProviders` for OAuth sign-in, and plugins such as `twoFactor`, `magicLink`, `emailOTP` or `organization`. ## Reading the session in your routes better-auth exposes its endpoints as server functions on `auth.api`. In an Express middleware, convert Node's headers and call: ```js const data = await auth.api.getSession({ headers: fromNodeHeaders(req.headers) }) ``` `data` is `{ session, user }` for a signed-in request and `null` otherwise. As with any `async` middleware in Express 5, a rejection from that call reaches your error-handling middleware without a wrapper. ## How it differs from express-session Teams coming from Passport often look for a session store to wire. There is none to add: better-auth writes its own `session` rows through the same adapter as its users, sets its own cookies, and reads them back in `getSession`. Things that follow from that: - **No `express-session` middleware** is mounted for better-auth's sessions, and its cookies are not readable through `req.session`. - **Revoking a session** is deleting or expiring its row, which better-auth exposes as its `revokeSession` and `revokeSessions` endpoints and server functions. - **Session reads hit the database** unless you configure its cookie cache or a secondary store, so the table and its indexes sit on the hot path of every authenticated request. ## What this buys and costs Compared with hand-wired Passport, better-auth brings sign-up, password hashing, email verification hooks, session rows and optional two-factor without you writing those routes. Compared with a hosted provider, users stay in your database, so leaving means rewriting code against data you already own. The cost is that its schema, not yours, shapes the identity tables, and every plugin you adopt adds to it.

  • You enable better-auth's twoFactor plugin on a running service. What else has to happen?
    The plugin extends the schema: a `twoFactorEnabled` column on `user` and a new `twoFactor` table for the secret and backup codes. Regenerate the schema and apply it before deploying, with `migrate` for a direct connection or your ORM's migrations for an adapter, or sign-ins that touch the plugin will fail against the old tables.
  • Where is a user's password hash kept when better-auth handles email and password sign-up?
    On an `account` row linked to the user, with `providerId: "credential"`, not on the `user` row. Each sign-in method, password or social provider, gets its own `account` row, which is how one user can sign in several ways.

  • Says better-auth stores users on the vendor's servers
  • Mounts toNodeHandler on '/api/auth/*' in an Express 5 app
  • Changes the Express mount path without changing basePath
  • Expects the tables to be created on first request without running a migration
  • Looks for the password hash on the user table

Assumes Express 5, where the catch-all mount must be a named wildcard such as '/api/auth/*splat'; Express 4 accepted '/api/auth/*'.