Setting headers in the local Angular development server

Viewed 1249

My application is a client side only app currently running on localhost. I am trying to use a Wasm library that requires access to SharedArrayBuffer. It is working on Chrome and Edge, however it seems Firefox has put restrictions in place resulting in an error: ReferenceError: SharedArrayBuffer is not defined

According to MDN Firefox requires the following headers to be set:

Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corp

My app is running on localhost:4200. I am trying to get the ng serve development server to set the headers. I have attempted to do this with the following code:

// proxy.conf.js
module.exports = {
  "/": {
    logLevel: "debug",
    target: "http://localhost:4200",
    bypass: (req, res, proxyOptions) => {
      res.setHeader("Cross-Origin-Opener-Policy", "same-origin");
      res.setHeader("Cross-Origin-Embedder-Policy", "require-corp");
    },
  },
};

However this does not work. Is there either a way to set the headers with the Angular server, or another workaround?

2 Answers

You can add the COEP and COOP headers to the Angular Dev-server in the angular.json to overcome this issue.

Eg.,

"serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "web-ui:build",
            "proxyConfig": "proxy.conf.json",
            "headers": {
              "Cross-Origin-Opener-Policy":"same-origin",
              "Cross-Origin-Embedder-Policy":"require-corp"
            }
           }
          }

This should get both the headers "Cross-Origin-Opener-Policy" and "Cross-Origin-Embedder-Policy" to appropriate values. Run ng serve to get these changes reflect in the response.

Was looking for a solution for this pretty long - thanks @Sasikumar for the hint!

Just wanted to add that the section in default new / my angular project looks little different:

    "serve": {
      "builder": "@angular-devkit/build-angular:dev-server",
      "configurations": {
        "production": {
          "browserTarget": "webapp:build:production"
        },
        "development": {
          "browserTarget": "webapp:build:development",
          "headers": {
            "X-Max-Test":"my-test-header",
            "Content-Security-Policy": "default-src 'self'; frame-ancestors 'self'; script-src 'self' 'unsafe-inline'; font-src 'self' https://fonts.gstatic.com/; style-src 'self' https://fonts.googleapis.com/ 'unsafe-inline'; img-src 'self' data:;"
          }
        }
      },
      "defaultConfiguration": "development"
Related