Skip to main content

Authentication Strategies

Choose the right strategy for your security needs: NONE: No authentication, anyone with tenant ID can send events
  • Use for: Public websites, demos, development
  • Security level: Low
SERVER_SIDE: Secret key authentication
  • Use for: Backend services, server-side code
  • Security level: High
  • Never expose secret in client code
JWT: Token-based authentication
  • Use for: Client apps with user authentication
  • Security level: High
  • Validates user identity with each request
Learn more in Authentication.

User ID Security

JWT User ID Validation

With JWT auth, user IDs must match the token’s subject:
Why: Prevents users from impersonating others.

User ID Override Restrictions

Be careful with userId overrides:
When using overrides:
  • Ensure you have permission to modify those users
  • Avoid switching between many different user IDs
  • With JWT, user ID must match token subject

Rate Limiting

Grain may block requests if:
  • Too many distinct user IDs from same source
  • Unusual patterns detected
  • Excessive property updates
Best practice: Use global setUserId() for current user, avoid overrides unless necessary.

Secret Key Protection

Never Expose Secrets

Server-Side Only

Use SERVER_SIDE auth only in:
  • Node.js backends
  • Serverless functions
  • Server API routes
Never in:
  • Browser JavaScript
  • Mobile apps
  • Any client-side code

Data Privacy

Sensitive Data

Never track sensitive information:

User Properties

Only set properties users consent to:
Follow GDPR, CCPA, and other privacy regulations.

CORS and API Security

Grain API uses CORS to restrict access. Configure allowed origins in your dashboard at grainql.com/dashboard. Default: All origins allowed (*) Recommended: Whitelist specific domains

Token Refresh

For JWT authentication, ensure tokens stay fresh:
Don’t cache tokens yourself - let your auth provider handle refresh.

Secure Configuration

Environment-Based Auth

Use different auth for different environments:
Development: No auth (easier) Production: JWT (secure)

Content Security Policy (CSP)

If using CSP headers, allow Grain API:

XSS Protection

Never render user-provided config values as HTML:

Audit Logging

Track security-relevant events:

Best Practices

1. Principle of Least Privilege: Grant minimum necessary permissions 2. Rotate Secrets: Regularly rotate secret keys 3. Monitor Suspicious Activity: Check dashboard for unusual patterns 4. Validate Input: Sanitize data before tracking 5. Use HTTPS: Always use HTTPS in production 6. Regular Updates: Keep SDK updated for security patches

Next Steps

Authentication

Choose the right auth strategy

Configuration

Configure securely