Selegic CRM Docs
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:

CookiePurpose
better-auth-sessionMain session cookie
Cookie domainDerived from BETTER_AUTH_URL
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_SECRET for 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_SECRET if compromised
  • Validate tokens before executing actions

Organization Context

Both API keys and sessions can resolve organization context:

Auth MethodOrganization Source
SessionactiveOrganizationSlug from session data
API keyx-tenant-id header or user's first org
Extension tokenToken payload

The tenantMiddleware ensures every authenticated request has a valid organization context.

On this page