Skip to content
LogoLogo

Store sessions

An app chooses the store that keeps the session on each platform.

Overview

An instance saves its session to its store, which decides where the session lives, and for how long.

PlatformStoreKeeps the session
WebIndexedDB, the defaultAcross loads and tabs of the origin
CLIStore.file(), the defaultIn a file that only the user reads
React Nativeexpo() of accounts/expoIn the secure store of the device
Backendbackend({ store })On the server, one for each browser

The demo signs a user in on two instances, one with a memory store and one with the default store. After a reload, only the default store returns its session.

Store a sessionDemo

Walkthrough

Use the default store

In a browser, an instance without store uses IndexedDB. It keeps the session's access key across loads as a non-extractable CryptoKey, whose private key no script reads.

import { accounts } from './tempo.config.js'
 
export function App() {
  const { session } = accounts.useSession()
 
  if (!session)
    return (
      <button onClick={() => accounts.dialog.signIn()} type="button">
        Sign in with Tempo
      </button>
    )
 
  // A reload renders this branch again, with no sign-in.
  return <p>Signed in as {session.user.email}</p> 
}

Keep the session in memory

Store.memory keeps the session until the page unloads, such as for a test. A reload leaves no session to sign out, so request no refresh token.

tempo.config.ts
import { Accounts, Store } from 'accounts'
import { react } from 'accounts/react'
 
export const accounts = Accounts.create({
  chain: 'testnet',
  plugins: [react()],
  // Without `offline_access`, Tempo ID issues no refresh token.
  scope: 'openid', 
  store: Store.memory(), 
})

Use cases

Each use case sets the store option, or builds a store with Store.from.

Write a store

Store.from instantiates a store over any storage. This one keeps a backend's sessions in a SQLite file.

store.ts
import { DatabaseSync } from 'node:sqlite'
import { Store } from 'accounts'
import { Json } from 'ox'
 
const database = new DatabaseSync('sessions.db')
database.exec(
  'create table if not exists store (key text primary key, value text not null, expires_at integer)',
)
 
export const store = Store.from({
  async getItem(key) {
    const row = database
      .prepare(
        'select value from store where key = ? and (expires_at is null or expires_at > ?)',
      )
      .get(key, Date.now())
    return row ? Json.parse(String(row.value)) : undefined
  },
  async removeItem(key) {
    database.prepare('delete from store where key = ?').run(key)
  },
  async setItem(key, value, options = {}) {
    database
      .prepare('insert or replace into store values (?, ?, ?)')
      .run(key, Json.stringify(value), options.expiresAt ?? null)
  },
})
MemberContract
getItemResolves with the value of the key, or undefined
localOptional. true for a store of one process alone, such as one in the memory of a page, which a page load empties. A refused refresh then throws at once, and redirect.signIn without open refuses the store
removeItemDeletes the value of the key
setItemWrites the value. With options.expiresAt, in milliseconds, the entry may then expire
takeItemOptional. Reads and deletes the value in one atomic step
updateOptional. Reads the value, writes the value that its function returns only if the key still holds the one it read, and otherwise runs the function again. The backend then keeps each concurrent sign-in of one sid across processes
  • A store that serializes uses ox's Json, which keeps a bigint.
  • A browser's access key has no serialized form, so keep a browser's session in the default store.

Separate the sessions of two instances

A saved session's key names the Tempo ID deployment, the client ID, and the chain. Instances that differ in url, clientId, or chain thus share one store, and each reads only its own session.

import { testnet } from './tempo.config.js'
 
export function App() {
  const { session } = testnet.useSession()
 
  return <p>{session ? session.user.email : 'Signed out on testnet'}</p>
}

Hold no session in a service

A service that signs in many users with a cli: client ID, such as a bot, holds no session of its own. store: false refuses the file of the default store, so each sign-in only returns its session.

tempo.config.ts
import { Accounts } from 'accounts'
import { device } from 'accounts/plugins'
 
export const accounts = Accounts.create({
  chain: 'testnet',
  clientId: 'cli:acme-bot',
  plugins: [
    device({
      onCode: (code) =>
        console.log(`Open ${code.verificationUriComplete} to sign in.`),
    }),
  ],
  store: false, 
})

Next steps