Skip to content
LogoLogo

Backend

The server of an app signs a user in with a redirect, and keeps the session.

Overview

The backend plugin runs the Tempo ID sign-in on the app's server, through a redirect to Tempo ID's pages. The server keeps each session in a store.

The browser holds only a session ID in an HttpOnly cookie, so the page needs no instance, and no page script reads a token. Choose this flow over the dialog or redirect flow if the server acts for the user, or if the page must hold no token. The app's origin is its client ID, with no registration or client secret.

The demo signs a user in on the site's server, reads the user, and signs out.

Sign in on the serverDemo
pnpx gitpick tempoxyz/accounts/tree/main/examples/backendSource

Walkthrough

The backend example runs this flow in a Hono server.

Install the packages

Create the instance

APP_URL holds the app's origin. Create one instance for the process: Tempo ID refuses a reused refresh token, so the instance holds each refresh in progress, and concurrent requests of a session share it.

tempo.config.ts
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() })],
})

To send transactions with the access key of each session, add accessKey and the viem plugin, as the Backend tab of Getting started shows. For a local Tempo ID or another chain, Use another Tempo ID or chain sets the instance.

StoreSessions live in
Store.memoryThe process. A restart signs each user out
Store.postgresA table of a Postgres database
Store.redisRedis 6.2 or later
Store.durableObjectThe storage of the app's own Durable Object
Store.workersKvA Workers KV namespace. Another location can read a sign-out up to 60 seconds late

If replicas share a store, route each session to one replica.

Serve the sign-in routes

accounts.handler serves the sign-in routes under /api/auth. Mount it on the page's origin, since each POST route refuses a request of another origin with 403.

import { Hono } from 'hono'
import { accounts } from './tempo.config.js'
 
const app = new Hono()
 
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw)) 
 
export default app
RouteResult
GET /api/auth/loginStarts a sign-in, and redirects the browser to Tempo ID
GET /api/auth/callbackCompletes the sign-in, sets the session cookie, and redirects to returnTo
GET /api/auth/sessionReturns the session without its tokens, or null
POST /api/auth/logoutEnds the session, and deletes the session cookie

Name the redirect URI

Tempo ID returns a sign-in only to a redirect URI of the app. A localhost origin accepts any path. A deployed origin lists /api/auth/callback in redirect_uris of its web app manifest, which its root page links.

manifest.webmanifest
{
  "name": "Example",
  "redirect_uris": ["https://app.example/api/auth/callback"]
}

Without redirect_uris, the only redirect URI is the origin's root.

Sign the user in

A link to /api/auth/login leaves the page for Tempo ID's sign-in. The server keeps the PKCE verifier, so only the server can redeem the code.

After the sign-in, the callback returns the browser to returnTo with the session cookie. session.get(request) returns the session of the request's cookie, or undefined. It refreshes an access token that expires within 30 seconds.

import { Hono } from 'hono'
import { html } from 'hono/html'
import { accounts } from './tempo.config.js'
 
const app = new Hono()
 
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw))
 
app.get('/', async (c) => {
  const session = await accounts.session.get(c.req.raw)
  if (session?.method !== 'tempo-id')
    return c.html(
      html`<a href="/api/auth/login?returnTo=/">Sign in with Tempo</a>`,
    )
 
  return c.html(html`<p>Signed in as ${session.user.email}</p>`)
})
 
export default app
Query parameter of the login routeEffect
loginHintFills the email field of Tempo ID's sign-in page
prompt=loginRequests a new sign-in, such as to switch to another account
returnToNames the path that the callback returns to, with error=access_denied after a denial

The browser sends the session cookie with each request, so guard each route that changes state against cross-site requests, such as with Hono's CSRF middleware.

End the session

The logout route revokes the refresh token, and deletes the session and its cookie. It returns 204, so the page reloads after it.

import { Hono } from 'hono'
import { html } from 'hono/html'
import { accounts } from './tempo.config.js'
 
const app = new Hono()
 
app.all('/api/*', (c) => accounts.handler.fetch(c.req.raw))
 
app.get('/', async (c) => {
  const session = await accounts.session.get(c.req.raw)
  if (session?.method !== 'tempo-id')
    return c.html(
      html`<a href="/api/auth/login?returnTo=/">Sign in with Tempo</a>`,
    )
 
  return c.html(html`
    <p>Signed in as ${session.user.email}</p>
    <button
      onclick="fetch('/api/auth/logout', { method: 'POST' }).then(() => location.reload())"
      type="button"
    >
      Sign out
    </button>
  `)
})
 
export default app

Use cases

Each use case uses one option or action of the backend plugin, or the dialog's backend option.

Sign in with the dialog

A page can open Tempo ID's sign-in in a dialog over the page, in place of a redirect. Pass backend to the dialog plugin of the page's instance.

dialog.signIn runs the sign-in through POST requests to the login and callback routes, and the server still keeps the PKCE verifier and the session. After the sign-in, the page reloads, and the server renders it with the session.

The authenticated-api example runs this flow in a React page.

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

If the user closes the dialog, the call rejects with an AbortError. If the backend does not answer, such as offline, it rejects with Accounts.RequestError, with the code server_error and status 0, and with signedIn once the user signed in on Tempo ID.

Restore the session on load

