GA Demos & Tools

repository·main·Indexed 23 days ago

https://github.com/googleanalytics/ga-dev-tools

A showcase of demonstrations and tools built using Google Analytics APIs and libraries. This repository serves as a practical reference for developers, featuring implementations for GA4 metadata retrieval via the useDimensionsAndMetrics hook, Campaign URL Builders, and Enhanced Ecommerce state management using StoreProvider and StoreContext. Built with Gatsby and Material UI, it includes a suite of specialized components and deployment guides for local development and production functions.

Tokens
11.1K
Snippets
25
Records
60
Agent score
82%

What's inside ga-dev-tools

  1. Understand the project structure and Gatsby configuration

    main

    The project is built using Gatsby and contains the following key files:

    • ./src: Contains the majority of the client-side code and all demo implementations.
    • ./gatsby-browser.js: Used to decorate the app at runtime. It utilizes Gatsby browser APIs like wrapRootElement (for injecting Material-UI Theme providers and Redux stores) and onInitialClientRender (to configure gapi, the Google API JavaScript client).
    • gatsby-config.js: The main configuration file for Gatsby plugins, including gatsby-plugin-prefetch-google-fonts, gatsby-plugin-react-svg, gatsby-plugin-typescript, and gatsby-source-filesystem.
  2. Deploy functions to production

    main

    To deploy the functions to production, follow these steps from the repository root:

    1. Validate configuration: Run yarn check-config --all from the top-level directory to ensure all required values are set correctly. The project uses functions.config() to access these values.
    2. Navigate to the functions directory: cd functions.
    3. Set Node.js version: Use nvm use 12 to match the version specified in the engines section of package.json.
    4. Install dependencies: Run npm install.
    5. Deploy: Run npm run deploy.
    # From the top-level
    yarn check-config --all
    
    # Inside ./functions
    nvm use 12
    npm install
    npm run deploy
  3. Install and run the GA Demos & Tools site locally

    main

    To develop or run the GA Demos & Tools site locally, you must use Yarn. The setup requires installing dependencies for both the root project and the lib directory.

    1. Install root dependencies:
      yarn
    2. Install dependencies in the lib directory:
      cd lib
      yarn
      cd ..
    3. Start the production app:
      yarn start:app:production

    During the startup process, you will be prompted with several questions. You can skip them, but demos requiring authentication will need a valid Google client ID to function. Once started, the app is available at http://localhost:5000.

    yarn
    cd lib
    yarn
    cd ..
    yarn start:app:production
  4. Manage request states with the Requestable type

    main

    The Requestable type is a discriminated union used to represent the lifecycle of an asynchronous request. It tracks the state using the RequestStatus enum and allows you to associate specific data types with each state: Successful, NotStarted, InProgress, and Failed.

    To extract the data associated with a specific state, use the provided utility functions successful, notStarted, inProgress, or failed. These functions return the data if the status matches, or undefined otherwise.

  5. Understand the validation states of useValidateEvent

    main

    The useValidateEvent hook implements a state machine using the RequestStatus type. The returned object shape changes based on the current status:

    StatusReturned Object PropertiesDescription
    NotStartedvalidateEventThe initial state. Waiting for user to trigger validation.
    InProgress(none)Validation is currently communicating with the GA API.
    Successfulsent, sendToGA, copyPayload, copySharableLinkThe payload passed all checks. sent tracks if sendToGA was called.
    FailedvalidationMessages, validateEvent, payloadErrorsValidation failed. validationMessages contains specific GA4 errors.

    Type Definitions

    export type ValidationSuccessful = {
      sent: boolean
      sendToGA: () => void
      copyPayload: () => void
      copySharableLink: () => void
    }
    
    export type ValidationNotStarted = { validateEvent: () => void }
    
    export type ValidationInProgress = {}
    
    export type ValidationFailed = {
      validationMessages: ValidationMessage[]
      validateEvent: () => void
      payloadErrors: string | undefined
    }
  6. Manage Enhanced Ecommerce state with StoreProvider and StoreContext

    main

    The StoreProvider component provides a React Context (StoreContext) used to manage the state of an Enhanced Ecommerce demo, including the shopping cart, checkout information, and recorded GA events.

    To use this in your application, wrap your component tree with StoreProvider. You can then consume the state and control functions using the StoreContext hook.

    Available Context Values

    State Properties

    • cart: An array of CartItem currently in the cart.
    • lastCart: A snapshot of the previous cart state (populated when emptyCart is called).
    • events: An array of GAEvent objects representing recorded events.
    • checkoutState: The current CheckoutState (email, shipping/billing addresses, payment/shipping methods, etc.).
    • isOpen: A boolean indicating if the store interface is open.

    Actions

    • addEvent(name, description, snippet): Records a new GA event with a generated timestamp and key.
    • addVariantToCart(product, variantId, quantity): Adds a specific product variant to the cart.
    • removeLineItem(id): Removes an item from the cart by its unique ID.
    • updateLineItem(id, quantity): Updates the quantity of an existing cart item.
    • getCartSubtotal(): Returns the numeric total of all items in the cart based on product price.
    • emptyCart(): Clears the current cart, moves the current items to lastCart, and returns the emptied items.
    • onOpen() / onClose(): Functions to handle the visibility state of the store interface.
  7. Define GA4 Event structures and types

    main

    The Event2 interface defines the structure for a Google Analytics 4 (GA4) event. An event consists of an EventType, a list of Category values, a list of Parameter objects, and an optional list of item parameters.

    Parameters are typed as either StringParameter or NumberParameter using the ParameterType enum.

    export interface Event2 {
      type: EventType
      categories: Category[]
      parameters: Parameter[]
      items?: Parameter[][]
    }