Hydrogen integration with third party tracking services

Hello,

Is there any way to integrate into Hydrogen tracking services like Google Analytics, Google Analytics 4, Facebook Pixel and use the Customer Privacy API ?

For Google Analytics, Google Analytics 4, Facebook Pixel etc:
You can implement custom scripts using the Script component https://shopify.dev/docs/api/hydrogen/2023-10/components/script.
Example of a cookie consent management tool “CookieYes”. But you can use any script you would like.

export default function App() {
...
return (

After adding the script you must make sure that the Content Security Policy is set to allow your scripts. You will notice if you get errors in the browser dev console.

Example of adding custom CSP:
entry.server.tsx

```javascript
export default async function handleRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
remixContext: EntryContext,
) {
const localDirectives =
process.env.NODE_ENV === 'development'
? ['localhost:*']
: [];
const {nonce, header, NonceProvider} = createContentSecurityPolicy({
defaultSrc: [
"'self'",
'cdn.shopify.com',
'shopify.com',
'*.youtube.com',
'*.google.com',
'fonts.gstatic.com',
'https://cdn-cookieyes.com',
'https://log.cookieyes.com',
...localDirectives,
],
imgSrc: [
"'self'",
'data:',
'cdn.shopify.com',
'https://cdn-cookieyes.com',
'https://log.cookieyes.com',
...localDirectives,
],
styleSrc: [
"'self'",
"'unsafe-inline'",
'fonts.googleapis.com',
'cdn.shopify.com',
'https://cdn-cookieyes.com',
'https://log.cookieyes.com',
...localDirectives,
],
connectSrc: [
"'self'",
'https://monorail-edge.shopifysvc.com',
'https://cdn-cookieyes.com',
'https://log.cookieyes.com',
...localDirectives,
],
});

More info on this: https://shopify.dev/docs/custom-storefronts/hydrogen/content-security-policy

Instead of using the Customer Privacy API as you have on the native Shopify solution I have another solution, to handle customer privacy:

  1. For user consent we recommend to use a tool like CookieYes or CookieBot. (implement as a Script in previous example)
  2. The tool of choice will block the cookies until accepted. (Just make sure to double check that it works and that the tool has scanned all possible cookies)
  3. To implement Shopify Cookies for analytics etc you can use the hook useShopifyCookies. https://shopify.dev/docs/api/hydrogen-react/2023-10/hooks/useshopifycookies
  4. For checking consent for the useShopifyCookies, you must first add a listener to wait for consent from the user. This is an example of implementation with CookieYes:
export default function App() {
const [consent, setConsent] = useState

This code is just for examples and you should adapt it to fit your requirements :slightly_smiling_face: 

Best of luck and feel free to reach out if you need help.
The team at [StablePeak](https://stablepeak.com)