Axios OAuth Client
axios-oauth-client is a utility library designed to simplify the implementation of various OAuth 2.0 grant types when using the Axios HTTP client. Currently at version 2.2.0, it provides dedicated functions for common flows such as Authorization Code, Owner Credentials (Resource Owner Password Credentials), Client Credentials, and Refresh Token grants. The library integrates directly with Axios, allowing developers to instantiate OAuth client functions with an Axios instance, a token endpoint URL, and client credentials. It streamlines the process of obtaining access tokens by handling the underlying HTTP requests and OAuth 2.0 specific parameter encoding. A key differentiator is its straightforward, function-based API specifically tailored for Axios users, focusing on providing the primitives for token acquisition rather than a comprehensive OAuth client state management system. This means users are responsible for token storage, renewal logic, and attaching tokens to subsequent requests. It's built for Node.js environments (engines >= 14) and ships with TypeScript types, ensuring type safety for its users.
Common errors
-
Cannot find module 'axios'
cause The peer dependency 'axios' is not installed or not resolvable by the module system.fixInstall axios: `npm install axios` or `yarn add axios`. -
TypeError: axios.create is not a function
cause An incompatible or incorrect version of Axios is installed, or Axios was not imported correctly.fixEnsure you have a compatible version of Axios (e.g., `^1.2.1`) and that you are importing `axios` as a default import: `import axios from 'axios'`. -
Request failed with status code 400 (or other HTTP error) when calling an OAuth grant function.
cause Incorrect OAuth client ID, client secret, token endpoint URL, grant type parameters (e.g., authorization code), or scopes were provided to the OAuth server.fixVerify all OAuth client credentials, endpoint URLs, and grant-specific parameters (like the authorization code or refresh token) are correct and match the configuration on your OAuth provider. Check the response body for specific error details from the OAuth server.
Warnings
- gotcha This library requires 'axios' as a peer dependency. It must be installed separately alongside 'axios-oauth-client' and meet the specified version range (e.g., '^1.2.1').
- gotcha axios-oauth-client provides functions for acquiring tokens but does not handle token storage, automatic refreshing before expiry, or attaching tokens to subsequent requests. Users must implement their own token management logic.
- gotcha The library directly exposes functions for different OAuth 2.0 grant types. There is no unified client instance that manages state across different grant types or automatically uses a refresh token if available from a previous grant.
Install
-
npm install axios-oauth-client -
yarn add axios-oauth-client -
pnpm add axios-oauth-client
Imports
- authorizationCode
const { authorizationCode } = require('axios-oauth-client')import { authorizationCode } from 'axios-oauth-client' - clientCredentials
import clientCredentials from 'axios-oauth-client'
import { clientCredentials } from 'axios-oauth-client' - refreshToken
const refreshToken = require('axios-oauth-client').refreshTokenimport { refreshToken } from 'axios-oauth-client'
Quickstart
import axios from 'axios';
import { clientCredentials, refreshToken } from 'axios-oauth-client';
const tokenEndpoint = 'https://oauth.com/2.0/token';
const clientId = process.env.OAUTH_CLIENT_ID ?? 'YOUR_CLIENT_ID';
const clientSecret = process.env.OAUTH_CLIENT_SECRET ?? 'YOUR_CLIENT_SECRET';
async function authenticateAndRefresh() {
const axiosInstance = axios.create();
// Client Credentials Grant
console.log('Attempting Client Credentials grant...');
const getClientCredentials = clientCredentials(
axiosInstance,
tokenEndpoint,
clientId,
clientSecret
);
const initialAuth = await getClientCredentials('read write');
console.log('Initial access token acquired:', initialAuth.access_token);
// Simulate refreshing the token
if (initialAuth.refresh_token) {
console.log('Attempting Refresh Token grant...');
const getRefreshToken = refreshToken(
axiosInstance,
tokenEndpoint,
clientId,
clientSecret
);
const refreshedAuth = await getRefreshToken(initialAuth.refresh_token, 'read write');
console.log('Refreshed access token acquired:', refreshedAuth.access_token);
} else {
console.log('No refresh token available from client credentials grant. Skipping refresh example.');
}
}
authenticateAndRefresh().catch(error => {
console.error('Authentication error:', error.response?.data || error.message);
});