DEV Community

Adesanya Ayokunle
Adesanya Ayokunle

Posted on

Using Axios Request Interceptor

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

Top comments (4)

Collapse
 
dylajwright profile image
Dylan

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.

Collapse
 
mrayor profile image
Adesanya Ayokunle • Edited

Thanks Dylan for the feedback πŸ‘πŸΎ. I’ll definitely get better at writing. πŸ˜…

Collapse
 
johnlewissims profile image
John Lewis Sims

Very cool! Why did you need this functionality?

Collapse
 
mrayor profile image
Adesanya Ayokunle

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