Remove ANALYTICS_NAMESPACE, as it's only usable at build time (#2293)

Replaces `ANALYTICS_NAMESPACE` with setting `window.btrixEvent` via
`inject_extra` config

---------

Co-authored-by: sua yoo <sua@suayoo.com>
This commit is contained in:
Emma Segal-Grossman 2025-01-13 23:13:30 -05:00 committed by GitHub
parent 12f358b826
commit 04e9127d35
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 31 additions and 12 deletions

View File

@ -22,7 +22,4 @@ const WEBSOCKET_HOST =
module.exports = {
"window.process.env.WEBSOCKET_HOST": JSON.stringify(WEBSOCKET_HOST),
"window.process.env.ANALYTICS_NAMESPACE": JSON.stringify(
process.env.ANALYTICS_NAMESPACE || "",
),
};

View File

@ -227,3 +227,23 @@ inject_extra: >
```
Note that the script will only run when the web app loads, i.e. the first time the app is loaded in the browser and on hard refresh. The script will not run again upon clicking a link in the web app. This shouldn't be an issue with most analytics libraries, which should listen for changes to [window history](https://developer.mozilla.org/en-US/docs/Web/API/History). If you have a custom script that needs to re-run when the frontend URL changes, you'll need to add an event listener for the [`popstate` event](https://developer.mozilla.org/en-US/docs/Web/API/Window/popstate_event).
### Tracking events
Certain anonymized user interactions—such as public collection views, downloads, and shares—can be tracked for the purpose of collecting and analyzing metrics. To enable tracking these events, set `window.btrixEvent` in your `inject_extra` config to your custom track call. This should be a JavaScript function that conforms to the following type:
```ts
type btrixEvent = (
event: string,
extra?: {
props?: {
org_slug: string | null;
collection_id?: string | null;
collection_name?: string | null;
logged_in?: boolean;
};
},
) => void;
```
Tracking is optional and will never expose personally identifiable information.

View File

@ -4,4 +4,3 @@ E2E_USER_EMAIL=
E2E_USER_PASSWORD=
GLITCHTIP_DSN=
INJECT_EXTRA=
ANALYTICS_NAMESPACE=

View File

@ -14,22 +14,25 @@ export type AnalyticsTrackProps = {
logged_in?: boolean;
};
declare global {
interface Window {
btrixEvent?: (
event: string,
extra?: { props?: AnalyticsTrackProps },
) => void;
}
}
export function track(
event: `${AnalyticsTrackEvent}`,
props?: AnalyticsTrackProps,
) {
// ANALYTICS_NAMESPACE is specified with webpack `DefinePlugin`
const analytics = window.process.env.ANALYTICS_NAMESPACE
? // eslint-disable-next-line @typescript-eslint/no-explicit-any
(window as any)[window.process.env.ANALYTICS_NAMESPACE]
: null;
if (!analytics) {
if (!window.btrixEvent) {
return;
}
try {
analytics(event, { props });
window.btrixEvent(event, { props });
} catch (err) {
console.debug(err);
}