# Server (https://session-kit.pages.dev/docs/reference/server)

Import these from `@monarcode/session-kit/server`. To set it up, see
[Server sessions](https://session-kit.pages.dev/docs/server-rendering/server-sessions).

## Functions

### createServerAuth

Creates the server side of Session kit ([`ServerAuth`](#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`](#serverauthoptions) for every option.

### sessionHandler

Makes the handler for your session route ([`SessionHandler`](#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.

### 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       | Description                                                                                                                                                                                                                                    |
| ---------- | ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `get`      | `function` | Returns the request's cookie `name`, or `undefined` when it has none.                                                                                                                                                                          |
| `set`      | `function` | Sets cookie `name` on the response.                                                                                                                                                                                                            |
| `delete`   | `function` | Removes cookie `name`, with the attributes it was set with.                                                                                                                                                                                    |
| `writable` | `union`    | Whether the response can still set cookies. It's `false` where the framework can't, such as while a Next.js Server Component renders. Then nothing is refreshed or saved, and calls that would write reject, as each `serverAuth` method says. |

### CookieOptions

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

### 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     | Description                                                      |
| ---------- | -------- | ---------------------------------------------------------------- |
| `httpOnly` | `true`   | Always `true`: page scripts can't read the session cookie.       |
| `secure`   | `union`  | Whether the cookie is sent over HTTPS only.                      |
| `sameSite` | `union`  | Which cross-site requests carry the cookie.                      |
| `path`     | `string` | The paths that receive the cookie.                               |
| `domain?`  | `string` | The domain that receives the cookie, or none for this host only. |
| `maxAge?`  | `number` | Lifetime in seconds. Absent when deleting.                       |

### RefreshIfDueOptions

Options for [`ServerAuth`](#serverauth)'s `refreshIfDue`.

### RefreshIfDueOptions

Options for ServerAuth's `refreshIfDue`.

| Prop      | Type     | Description                                                                                                                                                                                                                    |
| --------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `within?` | `number` | Refreshes when the access token expires within this many seconds, so it lasts through the request. Keep it well below the token's lifetime: a token that lives less than `within` is refreshed on every request. Default: `60` |

### RequestAuth

One request's session: what [`ServerAuth`](#serverauth) does for a request, without its [`CookieJar`](#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`](#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`](#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`](#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`](#createserverauth). It keeps the session in an encrypted cookie.

Your framework's adapter gives you one request's session ([`RequestAuth`](#requestauth)), with every method and no cookie jar. Its methods are here too, each taking the request's [`CookieJar`](#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`](#requestauth)'s `signIn` says what that means.

Members:

- `getSession`: [`RequestAuth`](#requestauth)'s `getSession`, for `jar`.
- `refreshIfDue`: [`RequestAuth`](#requestauth)'s `refreshIfDue`, for `jar`. It refreshes at most once per jar.
- `signIn`: [`RequestAuth`](#requestauth)'s `signIn`, for `jar`.
- `signOut`: [`RequestAuth`](#requestauth)'s `signOut`, for `jar`.
- `credentials`: [`RequestAuth`](#requestauth)'s `credentials`, for `jar`.
- `credentials.get`: Resolves the access token for `jar`, or `null`, as [`RequestAuth`](#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`](#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`](#requestauth)'s `clientCredentials`, for `jar`.
- `clientCredentials.get`: The access token for your page scripts, for `jar`, as [`RequestAuth`](#requestauth)'s `clientCredentials.get` gives it.
- `clientCredentials.renew`: Renews the page scripts' access token for `jar`, as [`RequestAuth`](#requestauth)'s `clientCredentials.renew` does.
- `forRequest`: This request's session ([`RequestAuth`](#requestauth)), for code that has the request's jar. The same jar always gives the same object.
- `updateUser`: [`RequestAuth`](#requestauth)'s `updateUser`, for `jar`.

### ServerAuthOptions

Options for [`createServerAuth`](#createserverauth). `user`, `refresh`, `revoke`, `maxAge` and `debug` work as they do for `createAuth`.

### ServerAuthOptions

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

| Prop                 | Type                                 | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| -------------------- | ------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name`               | `string`                             | Names this auth and its cookie, `<name>.session`, which is split into `<name>.session.0…n` when large. Up to 64 letters, digits, `_` or `-`.                                                                                                                                                                                                                                                                                                                                                                                            |
| `user`               | `Src`                                | Where the user comes from: a schema that checks the `user` passed to `signIn`, or `fromAccessToken(…)`. The cookie is trusted once sealed, but `signIn` doesn't check its input with your backend (RequestAuth's `signIn` says what to do).                                                                                                                                                                                                                                                                                             |
| `secret`             | `union`                              | The key that seals the cookie, with AES-256-GCM: at least 32 random characters, kept out of your code and the browser. Pass a list to rotate keys. The first seals, and any of them opens, so sessions survive a new secret. A cookie none of them opens reads as signed out. It's checked when a method first runs, not at creation, so build tools that load your module without it, such as `next build`, still work. Without a valid secret, every method rejects with `INVALID_OPTIONS`, and a request's `state` is `unavailable`. |
| `refresh?`           | `RefreshFn<NoInfer<UserInput<Src>>>` | Exchanges a refresh token for new tokens, as RefreshFn says.                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `revoke?`            | `RevokeFn`                           | Asks your backend to revoke the tokens after `signOut` (RevokeFn).                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `maxAge?`            | `number`                             | How long the cookie lasts, in seconds. Each save starts it again. Default: 30 days.                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `cookie?`            | `SessionCookieOptions`               | The session cookie's attributes (SessionCookieOptions). Default: each attribute's own.                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `clientCredentials?` | `union`                              | Lets your session route, or a request's `clientCredentials`, give the access token to your own page scripts. The refresh token never leaves the server. Without it, `clientCredentials` rejects with `INVALID_OPTIONS`. Default: `false`                                                                                                                                                                                                                                                                                                |
| `debug?`             | `union`                              | Logs what Session kit does on the server, like `createAuth`'s `debug` option.                                                                                                                                                                                                                                                                                                                                                                                                                                                           |

### SessionCookieOptions

The session cookie's attributes: the `cookie` option of [`ServerAuthOptions`](#serverauthoptions). The cookie is always `httpOnly`.

### SessionCookieOptions

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

| Prop        | Type     | Description                                                                                                                          |
| ----------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| `secure?`   | `union`  | Sends the cookie over HTTPS only. Turn it off only for plain-http development on `localhost`. Default: `true`                        |
| `sameSite?` | `union`  | Which cross-site requests send the cookie. `"none"` needs `secure`, or `createServerAuth` throws `INVALID_OPTIONS`. Default: `"lax"` |
| `path?`     | `string` | The paths the cookie is sent to. Default: `"/"`                                                                                      |
| `domain?`   | `string` | Shares the cookie with subdomains. Default: this host only.                                                                          |

### SessionHandler

Answers the browser client's requests to your session route, for one request and its cookie jar. [`sessionHandler`](#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`.

### 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     | Description                                                                                                                                                                             |
| --------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `within?`       | `number` | Refreshes when the access token expires within this many seconds, as RefreshIfDueOptions explains. Default: `60`                                                                        |
| `cacheControl?` | `union`  | The `Cache-Control` header for every response that doesn't set its own, as each one depends on who is signed in. `false` leaves every response as it is. Default: `"private, no-store"` |