Skip to content
LogoLogo

Restore sessions

An app restores the session of a signed-in user at each load, with no new sign-in.

Overview

A session holds a sign-in's user, tokens, and access key. The instance saves it to its store, so a later load of the app restores it with no new sign-in.

The demo signs a user in through Tempo ID's dialog, and restores the session from the browser's store after a reload.

Restore a sessionDemo
pnpx gitpick tempoxyz/accounts/tree/main/examples/webSource

Walkthrough

The web example runs these steps.

Create the instance

Create one instance for the app. The react plugin adds accounts.useSession, and a browser's default store is IndexedDB.

tempo.config.ts
import { Accounts } from 'accounts'
import { react } from 'accounts/react'
 
export const accounts = Accounts.create({
  chain: 'testnet',
  plugins: [react()],
})

Restore the session

The first render of accounts.useSession reads the saved session. Without one, or after its access key expires, session is undefined.

On a page of a first-party app, the first render also renews a missing or expired session from the browser's Tempo ID session, with no prompt. Manage sessions shows the options of that renewal.

import { accounts } from './tempo.config.js'
 
export function App() {
  const { session } = accounts.useSession() 
 
  if (!session) return <p>Signed out</p>
  return <p>Signed in as {session.user.email}</p>
}

Read the status

The hook returns the status, with a flag for each value, and renders again at each change.

import { accounts } from './tempo.config.js'
 
export function App() {
  const { isPending, session } = accounts.useSession() 
 
  if (isPending) return <p>Restoring the session…</p> 
  if (!session) return <p>Signed out</p>
  return <p>Signed in as {session.user.email}</p>
}
StatusFlagMeaningSession
pendingisPendingThe instance reads the saved session, or an authorization runsundefined
reauthorizingisReauthorizingAn authorization renews a saved session whose access key expiredThe expired session
signedInisSignedInThe instance holds a sessionThe session
signedOutisSignedOutThe instance holds no session, and no authorization runsundefined

Sign the user in

dialog.signIn saves the session that it returns, and the hook renders the signed-in branch.

import { accounts } from './tempo.config.js'
 
export function SignIn() {
  return (
    <button onClick={() => accounts.dialog.signIn()} type="button">
      Sign in with Tempo
    </button>
  )
}

Call the app's API

session.fetch sends a request with the session's access token. If the access token expires within 30 seconds, the tokens refresh beside the request. Without a session, the call throws Accounts.SignedOutError, and sends no request.

import { useState } from 'react'
import { accounts } from './tempo.config.js'
 
export function Profile() {
  const [profile, setProfile] = useState<string>()
 
  return (
    <button
      onClick={async () => {
        const response = await accounts.session.fetch({ url: '/api/me' }) 
        setProfile(await response.text())
      }}
      type="button"
    >
      {profile ?? 'Load the profile'}
    </button>
  )
}

Sign the user out

signOut empties the session, deletes the saved one, and revokes the refresh token.

import { accounts } from './tempo.config.js'
 
export function SignOut() {
  return (
    <button onClick={() => accounts.signOut()} type="button">
      Sign out
    </button>
  )
}

Render SignIn without a session, and Profile and SignOut with one.

Use cases

Each use case reads the session through accounts.session, which the hook also reads, or checks it with Session.expired.

Restore without React

session.get reads the saved session, such as on a page without React or in a script. It returns undefined without a session, and after its access key expires.

import { accounts } from './tempo.config.js'
 
const session = await accounts.session.get() 
 
console.log(session ? `Signed in as ${session.user.email}` : 'Signed out')

Renew an expired session

reauthorize: true renews a missing or expired session from the browser's Tempo ID session, with no prompt. The call returns undefined if only an interactive sign-in can renew it, so the page shows its sign-in. Outside a browser without redirectUri, such as in a CLI, it returns undefined with no request, and the program signs in again with the device grant.

import { accounts } from './tempo.config.js'
 
const session = await accounts.session.get({ reauthorize: true }) 
 
if (!session) console.log('Sign in again.')

Follow the status

session.status returns the status of the table above, and calls a listener at each change. It suits code outside a component, such as a router guard.

import { accounts } from './tempo.config.js'
 
const unsubscribe = accounts.session.status.subscribe((status, previous) => {
  if (previous.status === 'signedIn' && status.status === 'signedOut')
    console.log('Signed out')
})

Load the instance for returning visitors

The instance reads the saved session from IndexedDB, which has no synchronous read. With hint, the instance keeps a cookie while it holds a session. Hint.has of accounts/hint, which imports no other module, reads it at startup, so the page loads the instance only for a returning visitor.

A page that loads no instance renews no session from the browser's Tempo ID session at startup.

import { Hint } from 'accounts/hint'
 
if (Hint.has(document.cookie)) {
  const { accounts } = await import('./tempo.config.js')
  await accounts.session.get()
}

Check the expiry in an open page

The hook empties an expired session only when it reads the store, so a page that stays open can hold a session whose access key expired. Session.expired reports it.

import { Session } from 'accounts'
import { accounts } from './tempo.config.js'
 
export function App() {
  const { session } = accounts.useSession()
 
  if (!session || Session.expired(session))
    return (
      <button onClick={() => accounts.dialog.signIn()} type="button">
        Sign in with Tempo
      </button>
    )
  return <p>Signed in as {session.user.email}</p>
}

Next steps