Overview
The Toots API uses better-auth for session-based authentication. Authentication is handled transparently through middleware, and protected procedures automatically validate the user session.Authentication setup
Toots uses better-auth with the Prisma adapter for PostgreSQL. The auth configuration is defined inapps/web/lib/auth/auth.ts:5-12:
Email and password authentication is currently the only enabled authentication method.
Session context
Every RPC request includes session information in the context. The session is retrieved from request headers and passed to each procedure. Fromapps/web/app/rpc/[[...rest]]/route.ts:14-23:
Protected procedures
The API provides two base types for defining procedures:Public procedures
Usebase for procedures that don’t require authentication:
Protected procedures
UseprotectedBase for procedures that require authentication. The middleware automatically validates the session and adds the user to the context.
From apps/web/server/context.ts:10-19:
apps/web/server/procedures/projects.ts:34-43:
When using
protectedBase, the context.user object is guaranteed to exist and contains id, email, and optionally name.Session structure
The session object includes user information when authenticated:Authentication flow
- User authenticates: Client calls the better-auth API endpoints at
/api/auth - Session created: better-auth creates a session and stores it in the database
- Session cookie: Client receives a session cookie
- RPC calls: All subsequent RPC calls include the session cookie
- Session validation: The RPC handler extracts and validates the session
- Context injection: Session data is added to the request context
- Middleware check: Protected procedures verify the session exists
Making authenticated requests
From the client side, authentication is handled automatically through cookies:Error handling
If a protected procedure is called without authentication, it throws an “Unauthorized” error:Server-side authentication
When making RPC calls from server components, the session is automatically retrieved from Next.js headers. Fromapps/web/lib/orpc.server.ts:10-17: