Search code examples
expressaxiosinterceptor

Axios interceptor use express req object


I have an express route in which I send a header from the front end, in this route I'm making a GET request using axios. I created an interceptor with axios, but I would like to be able to read the req object from the activated route in order to add the header to the axios GET call.

// Example Interceptor
axios.interceptors.request.use(
  config => {
    // How to get req.headers from the route here?
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// Exemple GET route
router.get('/get', async (req, res, next) => {
  try {
    const { data } = await axios.get('https://kjhf.fsadjhfewq.....');
  } catch (error) {
    console.log(error)
  }

  res.status(200).json({});
});

Is it possible to do this?


Solution

  • So I think the way to do this is to use a middleware to set the headers, and pass on the axios instance

    // apiSetHeader.js middleware
    exports.default = (req, res, next) => {
      req.CustomAxios = axios.create({
        headers: { 'HeaderForTheApi': req.headers.apiHeader'}
      })
      next()
    }
    
    

    And then use that in your route

    // Exemple GET route
    router.get('/get', apiSetHeaderMiddleware, async (req, res, next) => {
      try {
        const { data } = await req.CustomAxios.get('https://kjhf.fsadjhfewq.....');
      } catch (error) {
        console.log(error)
      }
      res.status(200).json({});
    });
    

    Hope this helps!