Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular: add custom HTTP response headers to dev `ng serve`

Is it possible to add a custom HTTP response header to the development server that runs with ng serve? I'd like to add this custom header specially in the response of the main html file request, although it'd fine if it was added for every resource (js files, etc.).

I found these two recent Angular issues:

  • https://github.com/angular/angular-cli/issues/15095
  • https://github.com/angular/angular-cli/issues/15729

But it's still unclear to me if it's even possible to do it, and if it's possible how to accomplish it.

I have added a proxy.config.js file (referenced from angular.json, section projects -> my-app -> architect -> serve -> options -> proxyConfig) and tried several configs, like the following one, with no luck:

module.exports = {
    "/": {
        'headers': {
            'X-Custom-Foo': 'bar'
        },
        onProxyRes: (proxyRes, req, res) => {
            proxyRes.headers['x-added'] = 'foobar';
        }
    },
    'headers': {
        'X-Custom-Foo': 'bar'
    },
    onProxyRes: (proxyRes, req, res) => {
        proxyRes.headers['x-added'] = 'foobar';
    }
};

Is it possible to do so without having to use a third-party server?

like image 343
acalvo Avatar asked Mar 04 '23 01:03

acalvo


1 Answers

Assuming you're trying to simulate the production environment setting the same response header values: you could use bypass in the proxy configuration instead of onProxyRes. You are not trying to redirect the calls to another server (target value) and handle the answer in onProxyRes, so avoid using it and try with bypass. It should work fine ;)

The proxy.conf.js would look something like this:

module.exports = {
  "/": {
    "secure": false,
    "bypass": (req, res, proxyOptions) => {
      res.setHeader('X-Header-Test', 'bacon');
    }
  }
};
like image 55
noga Avatar answered Mar 05 '23 15:03

noga