Angular 12 CSS optimization inline event handler with Content Security Policy

Alex Moss picture Alex Moss · May 17, 2021 · Viewed 7.3k times · Source

After upgrading to Angular 12 my Content Security Policy blocks styles from loading correctly.

The Angular 12 devkit seems to add a new inline event handler to the CSS bundle reference in index.html, example below.

<link rel="stylesheet" href="styles.5951e4ca367b697db091.css" crossorigin="anonymous" integrity="sha384-2031E8+oC87S0N7NzRGcF8fqx777KEJOgQ3KcUN4aX6xsR3BVaV5sh4fibR5joOc" media="print" onload="this.media='all'">

Error

Refused to execute inline event handler because it violates the following Content Security Policy directive...

This seems to be related to this RFC: https://github.com/angular/angular-cli/issues/18730 but I can't find any more information about how to use it with a strict (no 'unsafe-inline') CSP.

Answer

Michael Hubeny picture Michael Hubeny · May 18, 2021

I had the same problem after Angular 12 upgrade.

The solution for me was to set the workspace option optimization "inlineCritical" to false. The inlineCritical option was changed in Angular 12 to default true to improve First Contentful Paint, see https://angular.io/guide/workspace-config#styles-optimization-options

here is an example workspace configuration

"project": {
  "architect": {
    "build": {
      "configurations": {
        "production": {
          "optimization": {
            "scripts": true,
            "styles": {
              "minify": true,
              "inlineCritical": false
            },
            "fonts": true
          }
        }
      }
    }
  }
},