Skip to Content

Server

Sessions kept on the server, in an encrypted cookie.

Import these from @monarcode/session-kit/server. To set it up, see Server sessions.

Functions

createServerAuth

Creates the server side of Session kit (ServerAuth). It keeps both tokens and the user in an encrypted, httpOnly cookie, so page scripts never see the refresh token.

Create one per app, at module level, and give it to your framework's adapter for each request's session. Throws INVALID_OPTIONS for options it can't use, such as a bad name. A missing or short secret is reported later, when a method first runs.

See ServerAuthOptions for every option.

sessionHandler

Makes the handler for your session route (SessionHandler), which answers createMirrorAuth's endpoint. A GET reads the session. A POST signs out, or gets or renews the access token for page scripts.

It answers only this site's own pages, by the Sec-Fetch-Site header, so another site can't sign the user out or ask for a token. Browsers send it to https and localhost pages, since 2023 (Safari 16.4). Without it, as on plain http, a GET is answered, and a POST needs an Origin header that matches the request's URL. Anything else is refused with 403. Every answer has Cache-Control: no-store.

The access token is served only when createServerAuth has clientCredentials. A failure answers with its AuthErrorCode, which the browser client rejects with. Anything that isn't an AuthError is thrown, for your framework to log.

A request it can't read answers 400 with INVALID_OPTIONS. Otherwise a failure's status is 401 for UNAUTHENTICATED, 409 for SESSION_CHANGED and 500 for any other code. That includes INVALID_OPTIONS from the server's setup, such as a missing secret or middleware, so your monitoring sees it. A method other than GET or POST answers 405.

Each framework's sessionRoute wraps it in a route. Use it directly on a server without an adapter, with the request's cookie jar.

Types

ClientCredentials

The access token as your server gives it to the browser, from serverAuth.clientCredentials in @monarcode/session-kit/server. expiresIn counts from when the server answered, so the browser's clock doesn't matter.

CookieJar

Reads and writes one request's cookies, for createServerAuth's methods. The framework adapters, such as nextJar and startJar, build one. Elsewhere, wrap the request's cookies and the response's Set-Cookie.

Make a new jar for each request, and pass it to every call while handling that request, so they share one refresh and see each other's writes. Never keep one at module level, or one request's session would show in the next.

Prop

Type

CookieOptions

The session cookie's attributes, as CookieJar's set and delete receive them. Every framework's cookie API takes this shape, or maps from it in a line.

Prop

Type

RefreshIfDueOptions

Options for ServerAuth's refreshIfDue.

Prop

Type

RequestAuth

One request's session: what ServerAuth does for a request, without its CookieJar. startAuth from @monarcode/session-kit/tanstack-start/server and routerAuth from @monarcode/session-kit/react-router/server give you one, and so do readOnly() and writable() from nextSession in @monarcode/session-kit/next. Elsewhere, serverAuth.forRequest(jar) does.

It's shaped like a client, so code written for one works on the server with it, such as createAuthFetch from @monarcode/session-kit/http. U is the user, and I is the user signIn accepts, as for ServerAuth. Write SessionOf or UserOf from @monarcode/session-kit for its types.

Some requests can't set cookies: a Next.js page, or a React Router loader once its response has left the middleware. There, nothing can be saved, so signIn, signOut, updateUser and refreshIfDue reject with INVALID_OPTIONS. getSession still resolves, and credentials.get rejects with REFRESH_FAILED once the access token has expired. Refresh first, in middleware or a proxy, with refreshIfDue.

