Architecture
Authentication is configured in the@packages/auth workspace package and used by both the Hono API and Next.js frontend.
Server Configuration
Better Auth Instance
The auth instance is configured with database adapter, providers, and plugins:packages/auth/src/index.ts
Database Adapter
Better Auth uses Drizzle ORM to store auth data in PostgreSQL:- user - User accounts with email, name, and verification status
- session - Active user sessions with tokens and expiry
- account - OAuth provider accounts linked to users
- verification - Email verification codes
- organization - Multi-tenant organizations
- team - Teams within organizations
- member - Organization membership with roles
- invitation - Pending organization invitations
Environment-Based Cookie Configuration
Cookie domains and prefixes are configured based on the deployment environment:packages/auth/src/lib/utils.ts
API Integration
Auth Router
The Hono API exposes Better Auth endpoints:api/hono/src/routers/auth.ts
/api/auth/*, providing all auth endpoints:
/api/auth/sign-in/social- OAuth sign-in/api/auth/sign-in/magic-link- Email magic link/api/auth/sign-out- Sign out/api/auth/get-session- Get current session/api/auth/organization/*- Organization management
Auth Middleware
Protect routes by validating sessions:api/hono/src/middlewares/auth.ts
api/hono/src/routers/v1.ts
Client Usage
Auth Client Setup
The frontend creates a Better Auth client:web/next/src/lib/auth/client.ts
Sign In with OAuth
Social authentication with GitHub or Google:components/access.tsx
Sign In with Magic Link
Passwordless email authentication:Sign Out
Server-Side Session Management
Getting Session in Server Components
Retrieve the current session:web/next/src/lib/auth/index.ts
Protecting Pages
Redirect unauthorized users:app/(protected)/layout.tsx
Accessing User Data
Session Type
TheSession type is exported from @packages/auth:
Organizations & Teams
The organization plugin enables multi-tenancy:Security Best Practices
Use environment variables for secrets
Use environment variables for secrets
Never hardcode client IDs or secrets:
Configure trusted origins
Configure trusted origins
Prevent CORS attacks by whitelisting origins:
Validate sessions on protected routes
Validate sessions on protected routes
Always check authentication before accessing protected resources:
Use httpOnly cookies
Use httpOnly cookies
Environment Variables
Required environment variables:.env
API Reference
Better Auth provides an interactive API reference at/api/auth/reference in development mode, documenting all available authentication endpoints.