The issue:
When I try to remove unsafe-inline source for script-src CSP my Angular webapp does not work anymore.
What is the root cause of this issue ?
When using SCSS in Angular@12+, Angular add a property onload on the index.html
<link rel="stylesheet" href="styles.672c1ac3d6da8cc311a2.css" media="print" onload="this.media='all'">
This results in a violation of the CSP unsafe-inline source for script-src header.
How to fix this issue and remove this "security breach" on my Angular web app ?
The solution:
Adding
"inlineCritical": falseto theangular.jsonsolved the issue because it disable Critical CSS inlining.Why Angular does that?
When the browser renders a page, it has to wait for the CSS resources to be downloaded and parsed. It can give the (false) impression that the loading of your application is slow, and impacts the First Contentful Paint (FCP) time.
A common technique to avoid that is to inline the CSS directly in the HTML, to avoid an extra request (this is what Lighthouse recommends). But you don’t want to inline all your CSS, otherwise the time to download the HTML increases. You just want to inline critical CSS resources, the ones that blocks the rendering, and that your user will see (you can defer the rest of CSS).
The Angular CLI introduces a new option in v11.1 to help us with this:
inlineCSSThe CLI will then usecrittersunder the hood to extract the critical CSS of your application, and inline them directly in the HTML. Runningng build --prodwith the above configuration produces anindex.htmlfile with a style element containing the critical CSS extracted, and the usualstyles.xxxxx.cssis loaded asynchronously using:<link rel="stylesheet" href="styles.3d6bb69e3d075769b349.css" media="print" onload="this.media='all'">For more informations about the unsafe-inline CSP keyword: https://content-security-policy.com/unsafe-inline/