SkilVaultSign inStart free

Catalogue / better-auth-fullstack-setup

better-auth-fullstack-setup

Older skill: source not recordedSignedGuides wiring Better Auth into a full-stack TypeScript app with a NestJS API, Drizzle ORM and PostgreSQL persistence, and a Next.js App Router frontend. Covers the auth instance and its Drizzle table set, session guards, email and password plus social providers such as GitHub and Google, route prote…
---
name: better-auth-fullstack-setup
description: >
  Guides wiring Better Auth into a full-stack TypeScript app with a NestJS
  API, Drizzle ORM and PostgreSQL persistence, and a Next.js App Router
  frontend. Covers the auth instance and its Drizzle table set, session
  guards, email and password plus social providers such as GitHub and
  Google, route protection middleware, and plugins for TOTP two-factor
  with backup codes and trusted devices, magic links, passkeys, email
  verification, and organizations. Use when the user wants to add login
  to a NestJS, Next.js, or Drizzle project, configure OAuth providers,
  protect routes, or set up Better Auth plugins and their migrations.
  Not for non-TypeScript stacks, hosting or infrastructure setup, or
  managing identity-provider accounts themselves.
allowed-tools: Read, Write, Edit, Glob, Grep, Bash
---

Better Auth across NestJS, Next.js, and Drizzle

What you are building

A single typed authentication layer shared by a NestJS API and a Next.js frontend, with PostgreSQL as the session store via Drizzle ORM. Sessions live in the database, so any server that can read the auth tables can validate a request — that is what makes one guard reusable on both sides.

Before writing anything, confirm with the user:

  • Which app owns the auth HTTP routes (the Next.js catch-all or the NestJS controller). Pick one owner; running both creates two cookie domains.
  • Which features they want: email and password, which social providers, and which plugins. Do not scaffold plugins nobody asked for.

Workflow

  1. Verify prerequisites and install packages.
  2. Lay out environment variables (names only).
  3. Define the Drizzle auth tables.
  4. Wire the backend: database module, auth instance, controller, guard.
  5. Wire the frontend: client, pages, session access.
  6. Protect routes on both apps.
  7. Add requested plugins and their tables.
  8. Generate and apply migrations.

1. Prerequisites and installation

Confirm Node 18+, PostgreSQL 14+ reachable, and both workspaces exist. Use distinct local ports, for example the API on 4000 and the web app on 3000, and record them — origins matter for cookies later.

Install in the API workspace: better-auth, the Drizzle adapter for Better Auth, drizzle-orm, and pg; as dev dependencies drizzle-kit and @types/pg. Install better-auth in the web workspace at the same release, otherwise generated types drift apart.

2. Environment variables

| Variable | Purpose | |---|---| | DATABASE_URL | Postgres connection string used by the app and drizzle-kit | | BETTER_AUTH_SECRET | Session and cookie signing key, minimum 32 characters | | BETTER_AUTH_URL | Public base URL of whichever app owns the auth routes | | AUTH_GITHUB_CLIENT_ID / AUTH_GITHUB_CLIENT_SECRET | GitHub OAuth app credentials | | AUTH_GOOGLE_CLIENT_ID / AUTH_GOOGLE_CLIENT_SECRET | Google OAuth client credentials | | SMTP_HOST / SMTP_PORT / SMTP_USER / SMTP_PASSWORD / SMTP_FROM | Outbound mail for verification codes and magic links |

Handle these rules strictly:

  • Reference variables by name only. If one is undefined, tell the user which names to fill in and stop that step.
  • Never print, copy, or echo secret values you find in the environment into code, logs, or your replies.
  • Ask the user to generate BETTER_AUTH_SECRET themselves with their local random-byte tool so the value never passes through the transcript.
  • Verify .env files are covered by .gitignore.

3. Drizzle schema

Create drizzle.config.ts pointing at the schema file and reading DATABASE_URL, then define the core tables:

| Table | One row per | Notable columns | |---|---|---| | user | identity | id (PK), email, name, email_verified, image, timestamps | | account | linked credential or OAuth app | composite PK (provider, provider_account_id), user_id FK with cascade delete | | session | active login | token (PK), user_id FK, expires_at | | verification | pending email/reset token | composite PK (identifier, token), expires_at | | authenticator | registered passkey | credential_id, user_id FK, public key, counter, device type, backed-up flag |

// src/auth/schema.ts
import { pgTable, text, timestamp, integer, primaryKey, index } from 'drizzle-orm/pg-core';

export const user = pgTable('user', {
  id: text('id').primaryKey(),
  name: text('name'),
  email: text('email').notNull(),
  emailVerified: timestamp('email_verified', { mode: 'date' }),
  image: text('image'),
  createdAt: timestamp('created_at').defaultNow(),
  updatedAt: timestamp('updated_at').defaultNow(),
}, (t) => [index('user_email_idx').on(t.email)]);

export const account = pgTable('account', {
  userId: text('user_id').notNull().references(() => user.id, { onDelete: 'cascade' }),
  type: text('type').notNull(), // credential | oauth | oidc | webauthn
  provider: text('provider').notNull(),
  providerAccountId: text('provider_account_id').notNull(),
  accessToken: text('access_token'),
  refreshToken: text('refresh_token'),
  expiresAt: integer('expires_at'),
}, (t) => [primaryKey({ columns: [t.provider, t.providerAccountId] })]);

export const session = pgTable('session', {
  token: text('token').primaryKey(),
  userId: text('user_id').notNull().references(() => user.id, { onDelete: 'cascade' }),
  expiresAt: timestamp('expires_at', { mode: 'date' }).notNull(),
}, (t) => [index('session_user_idx').on(t.userId)]);

