How access tokens work, how the SDK keeps a session alive and how to sign out.
#Access and refresh tokens
Signing in returns a session: a short-lived access token (a JWT, one hour by default) and a refresh token. With autoRefreshToken the SDK swaps the refresh token for a new access token before it expires; with persistSession it stores the session (in localStorage in browsers).
import { createClient } from 'stitchdb-js'
export const stitchdb = createClient('https://<project-ref>.p.stitchdb.com', '<anon-key>', {
auth: { persistSession: true, autoRefreshToken: true },
})#Session settings
In Studio → Authentication → Settings:
| Setting | Default | Range |
|---|---|---|
| Access token lifetime | 3600 s | 5 minutes to 7 days |
| Rotate refresh tokens | On | Each refresh issues a new refresh token |
| Refresh token reuse interval | 10 s | 0 to 3600 s |
| Maximum session length | Never | Up to 8,760 hours |
| Inactivity timeout | Never | Up to 8,760 hours |
| Single session per user | Off | Signing in ends the user's other sessions |
#Use the token with the REST API
Send the access token as a bearer token, together with the anon key:
curl 'https://<project-ref>.p.stitchdb.com/rest/v1/todos?select=id,task&is_complete=eq.false' \
-H "apikey: <anon-key>" \
-H "Authorization: Bearer <user-access-token>"#Session events
onAuthStateChange reports INITIAL_SESSION, SIGNED_IN, SIGNED_OUT, TOKEN_REFRESHED, USER_UPDATED, PASSWORD_RECOVERY and MFA_CHALLENGE_VERIFIED:
stitchdb.auth.onAuthStateChange((event, session) => {
if (event === 'SIGNED_IN') console.log('Hello', session.user.email)
if (event === 'SIGNED_OUT') console.log('Bye')
})#Sign out
await stitchdb.auth.signOut() // every session of the user (default)
await stitchdb.auth.signOut({ scope: 'local' }) // this device only
await stitchdb.auth.signOut({ scope: 'others' }) // every other deviceSigning out revokes refresh tokens. Access tokens that were already issued stay valid until they expire, so keep their lifetime short. Admins can sign a user out everywhere from Studio.
#Multi-factor authentication
Sessions verified with a second factor have aal: 'aal2'. See Multi-factor authentication.