ServerAuth & Sessions
Token Handling
API keys, session cookies, and extension tokens for CRM authentication.
API Keys
API keys provide machine-to-machine authentication. They are verified in tenantMiddleware:
const data = await auth.api.verifyApiKey({ body: { key: apiKey } });
if (data.valid && data.key?.referenceId) {
// API key is valid and associated with a user
}API Key Features
- Associated with a
referenceId(user ID) - Can be scoped to specific organizations
- Verified via
auth.api.verifyApiKey()
Security Best Practices
- Rotate API keys periodically
- Use scoped keys with minimal permissions
- Store keys securely (never in source control)
Session Cookies
Browser users authenticate via session cookies managed by Better Auth:
| Cookie | Purpose |
|---|---|
better-auth-session | Main session cookie |
| Cookie domain | Derived from BETTER_AUTH_URL |
Cookie Configuration
cookies: env.NODE_ENV === "production"
? { domain: getCookieDomain(), secure: true, sameSite: "none" }
: { secure: false, sameSite: "lax" },- Production: Secure, cross-subdomain cookies (
.crm.selegic.com) - Development: Local cookies on
localhost
Session Cache
Sessions are cached for 5 minutes to reduce database load:
session: {
cookieCache: { enabled: true, maxAge: 5 * 60 },
},Extension Tokens
Extension tokens are short-lived JWTs used by iframe-based extensions to authenticate with the Action API. They are generated in features/extensions.
Token Generation
Tokens are created with:
EXTENSION_TOKEN_SECRETfor signing- Short TTL (expires quickly)
- Scoped to specific organization/user
Security Best Practices
- Use minimal scopes
- Short token TTLs reduce blast radius
- Rotate
EXTENSION_TOKEN_SECRETif compromised - Validate tokens before executing actions
Organization Context
Both API keys and sessions can resolve organization context:
| Auth Method | Organization Source |
|---|---|
| Session | activeOrganizationSlug from session data |
| API key | x-tenant-id header or user's first org |
| Extension token | Token payload |
The tenantMiddleware ensures every authenticated request has a valid organization context.