ReactJS - Refused to apply inline style because it violates the following Content Security Policy directive
Asked Answered
C

0

7

I get the following error in the browser inspector (Chrome, Brave, Safari) when I load my ReactJS project in Production:

Refused to apply inline style because it violates the following Content Security Policy directive: "style-src-elem 'self' https://fonts.googleapis.com". Either the 'unsafe-inline' keyword, a hash ('sha256-TMIFk5ZjGNpczjRE6YVaBrPXVNzANj9JRK+w2bh9TX8='), or a nonce ('nonce-...') is required to enable inline execution.

I used the below command to build the ReactJS project (it solves the inline script issue, but not the inline style):

INLINE_RUNTIME_CHUNK=false npm run build

This is the CSP policy part referring to the style:

Header set Content-Security-Policy "default-src 'self'; style-src 'self'; style-src-elem 'self' https://fonts.googleapis.com; ..."

I believe the problem happens during the build phase, when React generates chunk files (with names such as '2.3c013fe3.chunk.js') and embeds inline style within the code, although I don't use inline style anywhere in my source code. All styles are contained in fileX.module.css and imported in the tsx files, like this example:

Example.tsx

import styles from './Example.module.css';

const Example = () => (
    <div className={styles.container}>
        Hello world
    </div>
);

Example.module.css

.container {
    display: flex;
    flex-direction: column;
    align-items: center;
}

If the auto-generated chunk files are the problem, I don't see how to solve this issue with hash or nonce alternatives, since React will always generate these inline styles. On the other hand, I assume unsafe-inline is not an option, since this essentially makes the CSP useless.

Any suggestion either on the CSP directives or React settings to solve this issue? (I read all similar Q&A but none of them refers to this specific problem with React)

Cyclotron answered 9/9, 2020 at 7:50 Comment(4)
If you find any way to resolve this, i'll be interested to know how you did...Gibber
@Fieuxcédric Unfortunately I didn't get any reply on this and didn't manage to get it solved, so same error keeps showing in the inspector :/ Perhaps in future versions of React.js this might be addressed...Cyclotron
@SergiJuanati Did you find anything? I'm facing the same issue.Rheology
@Rheology sadly, it remains unanswered.Cyclotron

© 2022 - 2024 — McMap. All rights reserved.