# `Tipalti.Auth.TokenServer`
[🔗](https://github.com/iamkanishka/tipalti/blob/main/lib/tipalti/auth/token_server.ex#L1)

Caches an OAuth 2.0 client-credentials access token for the modern REST
API and refreshes it automatically shortly before it expires.

One server runs per distinct `client_id`, started lazily on first use and
supervised under `Tipalti.Auth.Supervisor`. You don't need to start these
yourself — `Tipalti.Client` calls `fetch_token/1` on every REST request,
which starts the server on demand if it isn't already running.

A 60 second safety buffer is subtracted from the token's reported
lifetime, so a token is proactively refreshed before it actually expires
rather than after a request fails with 401.

# `state`

```elixir
@type state() :: %{
  config: Tipalti.Config.t(),
  token: String.t() | nil,
  expires_at: integer() | nil
}
```

# `fetch`

```elixir
@spec fetch(Tipalti.Config.t()) :: {:ok, String.t()} | {:error, Exception.t()}
```

Returns a cached, valid access token for the given config, fetching or
refreshing it first if necessary. Starts the backing `TokenServer` for
this `client_id` if one isn't already running.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
