I am having an issue with setting the Content Security Policy (CSP) for a React app. I am setting it with a meta tag in the head element of the index.html file.
<meta
http-equiv="Content-Security-Policy"
content="img-src 'self' https://via.placeholder.com/ data:"
/>
I want to load images from an external source and I have added the source origin to the meta tag but I have not been able to get the images to load in the application. I have tried a large number of variations for the format of the CSP, but I still have not been able to get the images to load. I am using a production build of the app that has been created with create-react-app and is being served by a Node server. Furthermore, I have set INLINE_RUNTIME_CHUNK=false in a .env file to make sure that no inline JavaScript is generated in the index.html file. The following error is generated when the application attempts to load the image.
Refused to load the image 'https://via.placeholder.com/150' because it violates the following Content Security Policy directive: "img-src 'self' data:".
It is my understanding that setting the img-src directive to the domain, in this case https://via.placeholder.com/, should allow loading of images from that domain. A * (wildcard) or https://* should allow images from all external domains or https-only domains, to be loaded into the application. However, it continues to show the same error message no matter what I put into the img-src directive. Additionally, I have added the ‘data:’ attribute with and without the wildcard (i.e. data:*) and have received the same error message. I have also tried to change the default-src directive to include the wildcard for all sources, as shown in the following code.
<meta
http-equiv="Content-Security-Policy"
content="default-src * 'unsafe-inline'; img-src * data:*"
/>
But, the error message will still not go away. I am fundamentally misunderstanding CSP? Or is there something else that I need to add in order to load images from external sources?