Adds an authentication header to matching requests.
import { FetchClient } from '@fgrzl/fetch';
import { addAuthentication } from '@fgrzl/fetch/middleware/authentication';
const client = addAuthentication(new FetchClient(), {
tokenProvider: () => localStorage.getItem('auth-token') || '',
});By default, a token is sent as Authorization: Bearer <token>.
interface AuthenticationOptions {
tokenProvider: () => string | Promise<string>;
headerName?: string;
tokenType?: string;
skipPatterns?: (RegExp | string)[];
includePatterns?: (RegExp | string)[];
requireToken?: boolean;
}tokenProvider: returns the token.headerName: header to set. Default isAuthorization.tokenType: token prefix. Default isBearer.skipPatterns: paths that should not receive auth.includePatterns: when provided, only matching paths receive auth.requireToken: return a synthetic401response when no token is available.
const client = addAuthentication(new FetchClient(), {
tokenProvider: () => getApiKey(),
headerName: 'X-API-Key',
tokenType: 'ApiKey',
});const client = addAuthentication(new FetchClient(), {
tokenProvider: () => sessionStorage.getItem('token') || '',
requireToken: true,
});
const response = await client.get('/private');
if (!response.ok && response.status === 401) {
showLogin();
}