How can I configure a proxy between Partytown and Gatsby when deploying on Netlify?

907 Views Asked by At

I am trying to setup GTM with Partytown but I am getting a CORS error, does anyone know how to solve it?

Below is my gatsby-ssr.js file:

import React from "react";
import { Partytown } from "@builder.io/partytown/react";

const ORIGIN = "https://www.googletagmanager.com";
const GTM_ID = "XXXXXX";

export const onRenderBody = ({ setHeadComponents }) => {
  setHeadComponents([
    <Partytown key="partytown" forward={["gtm"]} />,
    <script key="google-tag-manager" type="text/partytown" src={`${ORIGIN}/gtm.js?id=${GTM_ID}`} />,
    <script
      key="google-tag-manager-config"
      type="text/partytown"
      dangerouslySetInnerHTML={{
        __html: `(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
        new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
        j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
        '${ORIGIN}/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
        })(window,document,'script','dataLayer','${GTM_ID}');`,
      }}
    />,
  ]);
};

My page is hosted on Netlify and I have also tried to create a reverse proxy on Netlify, like this:

[[redirects]]
  from = "/local-gtm/*"
  to = "https://www.googletagmanager.com/:splat"
  status = 200

And then I've changed my ORIGIN variable on the frontend to fetch the data from the proxy url but it still shows me CORS errors. Does anyone have a clue what could be wrong here?

1

There are 1 best solutions below

0
Caligulaaa On

Hi you need to manually override your _redirects file in your build folder (public by default)

/__third-party-proxy https://www.googletagmanager.com/gtag/js?id=YOURID_NO_ENV_VAR 200

That will get the service worker going, realtime still seems pretty innacurate vs a good old oem script implementation..

<3

This is when using the gatsby script tag sorry. Whatever link you need to proxy would need to be manually enterred in the _redirects file.

Best of luck!