On this page

Sessions and tokens

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).

JavaScript
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:

SettingDefaultRange
Access token lifetime3600 s5 minutes to 7 days
Rotate refresh tokensOnEach refresh issues a new refresh token
Refresh token reuse interval10 s0 to 3600 s
Maximum session lengthNeverUp to 8,760 hours
Inactivity timeoutNeverUp to 8,760 hours
Single session per userOffSigning 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:

Terminal
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:

JavaScript
stitchdb.auth.onAuthStateChange((event, session) => {
  if (event === 'SIGNED_IN') console.log('Hello', session.user.email)
  if (event === 'SIGNED_OUT') console.log('Bye')
})

#Sign out

JavaScript
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 device

Signing 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.