Search code examples
cssreactjscontent-security-policycss-modules

CSS Modules styling is blocked by CSP wihout unsafe-inline for style-src directive


I have a React app created with CRA and I'm using CSS modules to style the components.

I create CSS files with the .module.css prefix. Example: ComponentName.module.css

Afterwards I import the CSS file inside the component I want to use it like so:

import styles from "./css/ComponentName.module.css";

Finally I apply the styling using the className attribute:

const welcomeText = (
    <div className={styles["welcome-text"]}>
        <h1 className={styles.title}>Welcome</h1>
    </div>
);

However, by using CSP and setting the style-src directive to 'self' all the styling is blocked. I have to also add 'unsafe inline' for it to work.

Is there a way to define the .module.css files and their usage with className as valid sources for the style-src directive? If not, what other ways of styling React components are there that are also compatible with style-src 'self' without needing 'unsafe-inline'? Would styled components work?

Or would it be safe to use unsafe-inline to style components with CSS Modules?

Thank you!

I have tried looking for answers on Google on how to make compatible the usage of CSS modules with CSP but I haven't found any.

EDIT: The CSP config I want to use is this

<meta http-equiv="Content-Security-Policy"
      content="default-src 'self' http://localhost:8090
img-src data: https: http:;
script-src 'self';
font-src 'self' https://fonts.gstatic.com;
style-src 'self' https://fonts.googleapis.com;"/>

However, when loading the page, all the CSS is gone and console logs these errors multiple times:

 Content Security Policy: The page’s settings blocked the loading of a resource at inline (“style-src”). styleTagTransform.js:12
 Content Security Policy: The page’s settings blocked the loading of a resource at inline (“style-src”). insertBySelector.js:36

To get rid of the errors and have the applied CSS work, the unsafe-inline has to be added:

 style-src 'self' https://fonts.googleapis.com 'unsafe-inline';"

Solution

  • Even though you don't have inline styles in your html code you have javascript files injecting styles inline. Rather have the javascript code modify css selectors and move the css code itself to a css file.