Authentication (Better Auth)

ShipSaaS uses Better Auth for user accounts. The template ships with email/password + email verification, passwordless magic links, and Google OAuth out of the box — all backed by your own Postgres database, with no third-party auth service in the middle.

1. Set your environment

Copy .env.example to .env.local and set:

BETTER_AUTH_SECRET=<openssl rand -base64 32>
BETTER_AUTH_URL=http://localhost:3000
DATABASE_URL=postgresql://user:password@localhost:5432/shipsaas

The auth instance lives in src/lib/auth.ts and the browser client in src/lib/auth-client.ts. All auth routes are handled by src/app/api/auth/[...all]/route.ts — there is nothing to deploy or configure outside your app.

2. Run the migrations

Better Auth's tables (user, session, account, verification) live in src/db/schema.ts alongside your app tables — one database, one schema, type-safe end to end. Apply them either way:

# Option A: let Drizzle push the schema (fast, dev-friendly)
npx drizzle-kit push

# Option B: apply the reviewed SQL
psql $DATABASE_URL -f migrations/001_initial_schema.sql

3. Email verification

Sign-up requires email verification before sign-in (emailAndPassword.requireEmailVerification). The verification email is sent automatically on sign-up (emailVerification.sendOnSignUp), and clicking the link signs the user in (autoSignInAfterVerification).

Emails go through Mailgun using the templates in src/lib/email-templates.ts (emailVerification, magicLink, passwordReset). For local development set SKIP_EMAILS=true to log links to the console instead of sending.

4. Magic links

The magicLink plugin is enabled on the server and the magicLinkClient on the browser. Users click Send magic link on /auth/login, receive a one-time link, and land signed in. Delivery is wired in src/lib/auth.ts via magicLink({ sendMagicLink }).

5. Google OAuth

  1. In the Google Cloud Console, create a project and configure the OAuth consent screen.
  2. Under Credentials, create an OAuth client ID for a Web application and add this authorized redirect URI:
    http://localhost:3000/api/auth/callback/google
    https://yourdomain.com/api/auth/callback/google
  3. Set GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET in .env.local. The provider is wired automatically in src/lib/auth.ts when both are present.

6. Sessions and route protection

Sessions are stored in the session table with a 7-day expiry, refreshed daily, and cookie-cached for 5 minutes so most server-rendered requests skip the session lookup.

  • Server components / route handlers: call getServerSession() from src/lib/auth.ts. The dashboard layout redirects unauthenticated users to /auth/login?redirectTo=....
  • Client components: use the useAuth() hook (src/hooks/useAuth.ts), which wraps Better Auth in TanStack Query.
  • Middleware (proxy.ts) only checks that the session cookie is present and redirects early; full verification always happens server-side. API routes get a JSON 401 instead of a redirect.

7. Security posture

What is enabled out of the box, so you don't have to think about it:

  • Cookies — httpOnly, Secure in production, SameSite=Lax, signed by BETTER_AUTH_SECRET.
  • CSRF & origin checks — origin validation on every auth mutation; callback and redirect URLs are validated against BETTER_AUTH_URL (plus optional BETTER_AUTH_TRUSTED_ORIGINS).
  • Rate limiting — 100 req/10s per IP overall, with sign-in capped at 5/min and sign-up and password reset at 3/min.
  • Email verification required — accounts can't sign in until verified, and sign-in responses don't reveal whether an email is registered.
  • OAuth tokens encrypted at rest — Google tokens in the account table are AES-256-GCM encrypted.
  • Session hygiene — 7-day expiry with daily refresh, a 1-hour “fresh” window for sensitive actions, password reset revokes every session, and the 5-minute cookie cache is HMAC-signed.

The middleware (proxy.ts) only checks cookie presence for early redirects — real authorization always happens server-side via getServerSession() in layouts and route handlers.

8. Test it

  • Visit /auth/register, sign up, and check the Mailgun log (or console) for the verification email. Clicking the link should land you signed in on the dashboard.
  • Sign out, go to /auth/login, use Magic link, and confirm the passwordless round-trip.
  • Click Continue with Google and complete the OAuth round-trip.
  • Check /api/auth/ok returns {"status":"ok"}.