Skip to content
LogoLogo

Use session cookies

A backend keeps the tokens of a session, and a session cookie authenticates each request of the page.

Overview

If a page's API runs on its own backend, the page needs no token. The backend plugin signs the user in on the server, keeps the session in a Store, and sets an HttpOnly session cookie. A deployed origin lists its callback in a web app manifest.

The demo signs in through the site's backend routes, and calls an API route with the cookie. It then signs out, and the same call receives 401.

Use a session cookieDemo
pnpx gitpick tempoxyz/accounts/tree/main/examples/authenticated-apiSource

Walkthrough

The authenticated-api example runs this flow with Hono, and serves a React app and its API at one origin.

Install the packages

Create the backendServer

The backend plugin keeps each session in a store on the server, since each session holds a refresh token and an access key's private key. The APP_URL variable names the app's origin, its clientId.

server.ts
import { Accounts, Store } from 'accounts'
import { backend } from 'accounts/plugins'
 
const accounts = Accounts.create({
  clientId: process.env.APP_URL,
  plugins: [backend({ store: Store.memory() })],
})

Serve the sign-in routesServer

accounts.handler serves the sign-in, callback, sign-out, and session routes under /api/auth. The callback sets the session cookie.

server.ts
import { Accounts, Store } from 'accounts'
import { backend } from 'accounts/plugins'
import { Hono } from 'hono'
 
const accounts = Accounts.create({
  clientId: process.env.APP_URL,
  plugins: [backend({ store: Store.memory() })],
})
 
const app = new Hono().all('/api/*', (c) =>
  accounts.handler.fetch(c.req.raw),
)
 
export default app

A deployed origin names /api/auth/callback in the redirect_uris of its web app manifest. Without one, Tempo ID redirects only to the origin's root, so both instances set redirectUri to the root.

Sign the user inClient

With backend, the dialog plugin runs the sign-in through the backend's routes, and dialog.signIn returns the user.

import { useState } from 'react'
import { accounts } from './tempo.config.js'
 
type Session = Awaited<ReturnType<typeof accounts.dialog.signIn>>
 
export function App() {
  const [session, setSession] = useState<Session>()
 
  if (!session)
    return (
      <button
        onClick={async () => setSession(await accounts.dialog.signIn())}
        type="button"
      >
        Sign in
      </button>
    )
  return <p>Signed in as {session.user.email}</p>
}

Authenticate each requestServer

session.get returns the cookie's session, or undefined. The cookie is SameSite Lax, so a browser also sends it from another origin of the same site. Hono's CSRF middleware refuses a form post from another origin.

server.ts
import { Accounts, Store } from 'accounts'
import { backend } from 'accounts/plugins'
import { Hono } from 'hono'
import { csrf } from 'hono/csrf'
import { createMiddleware } from 'hono/factory'
 
const accounts = Accounts.create({
  clientId: process.env.APP_URL,
  plugins: [backend({ store: Store.memory() })],
})
 
type Variables = { userId: string }
 
const auth = createMiddleware<{ Variables: Variables }>(async (c, next) => {
  const session = await accounts.session.get(c.req.raw) 
  if (session?.method !== 'tempo-id')
    return c.json({ error: 'invalid_token' }, 401)
 
  c.set('userId', session.user.id)
  await next()
})
 
const app = new Hono().all('/api/*', (c) =>
  accounts.handler.fetch(c.req.raw),
)
 
app
  .use('/v1/*', csrf(), auth)
  .get('/v1/me', (c) => c.json({ userId: c.get('userId') }))
 
export default app

Call the APIClient

The page calls the API at its own origin. A 401 means that the session ended. App renders Me for a signed-in user.

import { useState } from 'react'
import { Me } from './Me.js'
import { accounts } from './tempo.config.js'
 
type Session = Awaited<ReturnType<typeof accounts.dialog.signIn>>
 
export function App() {
  const [session, setSession] = useState<Session>()
 
  if (!session)
    return (
      <button
        onClick={async () => setSession(await accounts.dialog.signIn())}
        type="button"
      >
        Sign in
      </button>
    )
  return <Me /> 
}

Use cases

Each use case sets one option of the backend plugin, or uses one more of its reads or routes.

If the backend also serves other clients, such as a CLI, accessToken accepts both. session.get reads the cookie first, then an access token of the app in the authorization header.

server.ts
import { Accounts, Store } from 'accounts'
import { backend } from 'accounts/plugins'
import { Hono } from 'hono'
import { csrf } from 'hono/csrf'
import { createMiddleware } from 'hono/factory'
 
const accounts = Accounts.create({
  clientId: process.env.APP_URL,
  plugins: [
    backend({
      accessToken: true, 
      store: Store.memory(),
    }),
  ],
})
 
type Variables = { userId: string }
 
const auth = createMiddleware<{ Variables: Variables }>(async (c, next) => {
  const session = await accounts.session.get(c.req.raw)
  if (session?.method === 'tempo-id') c.set('userId', session.user.id)
  else if (session?.method === 'access-token')
    c.set('userId', session.token.userId)
  else return c.json({ error: 'invalid_token' }, 401)
 
  await next()
})
 
const app = new Hono().all('/api/*', (c) =>
  accounts.handler.fetch(c.req.raw),
)
 
app
  .use('/v1/*', csrf(), auth)
  .get('/v1/me', (c) => c.json({ userId: c.get('userId') }))
 
export default app

accessToken also takes the options of the tokens plugin, such as clientIds, and url, the public origin behind a proxy that terminates TLS, which each DPoP proof names.

Call an API for the user

session.fetch sends a request with the access token of the cookie's session. It returns undefined without a session, and sends no request then.

server.ts
import { Accounts, Store } from 'accounts'
import { backend } from 'accounts/plugins'
import { Hono } from 'hono'
 
const accounts = Accounts.create({
  clientId: process.env.APP_URL,
  plugins: [backend({ store: Store.memory() })],
})
 
const app = new Hono().all('/api/*', (c) =>
  accounts.handler.fetch(c.req.raw),
)
 
app.get('/v1/profile', async (c) => {
  const response = await accounts.session.fetch(c.req.raw, {
    url: 'https://api.example/me',
  })
  if (!response) return c.json({ error: 'invalid_token' }, 401)
  return c.json(await response.json())
})
 
export default app

Read the session in the page

After a reload, the page holds no session. The session route of accounts.handler returns the cookie's session, or null, so the click opens the dialog only without one.

import { useState } from 'react'
import { accounts } from './tempo.config.js'
 
type Session = Awaited<ReturnType<typeof accounts.dialog.signIn>>
 
export function App() {
  const [session, setSession] = useState<Session>()
 
  async function signIn() {
    const response = await fetch('/api/auth/session')
    const body = (await response.json()) as { session: Session | null }
    setSession(body.session ?? (await accounts.dialog.signIn()))
  }
 
  if (!session)
    return (
      <button onClick={signIn} type="button">
        Sign in
      </button>
    )
  return <p>Signed in as {session.user.email}</p>
}

Next steps