axios-jwt-simple
is a Node.js library that simplifies client-side JWT (JSON Web Token) authentication using Axios. It provides an easy-to-use interface for managing JWT tokens, attaching them to requests, and handling token expiration seamlessly. This library is particularly useful for applications that require secure communication with APIs using JWT-based authentication.
The peculiarity is that if you don't use automatic JWT management (jwtInit
method), it's simply axios with another name :-)
- Automatic Token Management: Automatically attaches JWT tokens to Axios requests.
- Token Refresh: Handles token expiration and refresh seamlessly.
- Customizable: Easily configure token storage and refresh logic.
- CommonJS and TypeScript Support: Works with both CommonJS and ES Modules, with full TypeScript type definitions.
axios-jwt-simple
is ideal for:
- Applications that use JWT for authentication and need to attach tokens to API requests.
- Projects requiring automatic token refresh when tokens expire.
- Developers looking for a lightweight and easy-to-integrate solution for managing JWTs with Axios.
You can install axios-jwt-simple
using your preferred package manager:
pnpm add axios-jwt-simple
npm install axios-jwt-simple
yarn add axios-jwt-simple
To use axios-jwt-simple
, you can simply use as it was axios
import ajs from 'axios-jwt-simple';
const url = 'https://mockhttp.org/get';
const response = await ajs.get(url);
but if you call jwtInit
it enter in Automatic token managed
import ajs from 'axios-jwt-simple';
const baseUrl = 'https://mockhttp.org/';
ajs.jwtInit(baseUrl)
If you just have an axios instance you can magically upgrade it to ATM with ajsAttach
method
import axios as 'axios';
const ajs = ajsAttach(axios);
ajs.jwtInit(baseUrl)
// or simply
ajsAttach(axios).jwtInit(baseUrl);
// and now axios have ATM inside
In ATM mode, ajs automatically manage jwt and refresh token.
If refresh token and access token don't exist or are invalid/expired, ajs make a POST to ajs.pathLogin
to get new access and refresh tokens.
If access token doesn't exist or is invalid/expired with a valid refresh token ajs make a GET to ajs.pathRefresh
to get new access token.
If a resource has called, ajs get a valid access token with the previous logic and then call the resource with the Autorization header with Bearer accessToken
.
.jwtInit: ( urlBase: string, onLoginRequest?: AjsOnRequest, onLoginResponse?: AjsOnResponse) => void;
where
-
urlBase
: The base URL for the API. -
onLoginRequest
: Optional custom handler for login requests to alter config request whenpathLogin
is called (seeonLoginRequest
method). -
onLoginResponse
: Optional custom handler for login responses to alter response whenpathLogin
respond (seeonLoginResponse
method)
This is a config callback inside the axios.interceptor.request.use
when login page has called.
It's used to inject auth data to login page.
As an example
ajs.jwtInit(baseUrl, (config: AjsRequestConfig) => {
config.data = {
username: 'user',
password: 'pass'
};
return config;
});
To parse access and refresh token, ajs expect that these are returned by POST pathLogin
in this form
{
"token": "...",
"refreshToken": "..."
}
If your login page return these information in a different way you can use this method to reformat infos.
As an example, if your tokens are returned as accessToken and renewToken these allow things to work
ajs.onLoginResponse = (response: AjsResponse) => {
response.data.token = response.data.accessToken;
response.data.refreshToken = response.data.renewToken
return response;
};
// or in jwtInit as
ajs.jwtInit(baseUrl, config => config, (response: AjsResponse) => {
response.data.token = response.data.accessToken;
response.data.refreshToken = response.data.renewToken
return response;
});
This is a config callback inside the axios.interceptor.request.use
when refresh page has called.
Usually don't use it because ajs automatically inject the Authorization Bearer with refreshToken when GET pathRefresh
has called
To parse access token, ajs expect that these are returned by GET pathRefresh
in this form
{
"token": "...",
}
If your refresh page return these information in a different way you can use this method to reformat infos.
As an example, if your tokens are returned in an X-ACCESS-TOKEN
header your onRefreshResponse must be something like this
ajs.onRefreshResponse = (response: AjsResponse) => {
response.data = { token: response.headers['X-ACCESS-TOKEN'] };
return response;
};
Url used to get a new access and refresh tokens via POST verb.
Url used to get a new access token via GET verb
Url used to invalidate server-side access and refresh tokens.
If you're using CommonJS, you can import the library as follows:
const ajs = require('axios-jwt-simple');
const baseUrl = 'https://mockhttp.org/';
ajs.jwtInit(baseUrl)
Both ATM and not-ATM mode ajs add an error interceptor that print detailed error informatio in error console
🟥 ERROR RESPONSE
URL: /status/404
Status: 404 - Not Found
Data: { status: 'Response with status code 404' }
Headers: Object [AxiosHeaders] {
date: 'Sat, 26 Apr 2025 19:20:30 GMT',
"content-type": 'application/json; charset=utf-8',
'content-length': '42',
connection: 'keep-alive',
...
In this case, a try...catch
handled an error structure (AjsErrorResponse
) with this signature
type AjsErrorResponse = {
error: boolean; // Indicates if an error occurred
messageError: string; // Optional error message
status: number; // HTTP status code
statusText: string; // HTTP status text
statusCode?: number; // Optional status code
message?: string; // Error message
};
axios-jwt-simple
is written in Typescript and so is fully typed and works seamlessly with TypeScript.
Yes, axios-jwt-simple
works with any JavaScript framework or library that uses Axios for HTTP requests.
- Report Bugs: GitHub Issues
- Feature Requests: GitHub Issues
- Help and Support: GitHub Discussions
- Contributing: Contributing Guidelines
We welcome contributions!