export const verification = pgTable('verification', {
  identifier: text('identifier').notNull(),
  token: text('token').notNull(),
  expiresAt: timestamp('expires_at', { mode: 'date' }).notNull(),
}, (t) => [primaryKey({ columns: [t.identifier, t.token] })]);

Add the authenticator table only when passkeys are in scope. Index user.email and session.user_id because the guard queries them on every request. The cascade deletes exist so removing a user removes their sessions and credentials atomically.

4. Backend wiring

Database access. Create a global DatabaseModule exposing a DatabaseService that opens a pg pool from DATABASE_URL, wraps it with drizzle(pool, { schema }), and closes the pool on module destroy.

Auth instance.

// src/auth/auth.instance.ts
import { betterAuth } from 'better-auth';
import { drizzleAdapter } from '@auth/drizzle-adapter';
import { DatabaseService } from '../database/database.service';

export function buildAuth(db: DatabaseService) {
  return betterAuth({
    database: drizzleAdapter(db.db, { provider: 'pg', schema: db.schema }),
    emailAndPassword: { enabled: true, requireEmailVerification: true },
    socialProviders: {
      github: {
        clientId: process.env.AUTH_GITHUB_CLIENT_ID!,
        clientSecret: process.env.AUTH_GITHUB_CLIENT_SECRET!,
      },
    },
    session: { expiresIn: 60 * 60 * 24 * 3, updateAge: 60 * 60 * 12 },
    trustedOrigins: ['http://localhost:3000'],
  });
}

The short expiry with a rolling refresh limits the damage of a stolen cookie while keeping daily users signed in.

Controller. Mount one catch-all route under auth that forwards the raw request and response to auth.handler. Do not reimplement sign-in or OAuth endpoints yourself — cookie signing, CSRF checks, and provider handshakes live in the handler, and duplicating them is where auth bugs come from. On top of that, expose small typed endpoints: GET /auth/me (session or null) and POST /auth/sign-out. Guard sign-out with a valid session so a stranger cannot revoke someone else's session by guessing.

Guard. Implement a NestJS CanActivate guard that reads the Authorization bearer header (or cookie header), calls auth.api.getSession({ headers }), attaches request.user and request.session, and throws UnauthorizedException otherwise. Also provide an optional variant that continues with request.user set to null — useful for endpoints that personalize rather than restrict. Export the guard from the AuthModule so feature controllers can apply it with @UseGuards.

CORS. Since the browser must send auth cookies from port 3000 to port 4000, enable CORS on the API with credentials: true and list the exact frontend origin.

5. Frontend wiring

Client. In lib/auth-client.ts, call createAuthClient from better-auth/react with baseURL set from a public env var pointing at the auth owner (the Next app itself, or the API origin if Nest owns auth). If Next owns auth, also export a server instance in lib/auth-server.ts and a catch-all route handler in app/api/auth/[...all]/route.ts that delegates to it.

Pages. Build /login and /register as client components:

const { data, error } = await authClient.signIn.email({ email, password });
const { data, error } = await authClient.signUp.email({ email, password, name: 'Dana' });
await authClient.signIn.social({ provider: 'github', callbackURL: '/board' });

Render error.message inline, disable the submit button while pending, and link between the two pages. Keep passwords out of component state logs.

Reading the session. In client components use the library's session hook from the same client instance. In server components and server actions call auth.api.getSession({ headers: await headers() }) so the check happens server-side with the request's own cookies.

6. Route protection

  • Next middleware: in middleware.ts, look up the session with auth.api.getSession({ headers: request.headers }). Redirect anonymous requests to /board/* toward /login, and send already-authenticated users hitting /login or /register to /board. Exclude static assets and the auth API from the matcher so every page load does not ping the database twice.
  • Server components: for pages middleware cannot cover, fetch the session and call redirect('/login') when it is null.
  • Nest: apply the guard at the controller level; per-route overrides beat a global guard when some endpoints must stay public.

7. Plugins

| Plugin | What it adds | Extra tables | Must configure | Main client calls | |---|---|---|---|---| | twoFactor | TOTP, emailed OTP, backup codes, trusted devices | two_factor | issuer, otpOptions.sendOTP delivery function | twoFactor.enable, verifyTotp, verifyBackupCode, disable | | magicLink | Passwordless email sign-in | none (reuses verification) | sendMagicLink delivery function, expiresIn | magicLink.send | | passkey | WebAuthn credentials | authenticator | rpID (your domain), rpName | passkey.register, signIn.passkey | | organization | Teams, roles, invitations | organization, member, invitation | role defaults | organization.create, organization.inviteMember | | emailVerification | Verified-email gate for passwords | none | sendVerificationEmail, sendOnSignUp | emailVerification.send, emailVerification.verify |

Add plugins to the server instance and mirror them in createAuthClient, or the client calls will not type-check.

Two-factor flow. twoFactor.enable({ password }) returns a totpURI (render it as a QR code) plus one-time backupCodes — display them immediately, because they cannot be fetched again. Verify sign-ins with verifyTotp({ code, trustDevice: true }); the trust flag skips the prompt for 30 days on that device. A lost authenticator is recovered with verifyBackupCode({ code }), after which steer the user to re-enroll. Disabling always requires the password. Implement sendOTP to deliver the code through your mail provider and rate-limit it.

Magic link. Provide sendMagicLink: async ({ email, url }) => deliver(url) and set expiresIn to 10 minutes — long-lived sign-in links are a liability.

Preview shortened. The full SKILL.md is in the pack.