---
title: "Session strategies | IdentityHound SDK"
description: "Choose where the IdentityHound SDK keeps a principal's session, on your server with serverSession, in the client with deviceSession, or with your own strategy, and learn what each one exposes to the page."
url: "https://agentpost.tools/docs/identityhound/sdk/session-strategies"
kind: sdk
---

# Session strategies

A session strategy keeps a principal’s [session](/docs/identityhound/concepts/sessions.md) token. The workflows and components use the credential the strategy hands them. Pass one as `session` to `createIdentity`, or to `IdentityhoundProvider` in React. Both strategies are in `@agentpost-tools/identityhound-sdk/workflows`.

Choose by where your code runs:

-   A web app with a server uses [`serverSession`](#serversession), whether the server is on the pages’ own origin or on another origin of the same site.
-   A phone app, or a web app with no server, uses [`deviceSession`](#devicesession).
-   An app whose server already has its own endpoints for this passes [its own strategy](#your-own-strategy).

| Strategy | Checks the code | Keeps the session token | The page’s JavaScript can read |
| --- | --- | --- | --- |
| `serverSession` | Your server | An HTTP-only cookie | Who signed in, and user tokens once a call asks for one; never the session token |
| `deviceSession` | This client | `storage`, under `key` | On the web, the session token itself, in `localStorage` |
| Your own strategy | Your endpoints | Wherever your endpoints keep it | What your endpoints answer |

## `serverSession`

`serverSession({ basePath, credentials, headers, fetch })` keeps the session on your server, in an HTTP-only cookie your server sets. It posts JSON to your endpoints at `basePath`, with the cookie. `basePath` is `/auth` by default, on the page’s own origin. For an API on another origin of the same site, such as `https://api.example.com` for pages at `https://app.example.com`, pass a full URL, such as `https://api.example.com/auth`. `credentials` defaults to `include` for a full URL, so the browser sends the cookie there, and `same-origin` for a path. `headers` adds headers to every request, such as a CSRF token your server asks for.

Name the cookie with the `__Host-` prefix, such as `__Host-identityhound_session`, and set it with `HttpOnly`, `Secure`, `SameSite=Lax`, and `Path=/`, no `Domain`, and the session’s `expiresAt` as its expiry. The `__Host-` prefix makes the browser keep it only from HTTPS, for this exact host. [Serve the API from another origin](/docs/identityhound/guides/server-session.md#3-serve-the-api-from-another-origin) covers a cookie that needs a narrower path.

Your server answers these endpoints, each a `POST` with a JSON body:

-   **`/auth/email-code/verify`** takes the fields the page sent, checks the code, starts the session, sets the cookie, and answers who signed in, `{ principal, signedUp }`.
-   **`/auth/oauth/:providerKey/callback`** takes the provider’s `code` and `state`, and finishes a sign-in with a provider, such as Twitch, the same way.
-   **`/auth/session`** answers who the cookie’s session signs in, `{ principal }`, or `null` when there is none or it has ended. The page asks it on every load. Clear the cookie when the session has ended.
-   **`/auth/user-token`** answers a new user token, `{ token, expiresAt }`, from the cookie’s session, or `null` when there is none or it has ended. The page asks only when a call from the page needs one, such as another Agentpost service’s browser component. An app that calls no Agentpost service from the page leaves it out, and the page never holds a credential.
-   **`/auth/sign-out`** revokes the session, clears the cookie, and answers 204.

An endpoint that refuses answers IdentityHound’s standard error body at IdentityHound’s status. The [server helpers](/docs/identityhound/sdk/server.md#keep-sessions-in-a-cookie) do IdentityHound’s side of each endpoint, and [Keep the session on your server](/docs/identityhound/guides/server-session.md) builds them.

## `deviceSession`

`deviceSession({ storage, key, bearer, authorize })` keeps the session in this client, in `storage`, under `key`, which is `identityhound.session` by default, with the principal it signed in. On the web, any script on the page can read it in `localStorage`. By default the strategy hands workflows a Platform user token. Set `bearer: 'session'` to hand them the session token instead, such as for your own API; `identity.getSessionToken()` then returns it.

`storage` has `getItem`, `setItem`, and `removeItem`, which may return promises. On a phone, wrap the keychain, such as expo-secure-store, as [Native apps](/docs/identityhound/sdk/native-apps.md#keep-the-session-in-the-keychain) shows; on the web, pass `localStorage`.

### Check access before the sign-in counts

`authorize` lets your app turn a sign-in away before anything is stored, such as an app only some principals may use. It gets `{ principal, signedUp, bearer }` once IdentityHound accepts the code. `bearer` is what signed-in calls will send: the session token with `bearer: 'session'`, or a user token minted from it. Ask your API with it, and resolve `true` to let the principal in.

-   Resolving `false` revokes the session, stores nothing, and fails the sign-in with `not_authorized`. The identity never becomes `signed_in`.
-   Rejecting does the same and fails with the rejection’s error, such as `network_error` when your API can’t be reached. The code the principal typed is spent, so they request a new one.

```ts
deviceSession({
  storage: keychain,
  bearer: 'session',
  authorize: async ({ bearer }) => {
    const response = await fetch('https://api.example.com/v1/me', {
      headers: { authorization: `Bearer ${bearer}` },
    });
    if (response.status === 401 || response.status === 403) return false;
    if (!response.ok) throw new Error(`the API answered ${response.status}`);
    return true;
  },
});
```

With `serverSession`, your server checks instead, before it sets the cookie: [Check access on your server](/docs/identityhound/guides/server-session.md#4-check-access-on-your-server).

## How the identity loads

`identity.load()`, which `IdentityhoundProvider` calls on mount, asks the strategy who is signed in. It mints no user token; the identity mints one only when a call needs it.

| Strategy | `load()` | `load({ verify: false })` |
| --- | --- | --- |
| `serverSession` | Posts to `/auth/session` | The same: the page keeps nothing to answer from |
| `deviceSession` | `GET /me` with the session; a 401 forgets it | Reads the principal kept at sign-in, with no request; a session kept by an older SDK is checked once instead |

Use `{ verify: false }` when your own API checks the session on its first call anyway, so the app makes no request to IdentityHound on start. When your API refuses the session, sign out with `{ revoke: false }`. In React, pass `load={{ verify: false }}` to the provider, or `load={false}` to call `identity.load()` yourself.

## Sign out

`identity.signOut()` ends the session, and `identity.signOut({ revoke: false })` only forgets it here.

-   **`deviceSession`** deletes the stored session first, then revokes it with IdentityHound. A revoke that fails, such as with no network, is ignored: the principal is signed out on this device either way, and the session ends on its own once idle. With `{ revoke: false }`, it sends nothing. To end the session at your own API first, such as to drop a push token, call your API with `identity.getSessionToken()` before `signOut()`.
-   **`serverSession`** posts to `/auth/sign-out`. When your server refuses or can’t be reached, `signOut()` rejects and the principal stays signed in, since the cookie is still set. With `{ revoke: false }`, it posts nothing, for a session your server already ended and whose cookie it already cleared.

## Your own strategy

Your own strategy is an object with:

-   `verifyEmailCode(input)`, which resolves to `{ principal, signedUp }`.
-   `completeOAuth(providerKey, input)`, when the app signs in with a provider. It resolves to `{ principal, signedUp }`.
-   `principal({ verify })`, optional, which resolves to who the session signs in, or `null`. Without it, the identity loads with `userToken()` and `GET /me`.
-   `userToken()`, which resolves to `{ token, expiresAt }`, or `null`.
-   `sessionToken()`, optional, which resolves to the session itself, `{ token, expiresAt }`, or `null`. Leave it out unless your page may hold the session.
-   `signOut({ revoke })`, which forgets the session, and ends it too when `revoke` is true.

When a workflow catches an `IdentityhoundApiError`, it keeps the API’s error code. For another rejection it keeps a string `code` if present, or sets `network_error`. A code the workflow doesn’t know comes as `unknown`, with the original in `details.code`.
