# Storage (https://session-kit.pages.dev/docs/configuration/storage)

A user who reloads the page, or opens your app the next day, expects to
still be signed in. That works because the client saves the session, and
`createAuth`'s `storage` option chooses where.

This page helps you pick a built-in store, set how long a saved session
lasts, or write a store of your own.

## Pick a store

The `storage` option takes one of Session kit's stores, or any object that
implements `AuthStorage`:

| Storage                           | Saved in                                                    | Use it for                                           |
| --------------------------------- | ----------------------------------------------------------- | ---------------------------------------------------- |
| `webStorage()`                    | `localStorage`                                              | Browsers. One session, shared by every tab.          |
| `webStorage({ area: "session" })` | `sessionStorage`                                            | One session per tab, ending with the tab.            |
| `secureStorage()`                 | The iOS keychain, or encrypted with an Android Keystore key | Expo apps. From `@monarcode/session-kit/expo`.       |
| `memoryStorage()`                 | Memory                                                      | Tests, and sessions that shouldn't outlive the page. |
| Your own `AuthStorage`            | Anywhere                                                    | Another store. Its operations can return promises.   |

`secureStorage()` splits a large session across several keys, since some
iOS releases refuse long values. Its
[reference](https://session-kit.pages.dev/docs/reference/expo#securestorage) has the details.

### Use localStorage with rotating refresh tokens

If your backend rotates refresh tokens, issuing a new one with each refresh,
use `localStorage`, not `sessionStorage`.

A browser copies `sessionStorage` into a duplicated tab, and into a window
opened with `window.open`. Both then start with the same refresh token but
never see each other's saves. The second to refresh sends a spent token and
is signed out. With reuse detection on the backend, both are.

## How long a saved session lasts

A saved session lasts 30 days from the last time it was saved. To change
that, pass `maxAge` to `createAuth`, in whole seconds: `7 * 24 * 60 * 60` for
a week.

Every save starts the count again, and the client saves at each sign-in,
refresh and profile update. A user who comes back within `maxAge` finds the
session restored, and one who's been away longer signs in again.

The client checks `maxAge` when it restores a saved session, such as on a
reload. Each save records its expiry, so a lower `maxAge` applies to a saved
session from its next save. A session saved longer ago isn't restored: the client clears it, and
the user is signed out without an error. So is a session saved in another
format by an older or newer version of Session kit.

`maxAge` must be a positive whole number. Anything else makes `createAuth`
throw `INVALID_OPTIONS`.

## Write your own store

To save the session somewhere else, write an `AuthStorage`. For example, to
save it in a key-value store your app already has, which removes each entry
when it expires:

```ts title="src/storage.ts"
import type { AuthStorage } from "@monarcode/session-kit";

declare const store: {
  get(key: string): Promise<string | undefined>;
  put(
    key: string,
    value: string,
    options: { expiresAt: number },
  ): Promise<void>;
  delete(key: string): Promise<void>;
};

export const kvStorage: AuthStorage = {
  get: async (key) => (await store.get(key)) ?? null,
  // The store drops the session itself when it's no longer valid.
  set: (key, value, { expiresAt }) => store.put(key, value, { expiresAt }),
  remove: (key) => store.delete(key),
};
```

An `AuthStorage` needs three operations: `get`, `set` and `remove`. Here's
what to know about them:

- Each can return a promise. A `get` that answers synchronously lets a saved
  session restore before the first render.
- `set` also receives `expiresAt`: when the saved session stops being valid,
  `maxAge` after this save, in Unix milliseconds.
- The client runs your store's operations one at a time, in the order it
  issued them, so a store that answers out of order is still safe.
- To report a failure, throw or reject. The client turns it into a
  `PERSISTENCE_FAILED` error, and
  [Handle storage failures](https://session-kit.pages.dev/docs/configuration/errors#handle-storage-failures)
  explains what happens next.

A store that several tabs share needs two more members, as `webStorage()`
has. `subscribe` tells the client when another tab changes the session, so
that [tabs follow each other](https://session-kit.pages.dev/docs/configuration/tabs). `lock` lets the tabs
take turns to refresh. An optional `debug` member adds your store's own
events to the [debug log](https://session-kit.pages.dev/docs/configuration/debugging). See
[`AuthStorage`](https://session-kit.pages.dev/docs/reference/core#authstorage) for each member.

## What the client saves

The client saves the tokens and the user in one `<name>:auth:session` entry.
Each save is then a single write, which other tabs see whole. A
[user read from the access token](https://session-kit.pages.dev/docs/client/users-from-tokens) isn't
saved. The client reads it from the token again on restore.

## Next steps

- [Tabs](https://session-kit.pages.dev/docs/configuration/tabs): see how tabs that share `localStorage`
  stay in step.
- [Errors](https://session-kit.pages.dev/docs/configuration/errors#handle-storage-failures): decide what
  to show when storage can't be read, written or cleared.
- [Security](https://session-kit.pages.dev/docs/security): compare how each place protects the tokens.