Members:

  • getSession: Resolves who is signed in, from the cookie, or null. It holds no tokens, so you can return it to the browser, such as from a server function or a loader. An expired access token is refreshed first, and a refresh token your backend rejects signs out. Rejects with REFRESH_FAILED when that refresh fails. Where the request can't set cookies, the session is returned as the cookie holds it.
  • refreshIfDue: Refreshes the access token when it has less than within seconds left (RefreshIfDueOptions), then resolves the session. Each adapter's middleware calls it before rendering, so pages get a fresh token to read. Call it yourself only in middleware of your own. It refreshes at most once per request. A failed refresh is ignored while the access token still works. Once the token has expired, it rejects with REFRESH_FAILED. Rejects with INVALID_OPTIONS for a negative within, or where the request can't set cookies.
  • signIn: Signs in by sealing your backend's tokens and the user into the cookie, replacing any session it held. Pass what your backend's sign-in returned: accessToken, refreshToken if there is one, and user unless the user comes from the access token. Resolves the new session, which holds no tokens, so you can return it to the browser. It never calls your backend, and trusts what it's given. If the browser signs in with your backend and sends the tokens and the user, the cookie's user is what the browser said, until a refresh or updateUser replaces it. Show it, but let your backend authorize with the access token. To trust it, check the input first, or sign in on the server. Rejects with USER_VALIDATION_FAILED for a user your schema rejects, with INVALID_SESSION for tokens that already expired, and with PERSISTENCE_FAILED for a session too large for the cookie. Rejects with INVALID_OPTIONS where the request can't set cookies.
  • signOut: Signs out by clearing the cookie, then calls revoke and waits for it. A failed revoke doesn't reject. The browser's client signs out through your session route, so call it yourself only from server code of your own, such as an action. Rejects with INVALID_OPTIONS where the request can't set cookies.
  • credentials: The access token (Credentials), for server code that calls your API. get, renew and reject work like the client's.
  • clientCredentials: The access token for your own page scripts (ClientCredentials), with the clientCredentials option. Your session route serves these. Expose them yourself only to your own site's pages, protected against CSRF. Both reject with INVALID_OPTIONS without the option.
  • isCurrent: Whether session is the one this request has read.
  • state: The state of this request's session, an AuthState. It's initializing until a call reads the cookie. Where the request can set cookies and the access token has expired, it stays so until a call refreshes it. It's unavailable when the request can't set cookies and the access token has expired, or the secret is missing. A Next.js page, which can't set cookies, follows the session that the same request's Server Function signed in or refreshed. Listeners must not throw. Their errors are rethrown asynchronously, which is an uncaught exception on a server.
  • updateUser: Replaces the signed-in user in the cookie, such as after a profile edit, and resolves the session. Pass the user, or an async function that fetches it. The session ID stays. Rejects with UNAUTHENTICATED when signed out, and with USER_VALIDATION_FAILED for a user your schema rejects, or when the function rejects or times out. Rejects with INVALID_OPTIONS where the request can't set cookies.

ServerAuth

The server side of Session kit, from createServerAuth. It keeps the session in an encrypted cookie.

Your framework's adapter gives you one request's session (RequestAuth), with every method and no cookie jar. Its methods are here too, each taking the request's CookieJar, for a server without an adapter. forRequest(jar) gives that request's session, which alone has isCurrent and state.

U is the user, and I is the user signIn accepts, or never with fromAccessToken. Write typeof serverAuth rather than spelling them out.

Nothing is kept between requests except a short record of new tokens, so parallel requests that carry the same cookie share one refresh. That record belongs to one createServerAuth call. A framework may load your module once per bundle, making several, so with rotating refresh tokens, give your backend a short reuse window.

signIn trusts what it's given. RequestAuth's signIn says what that means.

Members:

  • getSession: RequestAuth's getSession, for jar.
  • refreshIfDue: RequestAuth's refreshIfDue, for jar. It refreshes at most once per jar.
  • signIn: RequestAuth's signIn, for jar.
  • signOut: RequestAuth's signOut, for jar.
  • credentials: RequestAuth's credentials, for jar.
  • credentials.get: Resolves the access token for jar, or null, as RequestAuth's credentials.get does. With a read-only jar, an expired one rejects with REFRESH_FAILED.
  • credentials.renew: Gets a new access token for jar after your API rejected credentials, as RequestAuth's credentials.renew does.
  • credentials.reject: Signs jar's session out because your API rejected credentials for good, unless they're no longer current. Rejects with INVALID_OPTIONS given a read-only jar.
  • clientCredentials: RequestAuth's clientCredentials, for jar.
  • clientCredentials.get: The access token for your page scripts, for jar, as RequestAuth's clientCredentials.get gives it.
  • clientCredentials.renew: Renews the page scripts' access token for jar, as RequestAuth's clientCredentials.renew does.
  • forRequest: This request's session (RequestAuth), for code that has the request's jar. The same jar always gives the same object.
  • updateUser: RequestAuth's updateUser, for jar.

ServerAuthOptions

Options for createServerAuth. user, refresh, revoke, maxAge and debug work as they do for createAuth.

Prop

Type

SessionCookieOptions

The session cookie's attributes: the cookie option of ServerAuthOptions. The cookie is always httpOnly.

Prop

Type

SessionHandler

Answers the browser client's requests to your session route, for one request and its cookie jar. sessionHandler makes one.

SessionMiddlewareOptions

Options for the middleware that refreshes before each request: refreshSession from @monarcode/session-kit/tanstack-start/server and sessionMiddleware from @monarcode/session-kit/react-router/server.

Prop

Type

On this page