axios-xtra
v0.1.1
Published
A powerful Axios wrapper with automatic token refresh, HttpOnly cookie support, and Next.js SSR compatibility.
Readme
Axios Xtra
A powerful Axios wrapper with built-in HttpOnly cookie support, automatic token refresh with concurrency handling, and Next.js SSR compatibility.
Features
- 🔄 Automatic Token Refresh: Handles 401/expired token errors automatically.
- 🤝 Concurrency Handling: Queue multiple requests while refreshing tokens to prevent redundant calls.
- 🍪 HttpOnly Cookie Support: Built-in support for credentials in browser and SSR environments.
- 🚀 Next.js SSR Ready: Easy cookie synchronization for Server Components and
getServerSideProps. - 📦 Unwrap Response: Option to directly return
res.datafor cleaner code. - 🔁 Retry Mechanism: Automatic retry for network errors.
Installation
# axios-xtra 需要与 axios 一起使用 (peerDependency)
npm install axios-xtra axios
# or
yarn add axios-xtra axiosQuick Start
import { createAxiosPlus } from 'axios-xtra';
export const api = createAxiosPlus({
baseURL: 'https://api.example.com',
refreshUrl: '/auth/refresh',
accessExpirationCode: 401,
unwrapResponse: true,
});
// Use it like regular axios
const user = await api.get('/user/profile');API Reference
createAxiosPlus(config)
Creates an enhanced Axios instance.
| Parameter | Type | Default | Description |
| :--- | :--- | :--- | :--- |
| baseURL | string | - | The base URL for all requests. |
| refreshUrl | string | - | The endpoint URL to call when a token needs to be refreshed. |
| accessExpirationCode | number \| string | 401 | The error code that triggers a token refresh. |
| getErrorCode | (res) => code | - | Optional. A function to extract a custom error code from the response body if your API returns 200 OK with an error code in the body. |
| unwrapResponse | boolean | false | If true, the promise will resolve with response.data instead of the full Axios response object. |
| retryCount | number | 0 | Number of times to retry a failed request (for transient network errors). |
| retryDelay | number | 1000 | Delay between retries in milliseconds. |
| timeout | number | 10000 | Request timeout in milliseconds. |
| onBeforeRefresh | () => void | - | Callback function executed just before the refresh request starts. |
| onRefreshFailed | (error) => void | - | Callback function executed if the token refresh fails (e.g., to redirect to login). |
| onLoadingChange | (loading) => void | - | Callback triggered whenever the global loading state changes (useful for progress bars). |
| onError | (error) => void | - | A global error handler for all requests. |
| debug | boolean | false | Enables detailed console logging for requests and responses. |
| cookie | string | - | (Request level) Manually pass a cookie string. Highly useful for Next.js SSR cookie forwarding. |
Detailed Usage
For more advanced scenarios like Next.js SSR or custom error handling, please refer to the Usage Guide.
License
MIT
