I've developed a React application using Create React App and implemented CSS modules for styling the components.
Each CSS file is prefixed with .module.css
. For example: ComponentName.module.css
To use the CSS file within a component, I import it like this:
import styles from "./css/ComponentName.module.css";
Then, I apply the styling using the className
attribute:
const welcomeText = (
<div className={styles["welcome-text"]}>
<h1 className={styles.title}>Welcome</h1>
</div>
);
However, when implementing Content Security Policy (CSP) and setting the style-src
directive to 'self'
, all the styling is blocked. To make it work, I also need to include 'unsafe inline'
.
Is there a way to declare the .module.css
files and their usage with className
as valid sources for the style-src
directive?
If not, what are other methods of styling React components that are compatible with style-src 'self'
without requiring 'unsafe-inline'
? Would styled components be a feasible solution?
Alternatively, would it be secure to use 'unsafe-inline'
for styling components with CSS Modules?
Your insights are appreciated!
I have searched Google for solutions on how to reconcile the use of CSS modules with CSP constraints, but haven't found any definitive answers.
EDIT: The CSP configuration I intend to use is as follows:
<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, upon loading the page, all CSS disappears and the following errors are logged 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 eliminate the errors and ensure the applied CSS functions, 'unsafe-inline'
must be included:
style-src 'self' https://fonts.googleapis.com 'unsafe-inline';"