How to set custom headers on Express and receive it on axios

I am trying to set a custom header on every response my Express api sends, so I wrote a simple middleware:

app.use((request, response, next) => {
  response.setHeader("custom-header", "value");
  next();
});

But when I inspect the headers received on my ReactJS application using axios interceptor, it simply doesn't appear. Here is my interceptor:

import axios from "axios";

const api = axios.create({
  baseURL: "http://localhost:3333"
});

api.interceptors.response.use(
  response => {
    console.log(response.headers);
    return response;
  },
  error => {
    console.log(error)
    return Promise.reject(error);
  }
);

export default api;

Just in case it may be relevant, my express app also uses cors, helmet and express.json middlewares, but I already tryied removing them and still I wasn't able to receive the header on the client.

What would be the appropriate way to set and receive a custom header on every request?

Upvotes: 1

Views: 1833

Answers (1)

So ironically a few minutes after posting the question I finally found the solution (which I was looking for for hours):

Turns out it is necessary to configure Access-Control-Expose-Headers on the cors middleware configuration, like this:

app.use(
  cors({
    exposedHeaders: ["custom-header"]
  })
);

Upvotes: 3

Related Questions