angularangular-cli

How to add a custom header in ng serve proxy (Angular 18+)


I am trying to add a custom header to a proxy request when using ng serve in my Angular 18 app. I've tried the following configurations:

// proxy.config.js
const proxyConfig = {
  "/api/v1": {
    target: "http://localhost:3000",
    secure: false,
    changeOrigin: true,
    onProxyReq: (proxyReq) => {
      proxyReq.setHeader("X-foo", "bar");
    },
  },
};
module.exports = proxyConfig;

And this alternative syntax:

// proxy.config.js
const proxyConfig = {
  "/api/v1": {
    target: "http://localhost:3000",
    secure: false,
    changeOrigin: true,
    on: {
      proxyReq: (proxyReq) => {
        proxyReq.setHeader("X-foo", "bar");
      },
    },
  },
};
module.exports = proxyConfig;

Neither of these work. The custom X-foo header is not added to the request and I don't see any errors in the console.

What am I doing wrong?


Solution

  • In Angular 18 or later, you have to use a different syntax:

    // proxy.config.js
    const proxyConfig = {
      "/api/v1": {
        target: "http://localhost:3000",
        secure: false,
        changeOrigin: true,
        configure(proxy) {
          proxy.on("proxyReq", (proxyReq) => {
            proxyReq.setHeader("X-foo", "bar");
          });
        },
      },
    };
    module.exports = proxyConfig;