Skip to content

Function: jwtRefresh() ​

jwtRefresh(opts): BeforeRequestHook

Defined in: src/auth.ts:150

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

Configuration for token retrieval, expiry check, and refresh.

Returns ​

BeforeRequestHook

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),
      }),
    ],
  },
});

Released under the MIT License. Built with Claude Code.