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.
| Platform | Store | Keeps the session |
|---|---|---|
| Web | IndexedDB, the default | Across loads and tabs of the origin |
| CLI | Store.file(), the default | In a file that only the user reads |
| React Native | expo() of accounts/expo | In the secure store of the device |
| Backend | backend({ 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.
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>
}import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const accounts = Accounts.create({
chain: 'testnet',
plugins: [react()],
})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.
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(),
})The cli example runs these steps.
Save the session to a file
Outside a browser, an instance with a cli: client ID saves its session to ~/.tempo/id/store.json, with no store option. Every CLI of the user shares the file, which has mode 0600. If the save of a sign-in replaces a later session that another instance's sign-in saved, such as in two runs of a login at once, the instance takes that session back and revokes its own refresh token. Any other instance holds a session only with a store.
import { Accounts } from 'accounts'
import { device } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
clientId: 'cli:acme-example',
plugins: [
device({
onCode: (code) =>
console.log(
`Open ${code.verificationUriComplete} and confirm the code ${code.userCode}.`,
),
}),
],
})Read the saved session
import { accounts } from './tempo.config.js'
const session = await accounts.session.get()
if (!session) console.log('Not signed in.')import { Accounts } from 'accounts'
import { device } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
clientId: 'cli:acme-example',
plugins: [
device({
onCode: (code) =>
console.log(
`Open ${code.verificationUriComplete} and confirm the code ${code.userCode}.`,
),
}),
],
})The mobile example runs these steps.
Add the expo plugin
The plugin sets the instance's store to the device's secure store, from expo-secure-store, which the app installs.
import { Accounts } from 'accounts'
import { expo } from 'accounts/expo'
export const accounts = Accounts.create({
chain: 'testnet',
// The client ID of the app's registration.
clientId: 'example-mobile',
plugins: [expo({ redirectUri: 'com.example.app:/callback' })],
})The backend example runs these steps.
Pass a store to the backend plugin
A backend's instance serves many users, so it holds no session of its own. The backend plugin keeps one session for each session cookie in its store.
import { Accounts, Store } from 'accounts'
import { backend } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [backend({ store: Store.memory() })],
})| Store | Use |
|---|---|
Store.memory() | One process, such as in development |
Store.postgres(client) | A pg pool. The store creates its table |
Store.redis(client) | A redis client |
Sessions.durableObject(namespace) | One Durable Object for each session |
Store.durableObject(storage) | The storage of the app's own Durable Object |
Store.workersKv(namespace) | A Workers KV namespace. Another location can read a sign-out up to 60 seconds late |
In a Cloudflare Worker, Store.file throws Store.NodeRequiredError, since node:fs there keeps each file in the memory of one isolate. Use a Durable Object or Workers KV store.
Each stored session holds a refresh token and an access key's private key. Give no other role access to the store.
Read the session of a request
import { Hono } from 'hono'
import { accounts } from './tempo.config.js'
const app = new Hono()
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw))
app.get('/me', async (c) => {
const session = await accounts.session.get(c.req.raw)
if (session?.method !== 'tempo-id') return c.text('Signed out', 401)
return c.json(session.user)
})
export default appimport { Accounts, Store } from 'accounts'
import { backend } from 'accounts/plugins'
export const accounts = Accounts.create({
chain: 'testnet',
clientId: process.env.APP_URL,
plugins: [backend({ 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.
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)
},
})| Member | Contract |
|---|---|
getItem | Resolves with the value of the key, or undefined |
local | Optional. 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 |
removeItem | Deletes the value of the key |
setItem | Writes the value. With options.expiresAt, in milliseconds, the entry may then expire |
takeItem | Optional. Reads and deletes the value in one atomic step |
update | Optional. 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 abigint. - 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>
}import { Accounts } from 'accounts'
import { react } from 'accounts/react'
export const mainnet = Accounts.create({ chain: 'mainnet', plugins: [react()] })
export const testnet = Accounts.create({ chain: 'testnet', plugins: [react()] }) 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.
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,
})