react-axios-provider-kit
v0.1.1
Published
Configurable Axios Provider for React with JWT auth, refresh token, concurrency control, and pluggable storage
Maintainers
Readme
A production-ready Axios Provider for React.
This library provides a clean and configurable way to manage:
- API communication
- JWT authentication
- refresh token flows
- global error handling
- request retry logic
without coupling your networking layer to UI, routing, or i18n libraries.
✨ Features
- ✅ Centralized Axios configuration via React Context
- ✅ Automatic
Authorizationheader injection - ✅ Refresh token handling (single-flight, concurrency-safe)
- ✅ Prevents infinite refresh loops
- ✅ Pluggable token storage (session / local / memory)
- ✅ Optional typed API helper (
api.get/post/...) - ✅ SSR-safe (Next.js compatible)
- ✅ Zero dependency on routing or UI libraries
- ✅ Fully written in TypeScript
📦 Installation
npm install react-axios-provider-kitPeer Dependencies
{
"react": ">=19",
"axios": ">=1.4"
}🚀 Quick Start
import { AxiosProvider } from "react-axios-provider-kit";
export function App() {
return (
<AxiosProvider baseURL="https://api.example.com">
<YourApp />
</AxiosProvider>
);
}Use it anywhere in your app:
import { useAxios } from "react-axios-provider-kit";
const { client, api } = useAxios();
// raw axios
await client.get("/health");
// typed helper
const users = await api?.get<User[]>("/users");🔐 Authentication & Refresh Token
Example with JWT authentication and refresh logic:
import {
AxiosProvider,
createSessionStorageTokenStorage,
} from "react-axios-provider-kit";
import { toast } from "react-toastify";
import { useNavigate } from "react-router-dom";
const tokenStorage = createSessionStorageTokenStorage("access_token");
export function AppAxiosProvider({ children }: { children: React.ReactNode }) {
const navigate = useNavigate();
return (
<AxiosProvider
baseURL={import.meta.env.VITE_API_URL}
tokenStorage={tokenStorage}
onNotify={({ level, message }) => {
if (level === "warning") toast.warning(message);
if (level === "error") toast.error(message);
}}
onAuthFailure={() => {
tokenStorage.set(undefined);
toast.error("Session expired");
navigate("/login");
}}
isRefreshRequest={(config) =>
(config.url ?? "").includes("/auth/refresh")
}
refreshAccessToken={async ({ refreshClient, token }) => {
const res = await refreshClient.post("/auth/refresh", {
accessToken: token,
});
return { accessToken: res.data.accessToken };
}}
>
{children}
</AxiosProvider>
);
}⚙️ How Refresh Works
- An API request returns 401 Unauthorized
- A single refresh request is triggered
- All pending requests wait for the new token
- Original requests are retried automatically
- If refresh fails →
onAuthFailure()is called
This design avoids:
- ❌ multiple refresh calls
- ❌ race conditions
- ❌ infinite retry loops
🗄 Token Storage Options
Session Storage
createSessionStorageTokenStorage("jwt");Local Storage
createLocalStorageTokenStorage("jwt");Memory Storage (SSR-safe)
createMemoryTokenStorage();You can also provide a custom adapter:
const customStorage = {
get: () => myToken,
set: (token?: string) => { myToken = token; }
};🧩 API Helper (Optional)
The provider can expose a typed API helper that:
- unwraps
response.data - supports file uploads and blobs
- preserves error propagation
const { api } = useAxios();
const products = await api.get<Product[]>("/products");
await api.uploadFile("/upload", formData);Disable it if you only need the raw Axios client:
<AxiosProvider exposeApi={false} />🔕 Skipping Notifications Per Request
Disable global notifications for specific requests:
client.get("/silent-endpoint", {
_skipNotify: true,
});Useful for:
- background polling
- silent validations
- custom UI error handling
🧩 SSR / Next.js Notes
- No direct access to
windowordocument - Safe to use in Server-Side Rendering
- Memory storage recommended for SSR environments
⭐ Support the Project
If this library helped you, please consider giving it a ⭐ on GitHub.
Your support helps improve visibility and encourages continued development.
📄 License
© 2026 Mihai Musteata
