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
- Use for: Backend services, server-side code
- Security level: High
- Never expose secret in client code
- Use for: Client apps with user authentication
- Security level: High
- Validates user identity with each request
User ID Security
JWT User ID Validation
With JWT auth, user IDs must match the token’s subject:User ID Override Restrictions
Be careful with userId 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
setUserId() for current user, avoid overrides unless necessary.
Secret Key Protection
Never Expose Secrets
Server-Side Only
UseSERVER_SIDE auth only in:
- Node.js backends
- Serverless functions
- Server API routes
- Browser JavaScript
- Mobile apps
- Any client-side code
Data Privacy
Sensitive Data
Never track sensitive information:User Properties
Only set properties users consent to: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:Secure Configuration
Environment-Based Auth
Use different auth for different environments: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 patchesNext Steps
Authentication
Choose the right auth strategy
Configuration
Configure securely