Skip to content

Google Analytics — setup ​

How and why we instrument Google Analytics (GA4) events on Luna forms — the guiding principles, the standard event names, and worked examples for both Formik and non-Formik forms.

Why we track this ​

These guidelines allow us to:

  • Assess product usage — evaluate how our products are used to understand customer needs better.
  • Visualize user behavior — track user interactions to identify areas for improvement and enhance the user experience.
  • Utilize product feedback across the organization — harness customer feedback to drive product enhancements and improvements.

Principles ​

  • New forms should always consider including GA events wherever possible. Minimally, include form start and success events.
  • Differentiate submit vs edit events depending on whether the user is editing an existing entry or starting a new one.
  • Depending on whether the form uses Formik, how a form is considered "started", "cancelled", or "submitted" can differ significantly in behaviour. Leave comments and document clearly when each event is expected to fire for the form.

Main events ​

  • Use when a form starts:

    • luna_submit_start
    • luna_edit_start
  • Use when the form is successfully submitted/edited:

    • luna_submit_success
    • luna_edit_success
  • Use when the user cancels or navigates away from the form after it has started but before a successful submit:

    • luna_submit_cancel
    • luna_edit_cancel
  • Use if backend failure can be tracked:

    • luna_submit_failure
    • luna_edit_failure
  • Use if frontend validation error can be tracked:

    • luna_submit_error
    • luna_edit_error

How to instrument a form ​

There's one current pattern: the useGA() hook. Reach for it first; the sections below cover the Formik shortcut built on top of it, the non-Formik variant, and how to fire an event from outside a component (a thunk) when that's where the result you're tracking becomes known.

The useGA() hook ​

useGA() (@utils/hooks/analytics/useGA) returns sendGAEvent(event, action, formName), which dispatches a ReactGA.event() with the standard shape (category: 'Interaction', main_app/sub_app derived from the current path, and form_name). Call it directly inside the form component:

  • Start — a useEffect keyed on formik.dirty === true.
  • Cancel — a useEffect that listens for navigation away while the form is dirty, via globalHistory.listen.
  • Success / failure — fired wherever the submit result becomes known: in the component once the submit call resolves, or in the thunk that performs it (see "Firing an event outside a component" below).

HealthCheckForm is a clean example of the full arc — start and cancel in the component, success/failure in the thunk it dispatches to:

jsx
// clients/luna-front-end/src/pages/engagements/components/HealthCheck/HealthCheckForm.jsx
import useGA from '@utils/hooks/analytics/useGA';
import { AnalyticsFormName } from '@bhag-business-platform/luna-strings';

const HealthCheckForm = ({ engagementDetails }) => {
  const { sendGAEvent } = useGA();
  const isEditFlow = Boolean(initialValues?.start);

  // Start: fires the first time the form becomes dirty
  useEffect(() => {
    if (formik.dirty === true) {
      sendGAEvent(
        isEditFlow ? 'luna_edit_start' : 'luna_submit_start',
        isEditFlow ? 'Edit Start' : 'Submit Start',
        isEditFlow ? AnalyticsFormName.editHealthCheck : AnalyticsFormName.createHealthCheck
      );
    }
  }, [formik.dirty]);

  // Cancel: fires if the user navigates away while the form is dirty
  useEffect(() => {
    return globalHistory.listen(({ action }) => {
      if (action === 'PUSH' && formik.dirty === true) {
        sendGAEvent(
          isEditFlow ? 'luna_edit_cancel' : 'luna_submit_cancel',
          isEditFlow ? 'Edit Cancel' : 'Submit Cancel',
          isEditFlow ? AnalyticsFormName.editHealthCheck : AnalyticsFormName.createHealthCheck
        );
      }
    });
  }, [formik.dirty]);
  // ...
};
js
// clients/luna-front-end/src/store/Engagement/thunks/engagements.thunks.js
export const postHealthCheck =
  ({ engagementId, healthCheckToPost, isEditFlow, pathname }) =>
    (dispatch) => {
      dispatch(postHealthCheckRequest());
      api.engagements
        .addHealthCheck(engagementId, healthCheckToPost)
        .then((res) => {
          dispatch(postHealthCheckSuccess(res.data));
          // Success: fired once the API call resolves, from the thunk
          HandleGASubmit(
            isEditFlow ? AnalyticsFormName.editHealthCheck : AnalyticsFormName.createHealthCheck,
            isEditFlow,
            pathname,
            'success'
          );
        })
        // .catch(...) fires HandleGASubmit(..., 'failure') the same way
    };

