Issue Implementing GTM with CSP #2525
Replies: 3 comments 2 replies
-
Hey Shaquille, The Hydrogen repo has one example of how to implement GTM here: There is one issue with jsonLd/meta and it's probably best to useLoadScript but curious if this works for you. |
Beta Was this translation helpful? Give feedback.
-
I have the exact same issue on my store and I fixed it following this SOF answer.
Here is how it looks on our code: // in entry.server.tsx
const {nonce, header, NonceProvider} = createContentSecurityPolicy({
scriptSrc: [
"'strict-dynamic'",
'https://cdn.shopify.com',
'https://*.googletagmanager.com',
// other third party scripts loaded within GTM tags
...
],
objectSrc: ["'none'"],
...
}); Hope this helps others who encountered the same issue! |
Beta Was this translation helpful? Give feedback.
-
Having the same problem as the original poster shaquille. The problem they originally mentioned was that rendering GTM on the server causes hydration issues -- this is my same issue too. Including the GTM Script using dangerously set inner html cause a hydration error that occurs, because the GTM script uses new Date() to get a start time, and there's a mismatch client and server side. The official Hydrogen GTM implementation above does not address this -- following it will get you the hydration error. |
Beta Was this translation helpful? Give feedback.
-
Hello everyone,
I'm having trouble implementing Google Tag Manager (GTM) with a Content Security Policy (CSP). Rendering GTM on the server causes hydration errors, so I run the script after hydration. However, since nonce should be included in the HTML response, the scripts that run only after hydration won't be having the nonce value. Consequently, we're facing an issue where an inline script is being blocked by CSP:
Since inline scripts are not allowed with CSP, I converted the GTM script into a function and executed it after hydration to avoid using inline scripts. This solved the first inline script issue I encountered. However, after the GTM script function was executed, another inline script CSP issue arose from the script
https://www.googletagmanager.com/gtm.js
that was appended by the GTM script and I think it is a bit out of control.Since GTM is crucial for every store, I am considering removing CSP, similar to the previous setup of Hydrogen Demo Store on older version. However, I would like to know if the Hydrogen team or anyone has a solution for this problem.
By the way, here's my code:
Thank you in advance!
Beta Was this translation helpful? Give feedback.
All reactions