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)

Sergi Juanati
  • 1,230
  • 1
  • 9
  • 17

0 Answers0