Axios Token Interceptor
An interceptor which makes it easier to work with tokens in axios.
Usage
const tokenProvider = ; const instance = axios; // Configure the provider with the necessary options.const options = ... ;instanceinterceptorsrequest; // When a call to an endpoint is made, a token will be provided as a header.instance
Providing a token
There are different ways to provide a token. You can provide the token as a static value:
instanceinterceptorsrequest; // This will send the "Authorization: Bearer abc" header when making the call to the API endpoint.instance
Instead of providing a static value you can also use a method to get the token:
instanceinterceptorsrequest; // This will send the "Authorization: Bearer ..." header when making the call to the API endpoint.instance
And this method can also return a promise:
instanceinterceptorsrequest; // This will send the "Authorization: Bearer ..." header when making the call to the API endpoint.instance
Customizing the Header
The following options allow you to set the header and the header value:
instanceinterceptorsrequest; // This will send the "X-Api-Key: token/abc" header when making the call to the API endpoint.instance
Caching
In cases where getting a token is an expensive operation (eg: exchanging a refresh token for an access token) you'll want to cache this work for as long as the token is valid.
The following example shows how we can cache tokens for 8 hours:
const cache = tokenProvider; instanceinterceptorsrequest;
Now it could also be that the token itself contains the expiration time (this is typically expires_in
you'll get from your Authorization Server). In that case you can also use this to configure the maximum age of the cache:
const cache = tokenProvider; instanceinterceptorsrequest;
And the cache can also be reset:
const cache = tokenProvider; cache;
Note that
expires_in
coming from your authorization server is expressed in seconds, so you'll need to convert it to milliseconds when returning it to thegetMaxAge
function.