A page that renders without the server reads the session with dialog.session. With backend, it returns the session of GET /api/auth/session, or null. Its first call takes the read that the dialog's preload started as the instance was created, while it is pending or for 10 seconds after it settles, so the page reads the route once, signed in or out.

main.ts
import { accounts } from './tempo.config.js'
 
const session = await accounts.dialog.session() 
if (session?.method === 'tempo-id') render(session.user.email)
else if (session) render(session.account)
else button.onclick = () => accounts.dialog.signIn()

Write sign-in routes

An app with its own paths or cookie names calls the plugin's actions in place of accounts.handler, and sets the cookie itself.

server.ts
import { Accounts, Store } from 'accounts'
import { backend } from 'accounts/plugins'
import { Hono } from 'hono'
import { deleteCookie, getCookie, setCookie } from 'hono/cookie'
import { csrf } from 'hono/csrf'
 
const accounts = Accounts.create({
  chain: 'testnet',
  clientId: process.env.APP_URL,
  plugins: [backend({ store: Store.memory() })],
})
 
const app = new Hono()
 
const cookie = {
  httpOnly: true,
  path: '/',
  prefix: 'host',
  sameSite: 'Lax',
  secure: true,
} as const
 
app.use(csrf())
 
// Start: stores the sign-in under a new session ID, and redirects to Tempo ID.
app.get('/auth/start', async (c) => {
  const { id, url } = await accounts.backend.start({
    redirectUri: new URL('/auth/callback', c.req.url).href,
  })
  setCookie(c, 'session', id, cookie)
  return c.redirect(url)
})
 
// Callback: redeems the code, and stores the session under the same session ID.
app.get('/auth/callback', async (c) => {
  const id = getCookie(c, 'session', 'host')
  if (!id) return c.redirect('/auth/start')
 
  await accounts.backend.complete({ id, url: c.req.url })
  return c.redirect('/')
})
 
// Session: returns the user of the session ID.
app.get('/auth/session', async (c) => {
  const id = getCookie(c, 'session', 'host')
  const session = id ? await accounts.backend.get({ id }) : undefined
  if (session?.method !== 'tempo-id') return c.json({ user: null })
 
  return c.json({ user: session.user })
})
 
// Sign-out: revokes the refresh token, and deletes the session.
app.post('/auth/logout', async (c) => {
  const id = getCookie(c, 'session', 'host')
  if (id) await accounts.backend.end({ id })
  deleteCookie(c, 'session', cookie)
  return c.body(null, 204)
})
 
export default app

backend.start keeps a sign-in for 10 minutes, or 20 with funding. backend.complete throws Accounts.RequestError for a denial, and Accounts.PendingNotFoundError without a sign-in in progress.

Ask for funds

funding of backend.start names the amount that the app needs in the user's Tempo Account. If the account holds less, Tempo ID's deposit page opens after the approval, before the callback. The callback route stays the same as in Write sign-in routes.

import { Hono } from 'hono'
import { setCookie } from 'hono/cookie'
import { accounts } from './tempo.config.js'
 
const app = new Hono()
 
app.get('/auth/start', async (c) => {
  const { id, url } = await accounts.backend.start({
    funding: { amount: '10', currency: 'USD' }, 
    redirectUri: new URL('/auth/callback', c.req.url).href,
  })
  setCookie(c, 'session', id, {
    httpOnly: true,
    path: '/',
    prefix: 'host',
    sameSite: 'Lax',
    secure: true,
  })
  return c.redirect(url)
})
 
export default app

Call an API for the user

session.fetch(request, options) sends a request with the access token of the request's session, after a refresh if necessary. It returns undefined without a Tempo ID session, and sends nothing.

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 response = await accounts.session.fetch(c.req.raw, {
    url: 'https://api.example.com/me',
  })
  if (!response) return c.json({ error: 'invalid_token' }, 401)
 
  return response
})
 
export default app

Accept access tokens

accessToken: true has session.get(request) also accept an access token of the app in the request's authorization header, such as from the app's CLI. Such a session holds the verified token's claims. A request with a session cookie reads the cookie's session first.

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.json({ userId: session.user.id })
  if (session?.method === 'access-token')
    return c.json({ userId: session.token.userId })
 
  return c.json({ error: 'invalid_token' }, 401)
})
 
export default app

A DPoP-bound token carries a proof, which the route refuses once used, as Bind DPoP keys shows.

Authenticate with a private key

A backend whose client ID is its origin sends no client authentication, so any holder of a session's refresh token can refresh the session. A backend that publishes a metadata document with private_key_jwt signs a client assertion for each token request instead, with no registration. The document's URL is the client ID.

Generate an ES256 key pair once, as Pay for users shows, and store the private key as the APP_PRIVATE_KEY secret. The document publishes the public key and the redirect URI, on the app's origin.

{
  "client_id": "https://app.example/client.json",
  "client_name": "Example",
  "grant_types": ["authorization_code", "refresh_token"],
  "jwks": {
    "keys": [{ "alg": "ES256", "crv": "P-256", "kid": "…", "kty": "EC", "x": "…", "y": "…" }]
  },
  "redirect_uris": ["https://app.example/api/auth/callback"],
  "token_endpoint_auth_method": "private_key_jwt"
}

The instance then pushes each authorization request, and signs each code redemption and refresh. Tempo ID still shows the approval page with the app's host. It reads the document again after 5 minutes, so publish a new public key beside the old one at least 5 minutes before the instance signs with it.

Next steps