# Expiry (https://session-kit.pages.dev/docs/configuration/expiry)

The client refreshes the access token before it expires, so it reads when
that is from your tokens. Your backend can say so in a few ways: a lifetime
in the sign-in response, a fixed time, or claims inside a JWT.

This page shows where the client reads the expiry from, which field to send,
and what happens when there's none.

## Send the token's lifetime

Most backends answer with a lifetime, such as OAuth's `expires_in`. Pass it
as `expiresIn`, in seconds:

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

type TokenResponse = {
  access_token: string;
  refresh_token: string;
  expires_in: number;
};

export const toTokens = (body: TokenResponse): Tokens => ({
  accessToken: body.access_token,
  refreshToken: body.refresh_token,
  expiresIn: body.expires_in,
});
```

The client counts `expiresIn` from when it receives the tokens, so a wrong
device clock doesn't matter. Send `expiresAt`, in Unix milliseconds, only
when your backend gives no lifetime.

Pass `expiresIn` or `expiresAt`, not both. Tokens with both are an
`INVALID_SESSION` error. See [`Tokens`](https://session-kit.pages.dev/docs/reference/core#tokens) for
each field.

## Where the expiry comes from

When your tokens hold more than one of these, the client uses the first it
finds:

1. `expiresIn` or `expiresAt`.
2. A JWT access token's `exp` and `iat` claims, as a lifetime, when `exp` is
   later than `iat`.
3. A JWT access token's `exp` claim alone, as a time.

A JWT with `iat` works like `expiresIn`: the client counts the lifetime from
when it receives the token. So if your access token is a JWT with both
claims, you don't need to send an expiry at all.

## Fixed times and device clocks

`expiresAt` and a JWT's `exp` alone are fixed times, which the client
compares with the device's clock. Device clocks can be minutes off. A clock
that runs fast makes the token look already expired, and `signIn` rejects
it with `INVALID_SESSION`.

## Tokens without an expiry

When the client can't tell when the token expires, it uses the token until
your API rejects it. [`authFetch`](https://session-kit.pages.dev/docs/client/requests) then refreshes after
the 401. There's no early refresh, since there's nothing to count down to.

## Next steps

- [Refresh](https://session-kit.pages.dev/docs/configuration/refresh): see when the client refreshes, and
  what it does when a refresh fails.
- [Authenticated requests](https://session-kit.pages.dev/docs/client/requests): send the access token
  with each request, and refresh after a 401.
- [`Tokens` reference](https://session-kit.pages.dev/docs/reference/core#tokens): every field `signIn`
  and your refresh callback take.