---
title: "Keep the session on your server"
description: "Make your web app's server check IdentityHound sign-in codes and keep each principal's session in an HTTP-only cookie, on the page's own origin or an API on another origin of the same site, so the page's JavaScript never holds the session token."
url: "https://agentpost.tools/docs/identityhound/guides/server-session"
kind: guide
needs:
  - what: "Your project's secret key, `key`, for your server, and to read sign-in codes from the test inbox in a `dev` project"
    from: "https://agentpost.tools/docs/platform/guides/keys.md"
  - what: "Your publishable key, `publishableKey`, listing your app's origins in `allowedOrigins`"
    from: "https://agentpost.tools/docs/platform/guides/keys.md"
---

# Keep the session on your server

Use this setup when your app has a server, on the same origin as its pages or on another origin of the same site; [Session strategies](/docs/identityhound/sdk/session-strategies.md) compares the choices.

Your server adds its endpoints over `createSessions` from `@agentpost-tools/identityhound-sdk/server`, and the page passes `serverSession()` to the [email sign-in component](/docs/identityhound/components/email-sign-in.md)’s identity. The example’s server uses [Hono](https://hono.dev) on Node; any server framework works the same way. The [SDK overview](/docs/identityhound/sdk.md) lists the packages and how to install them.

## Before you start

-   Your project's secret key, `key`, for your server, and to read sign-in codes from the test inbox in a `dev` project, from [Create a project and issue a key](/docs/platform/guides/keys.md).
-   Your publishable key, `publishableKey`, listing your app's origins in `allowedOrigins`, from [Create a project and issue a key](/docs/platform/guides/keys.md).

This page's code continues the script of the pages above: run its blocks after theirs, in the same file. To run them as a script of their own, first copy each helper from the page that defines it, and set each other value, such as a key or an ID, to one you already have.

## 1\. Add your server’s endpoints

Serve these endpoints at `/auth` on the same origin as your pages, and pass your secret key, `key`, as `secretKey` from your server’s environment:

```ts
// The app's server keeps the principal's session, in Hono. The page sends the
// emailed code here; this server verifies it with IdentityHound, keeps the
// session in an HTTP-only cookie, and answers with who signed in. On load the
// page asks here who is signed in; it asks for a short-lived user token only
// when a call to another Agentpost service needs one, and asks here to sign
// out. Its JavaScript never sees the session token.
//
// These are the endpoints `serverSession()` posts to, at `/auth`.
import { getConnInfo } from '@hono/node-server/conninfo';
import { IdentityhoundApiError } from '@agentpost-tools/identityhound-sdk';
import {
  createSessions,
  errorBody,
  type StartedSession,
  type Visitor,
} from '@agentpost-tools/identityhound-sdk/server';
import { Hono, type Context } from 'hono';
import { deleteCookie, getCookie, setCookie } from 'hono/cookie';
import type { ContentfulStatusCode } from 'hono/utils/http-status';

export interface SessionServerOptions {
  /** The project's secret key, `sk_test_…` or `sk_live_…`. Keep it on the server. */
  secretKey: string;
  /** IdentityHound's API root. Defaults to Agentpost's hosted API. */
  baseUrl?: string;
}

// Sent as `__Host-identityhound_session`: only over HTTPS, only to this
// host, and never readable from the page.
const COOKIE = 'identityhound_session';
const COOKIE_OPTIONS = {
  prefix: 'host',
  httpOnly: true,
  secure: true,
  sameSite: 'Lax',
  path: '/',
} as const;

export function createSessionServer({
  secretKey,
  baseUrl,
}: SessionServerOptions) {
  // A principal that signs up with a provider starts with the provider's name
  // and picture.
  const sessions = createSessions({
    secretKey,
    baseUrl,
    profileFromProvider: { name: 'displayName', avatar: true },
  });
  const app = new Hono();

  // Only the app's own pages may change the session.
  app.use('/auth/*', async (c, next) => {
    if (!fromThisSite(c))
      return c.json(
        { error: { code: 'forbidden', message: 'cross-site request' } },
        403,
      );
    c.header('Cache-Control', 'no-store');
    await next();
  });

  app.post('/auth/email-code/verify', async (c) => {
    const input = await c.req.json();
    const started = await sessions.verifyEmailCode(input, visitor(c));
    keepSession(c, started);
    return c.json(started.signedIn);
  });

  app.post('/auth/oauth/:providerKey/callback', async (c) => {
    const input = await c.req.json();
    const providerKey = c.req.param('providerKey');
    const started = await sessions.completeOAuth(
      providerKey,
      input,
      visitor(c),
    );
    keepSession(c, started);
    return c.json(started.signedIn);
  });

  app.post('/auth/session', async (c) => {
    const token = session(c);
    const principal = await sessions.principal(token);
    // The session ended, such as after a spell with no use: forget it.
    if (token && !principal) deleteCookie(c, COOKIE, COOKIE_OPTIONS);
    return c.json(principal ? { principal } : null);
  });

  // Only for a page that calls another Agentpost service itself.
  app.post('/auth/user-token', async (c) => {
    const token = session(c);
    const userToken = await sessions.userToken(token);
    // The session ended, such as after a spell with no use: forget it.
    if (token && !userToken) deleteCookie(c, COOKIE, COOKIE_OPTIONS);
    return c.json(userToken);
  });

  app.post('/auth/sign-out', async (c) => {
    await sessions.signOut(session(c));
    deleteCookie(c, COOKIE, COOKIE_OPTIONS);
    return c.body(null, 204);
  });

  // IdentityHound's refusals go to the page as they are, so its sign-in
  // shows the right words, such as "That code is wrong. 4 tries left."
  app.onError((error, c) => {
    if (error instanceof IdentityhoundApiError)
      return c.json(errorBody(error), error.status as ContentfulStatusCode);
    console.error(error);
    return c.json(
      { error: { code: 'internal_error', message: 'something went wrong' } },
      500,
    );
  });

  return app;
}

/** The session token the visitor's cookie holds. */
function session(c: Context) {
  return getCookie(c, COOKIE, 'host');
}

/** Keeps a new session in the cookie, until the session's own end. */
function keepSession(c: Context, started: StartedSession) {
  setCookie(c, COOKIE, started.token, {
    ...COOKIE_OPTIONS,
    expires: new Date(started.expiresAt),
  });
}

/** The browser signing in, so IdentityHound counts its guesses and records its session. */
function visitor(c: Context): Visitor {
  return {
    ip: getConnInfo(c).remote.address,
    userAgent: c.req.header('User-Agent'),
    session: session(c),
  };
}

/**
 * Whether a request came from this app's own pages. A browser says where a
 * request came from in `Sec-Fetch-Site`, and an older one in `Origin`. A
 * request with neither isn't from a browser, so it carries no visitor's
 * cookie to misuse.
 */
function fromThisSite(c: Context) {
  const site = c.req.header('Sec-Fetch-Site');
  if (site) return site === 'same-origin';
  const origin = c.req.header('Origin');
  return !origin || origin === new URL(c.req.url).origin;
}
```

-   **`/auth/session` answers who is signed in** on every page load, with `sessions.principal`, which asks IdentityHound with the cookie’s session and mints no user token. **`/auth/user-token`** is only for a page that calls another Agentpost service itself: leave it out when your page doesn’t, and the page never holds a credential.
-   **Only your own pages may call them.** A request whose `Sec-Fetch-Site` isn’t `same-origin` gets 403, and so does one with no `Sec-Fetch-Site` whose `Origin` isn’t your site’s. Another site then can’t sign your visitor out, or sign them in to an account of its choosing. A request with neither header passes: it doesn’t come from a browser, so it carries no visitor’s cookie. Every request that passes gets `Cache-Control: no-store`.
-   Behind a proxy, pass the address your proxy reports; [The visitor](/docs/identityhound/sdk/server.md#the-visitor) explains.

## 2\. Point the page at your endpoints

Pass `serverSession()` as the identity’s `session`, and pass your publishable key as `publishableKey`: the page still requests the emailed code itself.

```tsx
// The page's half: IdentityHound's email-code component, with the session
// kept on the app's server. `serverSession()` posts the code to the app's
// endpoints in ./server.ts, which keep the session in an HTTP-only cookie,
// so this page only ever holds who is signed in and short-lived user tokens.
import {
  IdentityhoundProvider,
  useSession,
} from '@agentpost-tools/identityhound-react';
import {
  serverSession,
  type IdentityOptions,
  type ServerSessionOptions,
} from '@agentpost-tools/identityhound-sdk/workflows';
import { EmailCodeSignIn } from '@agentpost-tools/identityhound-ui/react';

export interface ServerSessionAppProps {
  /** The project's publishable key, `pk_test_…` or `pk_live_…`, which requests the emailed code. */
  publishableKey: string;
  /** IdentityHound's API root. Defaults to Agentpost's hosted API. */
  baseUrl?: string;
  /** For tests: how the page calls IdentityHound. */
  fetch?: IdentityOptions['fetch'];
  /** For tests: how the page calls its own server. */
  serverFetch?: ServerSessionOptions['fetch'];
}

export function ServerSessionApp({
  publishableKey,
  baseUrl,
  fetch,
  serverFetch,
}: ServerSessionAppProps) {
  return (
    <IdentityhoundProvider
      publishableKey={publishableKey}
      session={serverSession({ fetch: serverFetch })}
      baseUrl={baseUrl}
      fetch={fetch}
    >
      <Account />
    </IdentityhoundProvider>
  );
}

function Account() {
  const session = useSession();
  if (session.status === 'loading') return <p>Loading…</p>;
  if (session.status === 'signed_in')
    return (
      <p>
        {session.principal.displayName
          ? `Signed in as ${session.principal.displayName}. `
          : 'Signed in. '}
        <button type="button" onClick={() => void session.signOut()}>
          Sign out
        </button>
      </p>
    );
  return <EmailCodeSignIn />;
}
```

-   `serverSession()` posts to `/auth` on the page’s own origin, with the cookie. Its `basePath` and `headers` options serve the endpoints at another path or add a header of your own, such as a CSRF token. For an API on another origin, pass a full URL as `basePath`; [Serve the API from another origin](#3-serve-the-api-from-another-origin) covers the rest.
-   On load the page posts to `/auth/session` to learn who is signed in. It asks `/auth/user-token` only when something on the page calls `getUserToken()`, such as another service’s browser component.
-   As Web Components, pass the same strategy to `createIdentity`: `createIdentity({ publishableKey, session: serverSession() })`.

## 3\. Serve the API from another origin

Skip this step when your endpoints are on your pages’ own origin. Many apps serve their API from a sibling host, such as pages at `https://app.example.com` and the API at `https://api.example.com`, or two `localhost` ports in development. Both are the same site, so the browser sends the API’s `SameSite=Lax` cookie with the page’s requests once you allow it. Four things change.

**The page.** Pass the API’s full URL as `basePath`. `serverSession()` then sends the cookie with `credentials: 'include'`:

```ts
serverSession({ basePath: 'https://api.example.com/auth' });
```

**The origin check.** A request from your pages now arrives with `Sec-Fetch-Site: same-site`, never `same-origin`, so check `Origin` against your pages’ origins instead. A browser sends `Origin` on every cross-origin `POST`:

```ts
const PAGES = new Set(['https://app.example.com']);

function fromThisSite(c: Context) {
  const origin = c.req.header('Origin');
  // A request with no Origin isn't from a browser, so it carries no visitor's cookie.
  return origin === undefined || PAGES.has(origin);
}
```

**Credentialed CORS.** Answer the page’s requests, and the preflight for its JSON `POST`, with your pages’ origin by name, never `*`, and allow credentials. With Hono:

```ts
import { cors } from 'hono/cors';

app.use(
  '/auth/*',
  cors({
    origin: [...PAGES],
    credentials: true,
    allowMethods: ['POST'],
    allowHeaders: ['content-type', 'accept'],
  }),
);
```

Add any header you pass in `serverSession`’s `headers`, such as a CSRF token, to `allowHeaders`.

**The cookie.** Set it from the API, with no `Domain`, so only the API’s host gets it. Keep the `__Host-` prefix when the cookie can have `Path=/`. When the API serves other routes that shouldn’t receive the session, give it a narrower path, such as `Path=/auth`, and name it with the `__Secure-` prefix instead, since `__Host-` requires `Path=/`. Keep `HttpOnly`, `Secure`, and `SameSite=Lax` either way. In development over `http://localhost`, drop the prefix and `Secure`, which a browser refuses on plain HTTP.

## 4\. Check access on your server

Skip this step when anyone who signs in may use your app. When only some principals may, check on your server before it sets the cookie, so a refused principal is never signed in:

1.  Call `sessions.verifyEmailCode(input, visitor)` or `completeOAuth` with a `visitor` that leaves out `session`, so the session already in the browser isn’t revoked yet.
2.  Check `started.signedIn.principal` against your own records.
3.  To refuse, call `sessions.signOut(started.token)`, set no cookie, and answer an error body, such as `403` with `{ "error": { "code": "not_authorized", "message": "…" } }`. The page’s sign-in shows `not_authorized`.
4.  To let them in, call `sessions.signOut(previousCookie)` for the session the browser held before, if any, then set the new cookie and answer `started.signedIn`.

A phone app with its own API checks with `deviceSession`’s `authorize` instead: [Check access before the sign-in counts](/docs/identityhound/sdk/session-strategies.md#check-access-before-the-sign-in-counts).

## Check it worked

Sign in through the page. In a `dev` project, use an address at `.test`: its code waits in the [test inbox](/docs/platform/concepts/environments.md#test-inbox), which you read with `key`. Then check:

1.  The answer to the sign-in’s `/auth/email-code/verify` request sets `__Host-identityhound_session` with `HttpOnly`, `Secure`, `SameSite=Lax`, and `Path=/`, and its value starts with `agp_st_`.
2.  No answer body the page receives, no `document.cookie`, and nothing in `localStorage` or `sessionStorage` holds that value.
3.  `POST /auth/session` from the page answers `{ "principal": { … } }`, and still does after a reload. A reload sends no `POST /auth/user-token`.
4.  After `useSession().signOut()`, `POST /auth/session` answers `null`.

The example app’s test asserts the first two after a sign-in:

```ts
// The cookie: the session token, HTTP-only, Secure, SameSite=Lax, ending with the session.
const [set] = browser.setCookies;
assert.equal(set.name, COOKIE);
session = set.value;
assert.match(session, /^agp_st_/);
assert.equal(set.attributes.httponly, '');
assert.equal(set.attributes.secure, '');
assert.equal(set.attributes.samesite, 'Lax');
assert.equal(set.attributes.path, '/');
assert.equal(set.attributes.domain, undefined);

// The page got who signed in and user tokens, never the session token.
assert.ok(browser.bodies.length > 0);
for (const body of browser.bodies)
  assert.ok(!body.includes(session), `no session token in ${body}`);
assert.ok(!document.cookie.includes(session));
assert.equal(localStorage.length, 0);
assert.equal(sessionStorage.length, 0);
```
