Which Method Should I Use?
| Scenario | Method | Why |
|---|---|---|
| React/Next.js app | JWT Sessions | User is logged in, token comes from auth flow |
| Mobile app | JWT Sessions | Same as web—user session based |
| Backend service | M2M OAuth 2.0 | No user session, server-to-server calls |
| CLI tool | M2M OAuth 2.0 | Automated scripts, no browser |
| Cron job | M2M OAuth 2.0 | Background tasks, no user context |
JWT Session Tokens
For frontend apps where users authenticate via Stytch B2B (magic link, SSO, or password).Usage
With React UI Kit
M2M OAuth 2.0
For backend services using OAuth 2.0 Client Credentials flow.Step 1: Get Credentials
Create M2M client credentials in Dashboard → Settings → API Access. Assign scopes based on what the service needs.Step 2: Exchange for Token
Exchange your client credentials for an access token: Token Endpoint:Step 3: Use the Token
Token Caching
M2M tokens expire after 1 hour. Cache and refresh before expiry:Scopes
| Scope | Permission |
|---|---|
chat:invoke | Create chat completions (billable) |
chat:read | Read chat history |
chat:write | Create, update, delete chats |
models:read | List and view models |
models:write | Create, update, delete models |
datasets:read | View datasets |
datasets:write | Create, update, delete datasets |
files:read | View and download files |
files:write | Upload, update, delete files |
particles:read | View particles |
particles:write | Create, update, delete particles |
system-prompts:read | View system prompts |
system-prompts:write | Create, update, delete system prompts |
connections:read | View external connections (Google Drive, Notion) |
connections:write | Create, update, delete connections |
usage:read | View usage and credit balance |
org:admin | Organization admin access |
Security Best Practices
- Never expose tokens in client-side code — Use a backend proxy for production
- Store secrets in environment variables — Not in code or version control
- Rotate M2M credentials every 90 days — Dashboard → Settings → API Access
- Use HTTPS only — The API rejects HTTP requests
- Scope credentials minimally — Only request permissions you need
Troubleshooting
| Error | Cause | Solution |
|---|---|---|
401 Unauthorized | Invalid or expired token | Refresh M2M token; verify JWT session |
403 Forbidden | Missing scope | Request credentials with required scopes |
Token Expired | M2M token past 1 hour | Request new token |