Formik shortcut: GAFormikChangeHandler ​

For Formik forms, GAFormikChangeHandler (@components/GAFormikChangeHandler) wraps useGA() and fires the same dirty-based start effect and navigate-away cancel effect for you — drop it inside <Formik> instead of hand-writing those two useEffects:

jsx
// clients/luna-front-end/src/pages/newProfile/PersonalDetails/Sections/AboutMe/AboutMe.jsx
import GAFormikChangeHandler from '@components/GAFormikChangeHandler/GAFormikChangeHandler';
import { HandleGACancel } from '@utils/analytics';
import { AnalyticsFormName } from '@bhag-business-platform/luna-strings';

<Formik
  enableReinitialize
  initialValues={initialValues(myDetails?.aboutMe)}
  validationSchema={validationSchema}
  onSubmit={_submitForm}
>
  {({ resetForm }) => (
    <>
      <GAFormikChangeHandler formName={AnalyticsFormName.editProfileAboutMe} isEdit={true} />
      <Form>
        {/* ...fields... */}
        <Button
          onClick={() => {
            resetForm();
            setIsEditing(false);
            // Explicit Cancel click isn't covered by GAFormikChangeHandler — dispatch it here
            HandleGACancel(AnalyticsFormName.editProfileAboutMe, true, pathname);
          }}
        >
          Cancel
        </Button>
      </Form>
    </>
  )}
</Formik>

formName (from @bhag-business-platform/luna-strings) and isEdit are required props. GAFormikChangeHandler only covers start and navigate-away cancel — an explicit "Cancel" button click still needs its own HandleGACancel call, and submit success/failure still need their own dispatch (typically from the thunk the submit calls, as above).

No Formik ​

Without a formik.dirty flag to key off, fire the start event on mount instead, delayed slightly so it doesn't race GA's automatic page_view event:

jsx
// clients/luna-front-end/src/pages/opportunities/add/AddExpansion.jsx
import useGA from '@utils/hooks/analytics/useGA';
import { AnalyticsFormName } from '@bhag-business-platform/luna-strings';

const AddExpansion = () => {
  const { sendGAEvent } = useGA();

  const handleSubmit = useCallback((values) => {
    // ...dispatch the create action...
    sendGAEvent(
      'luna_submit_success',
      'Submit Success',
      AnalyticsFormName.createAdditionalOpportunity
    );
  });

  useEffect(() => {
    setTimeout(() => {
      sendGAEvent(
        'luna_submit_start',
        'Submit Start',
        AnalyticsFormName.createAdditionalOpportunity
      );
    }, 500);
  }, []);
  // ...
};

Firing an event outside a component ​

Hooks aren't available in a Redux thunk, so when the result you're tracking (usually success/failure) is only known there, use the plain helpers in @utils/analytics instead of useGA():

  • HandleGASubmit(formName, isEdit, pathname, type) — type is 'success', 'failure', 'error', etc, building the matching luna_<edit|submit>_<type> event.
  • HandleGACancel(formName, isEdit, pathname) — for an explicit cancel dispatched from outside a component (or an explicit button click, as in the GAFormikChangeHandler example above).

Both wrap ReactGA.event() directly — see the postHealthCheck thunk above for a real HandleGASubmit call.

Legacy shape — don't copy it

A handful of older components (EngagementForm.jsx, CreateInvoice.jsx) call ReactGA.event() directly inline, rebuilding main_app/sub_app by hand. That predates the useGA hook and was never migrated — use useGA() (or the thunk helpers above) in new forms instead.

Made with ❤️ by the Luna team