tip minersTip Miners

How to add google analytics to a Remix Run Web App

adding google analytics script  or GTM on your Remix JS app is a matter of adding it with JSX in a  dangerouslySetInnerHTML attributeWritten by Miguel

You have to remember that Remix is after all a React Framework and it uses JSX , hence, you need to make use of dangerouslySetInnerHTML

Steps

Open your entry point, generally is app/root.tsx and add to default export return the script provided by Google to install Analytics or Google Tag Manager It should be inside of <head> tag

Move the content of the data layer setup script to dangerouslySetInnerHTML .

You will go from:

<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', 'G-XXXXXXXX');
</script>

to

<script 
dangerouslySetInnerHTML={{__html:`
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', 'G-XXXXXXXX');
`}}></script>

Check on your development environment to see if its all good and then deploy

Add these scripts after <Meta /> and <Links /> ; the download of your CSS assets has more priority for the First Contentful Paint(FCP), unless you use Google Tag Manager to make changes to your site ( not very likely since you are using Remix JS )

More articles of Web Development

Idiomatic Application

And .. What is an idiomatic application?

Headless Worpress with Remix JS on Cloudflare

WordPress Headless CMS with Remix JS for Free

change remix app to be deployed to Cloudflare workers

Change deploy target to Cloudflare workers on Remix