loading...

Using Axios Request Interceptor

mrayor profile image Adesanya Ayokunle ・1 min read

What is Axios Request Interceptor?

Axios Request Interceptor is a method in the promise-based HTTP client that allow you to run your code or modify the request before the actual call to the endpoint is made.

A simple use case is if you want to check whether certain credentials are valid before making a request, you can do this with a request interceptor. Or if you need to attach a token to every request made, instead of duplicating the token addition logic at every axios call, you can make an interceptor which attaches a token on every request that is made.

To demonstrate, I want to switch between two baseUrl depending on if it is available or not.

Base Code:

import constants from "constants";
import axios from "axios";

const { apiUrl } = constants;

export default axios.create({
  baseURL: apiUrl,
});

With request interceptors:

import constants from "constants";
import axios from "axios";

const { apiUrlOne, apiUrlTwo} = constants;

//create instance
const app = axios.create();

//check if endpoint is available
const isAvailable = async () => {
  const res = await fetch(apiUrlOne);
  if (res.ok) {
    return apiUrlOne;
  }
  return apiUrlTwo;
};

app.interceptors.request.use(
  async (config) => {
    const conf = config;
    const url = await isAvailable();

    //update the request baseURL
    conf.baseURL = url;

    //return the request configurations
    return conf;
  },
  (error) => Promise.reject(error)
);

This is just a demonstration on how to use the Axios request interceptor. Cool yeah!. Learn more at axios docs

Posted on by:

mrayor profile

Adesanya Ayokunle

@mrayor

Full stack Web/Mobile developer with experience in the MERN and LAMP stack. I also do some design.

Discussion

markdown guide
 

So close, you had a great start but a very quick ending! You should go into more detail about the implementation of the interceptor and what you can and can't do and why you'd use it.

 

Thanks Dylan for the feedback 👍🏾. I’ll definitely get better at writing. 😅

 

Very cool! Why did you need this functionality?

 

Yeah...worked on a side project where I needed to use a different endpoint if one was down for some reason.