---
url: https://haihv.github.io/valifetch/api/auth/functions/jwtRefresh.md
---

# Function: jwtRefresh()

> **jwtRefresh**(`opts`): [`BeforeRequestHook`](../../index/type-aliases/BeforeRequestHook.md)

Defined in: [src/auth.ts:150](https://github.com/haihv/valifetch/blob/285835d38a6676b98d2ee1a93e23166c6c834cb2/src/auth.ts#L150)

Returns a `beforeRequest` hook that proactively refreshes a JWT access token
when it is expired before attaching it as `Authorization: Bearer <token>`.

Concurrent requests that arrive while a refresh is already in flight are
queued — only **one** refresh call is made, and all waiting requests receive
the same new token once it resolves.

## Parameters

### opts

[`JwtRefreshOptions`](../type-aliases/JwtRefreshOptions.md)

Configuration for token retrieval, expiry check, and refresh.

## Returns

[`BeforeRequestHook`](../../index/type-aliases/BeforeRequestHook.md)

A `beforeRequest` hook that refreshes and attaches the token as needed.

## Example

```ts
import valifetch from 'valifetch';
import { jwtRefresh } from 'valifetch/auth';

const api = valifetch.create({
  hooks: {
    beforeRequest: [
      jwtRefresh({
        getToken: () => store.accessToken,
        isExpired: (token) => isJwtExpired(token),
        refresh: () => authApi.post('/refresh').then((r) => r.token),
        onRefreshed: (token) => store.setToken(token),
      }),
    ],
  },
});
```
