Package Exports
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (axios-dynamic-client) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
axios-http-client-utility
A flexible and type-safe HTTP client wrapper built on top of Axios with integrated token management, error handling, and request/response interceptors.
Table of Contents
- Features
- Installation
- Quick Start
- API Reference
- Usage Examples
- Error Handling
- TypeScript Support
- Contributing
- License
- Keywords
Features
- Authentication-ready: automatic token injection through a customizable
getToken
- Built-in 401 handling via an
unauthorizedHandler
callback - Flexible configuration for custom headers, base URLs, and per-request overrides
- Environment-aware: falls back to
API_BASE_URL
whenbaseURL
is omitted - Written in TypeScript with complete type definitions
- Minimal dependencies (Axios is the only peer dependency)
Installation
npm install axios-http-client-utility axios
or yarn add axios-http-client-utility axios
or pnpm add axios-http-client-utility axios
text
axios
is required as a peer dependency.
Quick Start
import { createHttpClient } from 'axios-http-client-utility';
const api = createHttpClient({ baseURL: 'https://api.example.com' });
const users = await api.get('/users'); const newUser = await api.post('/users', { name: 'Jane' });
API Reference
Option | Type | Description | Default |
---|---|---|---|
baseURL |
string |
Base URL for all requests | process.env.API_BASE_URL |
getToken |
() => string | null |
Function that returns the auth token | undefined |
unauthorizedHandler |
() => void |
Callback executed on 401 Unauthorized responses | undefined |
additionalHeaders |
Record<string, string> |
Extra headers added to every request | {} |
FunctioncreateHttpClient(options?: HttpClientOptions) → AxiosInstance
Throws an error if no base URL is available through options.baseURL
or API_BASE_URL
.
Usage Examples
React Application
import { createHttpClient } from 'axios-http-client-utility'; import { useAuth } from './auth-context';
export const useApi = () => { const { token, logout } = useAuth();
return createHttpClient({ baseURL: process.env.REACT_APP_API_BASE_URL, getToken: () => token, unauthorizedHandler: logout, additionalHeaders: { 'X-Client-Version': '1.0.0' } }); };
Node.js Service
import { createHttpClient } from 'axios-http-client-utility';
const externalApi = createHttpClient({ baseURL: 'https://external.example.com/v1', getToken: () => process.env.API_KEY, additionalHeaders: { 'User-Agent': 'MyService/1.0' } });
export async function fetchData(id: string) { const res = await externalApi.get(/data/${id}); return res.data; }
Token Refresh Workflow
const auth = createHttpClient({ baseURL: 'https://auth.example.com' });
const api = createHttpClient({ baseURL: 'https://api.example.com', getToken: () => localStorage.getItem('accessToken'), unauthorizedHandler: async () => { const rt = localStorage.getItem('refreshToken'); if (!rt) return redirectToLogin();
try { const { data } = await auth.post('/auth/refresh', { refreshToken: rt }); localStorage.setItem('accessToken', data.accessToken); localStorage.setItem('refreshToken', data.refreshToken); location.reload(); } catch { localStorage.clear(); redirectToLogin(); } } });
Error Handling
Automatic 401 Handling
Provide an unauthorizedHandler
when creating the client:
createHttpClient({
baseURL: '...',
unauthorizedHandler: () => {
console.log('Session expired');
redirectToLogin();
}
});
Manual Error Checks
try { const res = await api.get('/resource'); return res.data; } catch (err: any) { if (err.response?.status === 404) throw new Error('Not found'); if (err.response?.status === 500) throw new Error('Server error'); throw err; }
TypeScript Support
import { createHttpClient, HttpClientOptions } from 'axios-http-client-utility'; import { AxiosResponse } from 'axios';
interface User { id: string; name: string; }
const api = createHttpClient({ baseURL: '...' });
const res: AxiosResponse<User[]> = await api.get('/users'); const users = res.data;
License
MIT © Sailaza Prasad
Keywords: axios, http client, typescript, authentication, interceptors, error handling, token management, api client, rest client Related