Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feature]: Add Google Tag to all Pages #23

Open
6 tasks
jimbrig opened this issue Sep 30, 2024 · 0 comments
Open
6 tasks

[Feature]: Add Google Tag to all Pages #23

jimbrig opened this issue Sep 30, 2024 · 0 comments
Assignees
Labels
config Configuration Management feature New feature requests help wanted Extra attention is needed refactor Code refactoring and cleanup setup Setup & Initialization

Comments

@jimbrig
Copy link
Member

jimbrig commented Sep 30, 2024

Per email from Mitchell Flanders:

  • grant "edit" access for analytics8@crisp.co to Google Analytics

Initialize Google Analytics and Tag Manager

  • initialize a new google analytics account and property for bastienlaw.com
  • get the gtag.js script from setup
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-BQBBSBFGZG"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'G-BQBBSBFGZG');
</script>

From above the GA_TRACKING_ID is G-BQBBSBFGZG

Add Necessary Code to Repository

  • Add a app/.env.example and app/.env that is included in .gitignore with the tracking ID:
# app/.env

GA_TRACKING_ID="***"
  • Create a app/app/utils/gtags.client.ts utility typescript file:
// app/utils/gtags.client.ts
declare global {
    interface Window {
        gtag: (
            option: string,
            gaTrackingId: string,
            options: Record<string, unknown>,
        ) => void;
    }
}

/**
 * @example
 * https://developers.google.com/analytics/devguides/collection/gtagjs/pages
 */
export const pageview = (url: string, trackingId: string) => {
    if (!window.gtag) {
        console.warn(
            "window.gtag is not defined. This could mean your google analytics script has not loaded on the page yet.",
        );
        return;
    }
    window.gtag("config", trackingId, {
        page_path: url,
    });
};

/**
 * @example
 * https://developers.google.com/analytics/devguides/collection/gtagjs/events
 */
export const event = ({
    action,
    category,
    label,
    value,
}: Record<string, string>) => {
    if (!window.gtag) {
        console.warn(
            "window.gtag is not defined. This could mean your google analytics script has not loaded on the page yet.",
        );
        return;
    }
    window.gtag("event", action, {
        event_category: category,
        event_label: label,
        value: value,
    });
};
import { json } from "@remix-run/node";

import {
  Link,
  Links,
  Meta,
  MetaFunction,
  Outlet,
  Scripts,
  ScrollRestoration,
  useLoaderData,
  useLocation,
} from "@remix-run/react";

import { useEffect } from "react";

import "./styles/typography.css";
import './styles/global.css';

import ScrollToTopButton from "./components/ScrollToTopButton";
// import ChatbotScript from "./components/ChatBot";

import * as gtag from "./utils/gtags.client";

// Load the GA tracking id from the .env
export const loader = async () => {
  return json({ gaTrackingId: process.env.GA_TRACKING_ID });
};

export const meta: MetaFunction = () => {
  return [
    {title: "Bastien Law"},
    {name: "description", content: "Law Offices of Villard Bastien"},
  ];
};

export function Layout({ children }: { children: React.ReactNode }) {
  const location = useLocation();
  const { gaTrackingId } = useLoaderData<typeof loader>();

  useEffect(() => {
    if (gaTrackingId?.length) {
      gtag.pageview(location.pathname, gaTrackingId);
    }
  }, [location, gaTrackingId]);

  return (
    <html lang="en">
      <head>
        <meta charSet="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <Meta />
        <Links />
      </head>
      <body>
        {process.env.NODE_ENV === "development" || !gaTrackingId ? null : (
          <>
            <script
              async
              src={`https://www.googletagmanager.com/gtag/js?id=${gaTrackingId}`}
            />
            <script
              async
              id="gtag-init"
              dangerouslySetInnerHTML={{
                __html: `
                window.dataLayer = window.dataLayer || [];
                function gtag(){dataLayer.push(arguments);}
                gtag('js', new Date());

                gtag('config', '${gaTrackingId}', {
                  page_path: window.location.pathname,
                });
              `,
              }}
            />
          </>
        )}
        {[children, <ScrollToTopButton key={0} />]}
        <ScrollRestoration />
        <Scripts />
        {/* <ChatbotScript /> */}
      </body>
    </html>
  );
}

export default function App() {
  return <Outlet />;
}

export function HydrateFallback() {
  return <p>Loading...</p>;
}

Apply Google Tag where Necessary

  • Forms
  • Location Tracking
  • etc.
@jimbrig jimbrig self-assigned this Sep 30, 2024
@jimbrig jimbrig added config Configuration Management feature New feature requests help wanted Extra attention is needed refactor Code refactoring and cleanup setup Setup & Initialization labels Sep 30, 2024
@jimbrig jimbrig pinned this issue Sep 30, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
config Configuration Management feature New feature requests help wanted Extra attention is needed refactor Code refactoring and cleanup setup Setup & Initialization
Projects
None yet
Development

No branches or pull requests

1 participant