Handling Google Analytics CSP Errors in Magento: Temporary Fix via Custom Module

If you’ve encountered the Google Analytics CSP error on Magento, specifically related to https://region1.analytics.google.com, you’re not alone. The error typically looks like this in your browser’s console:

Refused to load the script 'https://region1.analytics.google.com/...' because it violates the following Content Security Policy directive: "script-src 'self'".

Google advises to update the hosts src here

EU data is collected in the EU
Google Analytics 4 collects all data from EU-based devices (based on IP-geo lookup) through domains and on servers based in the EU before forwarding traffic to Analytics servers for processing.

If you currently use a Content Security Policy (CSP), update your configurations (img-src and connection-src directives) to allow the following domains used by Analytics:

*.google-analytics.com
*.analytics.google.com

To address this issue, I’ve submitted a pull request to the Magento repository (PR #38991). However, while we wait for this PR to be reviewed and merged, there’s a way to temporarily fix the issue using a custom module.

Steps to Fix the CSP Error with a Custom Module

  1. csp_whitelist.xml

    In the etc directory, create a csp_whitelist.xml file to add the necessary CSP whitelisting:

<?xml version="1.0" encoding="UTF-8"?>  
<csp_whitelist xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Csp:etc/csp_whitelist.xsd">  
 <policies> <policy id="script-src">  
 <values> <value id="google_analytics" type="host">*.google-analytics.com</value>  
 <value id="google_analytics_4" type="host">*.analytics.google.com</value>  
 </values> </policy> <policy id="connect-src">  
 <values> <value id="google_analytics" type="host">*.google-analytics.com</value>  
 <value id="google_analytics_4" type="host">*.analytics.google.com</value>  
 </values> </policy> <policy id="img-src">  
 <values> <value id="google_analytics" type="host">*.google-analytics.com</value>  
 <value id="google_analytics_4" type="host">*.analytics.google.com</value>  
 </values> </policy> </policies></csp_whitelist>
  1. Flush the cache

Conclusion

By following these steps, you can create a custom module that temporarily addresses the CSP issue with Google Analytics on Magento until the official fix is merged (hopefully). This approach ensures that your site remains secure while adhering to the necessary Content Security Policies.

For any updates or further changes, keep an eye on the progress of the pull request. If you have any questions or run into issues, feel free to reach out to!