Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

fix: csp (#21023)

ecmadao9404f7f84823
diff --git a/.github/workflows/build-push-cloud-image.yml b/.github/workflows/build-push-cloud-image.yml
index 6952709bbf..fca9722007 100644
--- a/.github/workflows/build-push-cloud-image.yml
+++ b/.github/workflows/build-push-cloud-image.yml
@@ -57,14 +57,19 @@ jobs:
BB_POSTHOG_KEY: ${{ vars.BB_POSTHOG_KEY }}
BB_POSTHOG_HOST: ${{ vars.BB_POSTHOG_HOST }}
BB_POSTHOG_RECORDING_SAMPLE_RATE: ${{ vars.BB_POSTHOG_RECORDING_SAMPLE_RATE || '1' }}
+ BB_GA4_MEASUREMENT_ID: ${{ vars.BB_GA4_MEASUREMENT_ID }}
run: |
if [ -z "${BB_POSTHOG_KEY}" ] || [ -z "${BB_POSTHOG_HOST}" ]; then
echo "BB_POSTHOG_KEY or BB_POSTHOG_HOST is not configured. Frontend analytics will be disabled." >&2
fi
+ if [ -z "${BB_GA4_MEASUREMENT_ID}" ]; then
+ echo "BB_GA4_MEASUREMENT_ID is not configured. GA4 will be disabled." >&2
+ fi
{
echo "BB_POSTHOG_KEY=${BB_POSTHOG_KEY}"
echo "BB_POSTHOG_HOST=${BB_POSTHOG_HOST}"
echo "BB_POSTHOG_RECORDING_SAMPLE_RATE=${BB_POSTHOG_RECORDING_SAMPLE_RATE}"
+ echo "BB_GA4_MEASUREMENT_ID=${BB_GA4_MEASUREMENT_ID}"
} > frontend/.env.release
- name: Build and push Docker image
diff --git a/backend/server/echo_routes.go b/backend/server/echo_routes.go
index bcaa0ef98b..663c54feda 100644
--- a/backend/server/echo_routes.go
+++ b/backend/server/echo_routes.go
@@ -159,7 +159,7 @@ func securityHeadersMiddleware(saas bool) echo.MiddlewareFunc {
imgSrc := "img-src 'self' data: blob: discordapp.com"
connectSrc := "connect-src 'self' data: ws: wss: https://api.github.com https://hub.bytebase.com"
if saas {
- scriptSrc += " https://www.googletagmanager.com"
+ scriptSrc += " https://www.googletagmanager.com https://*.i.posthog.com"
imgSrc += " https://*.google-analytics.com https://*.googletagmanager.com"
connectSrc += " https://*.google-analytics.com https://*.analytics.google.com https://*.googletagmanager.com https://*.i.posthog.com"
}
diff --git a/backend/server/echo_routes_test.go b/backend/server/echo_routes_test.go
index 88107c45dd..d6a48242e1 100644
--- a/backend/server/echo_routes_test.go
+++ b/backend/server/echo_routes_test.go
@@ -60,13 +60,25 @@ func TestSecurityHeadersMiddleware_GA4Sources(t *testing.T) {
}
}
-func TestSecurityHeadersMiddleware_SaaSAllowsPostHogIngestionHosts(t *testing.T) {
+func TestSecurityHeadersMiddleware_SaaSAllowsPostHogHosts(t *testing.T) {
csp := testSecurityHeadersCSP(t, true)
- if !strings.Contains(csp, "https://*.i.posthog.com") {
- t.Errorf("Content-Security-Policy = %q, want to contain PostHog ingestion hosts", csp)
+ for _, directive := range []string{"script-src", "connect-src"} {
+ if source := cspDirective(csp, directive); !strings.Contains(source, "https://*.i.posthog.com") {
+ t.Errorf("Content-Security-Policy %q directive = %q, want to contain PostHog hosts; csp=%q", directive, source, csp)
+ }
}
}
+func cspDirective(csp string, directive string) string {
+ for _, source := range strings.Split(csp, ";") {
+ source = strings.TrimSpace(source)
+ if strings.HasPrefix(source, directive+" ") {
+ return source
+ }
+ }
+ return ""
+}
+
func testSecurityHeadersCSP(t *testing.T, saas bool) string {
t.Helper()
diff --git a/frontend/src/components/DashboardBodyShell.test.tsx b/frontend/src/components/DashboardBodyShell.test.tsx
index 37fc7b5f2e..524780e6cb 100644
--- a/frontend/src/components/DashboardBodyShell.test.tsx
+++ b/frontend/src/components/DashboardBodyShell.test.tsx
@@ -112,19 +112,30 @@ describe("DashboardBodyShell", () => {
expect(
harness.container.querySelector('[data-label="bb-main-body-wrapper"]')
).not.toBeNull();
- expect(
- harness.container.querySelector('[data-label="bb-dashboard-header"]')
- ).not.toBeNull();
- expect(
- harness.container.querySelector(
- '[data-testid="dashboard-header"][data-show-logo="false"][data-show-mobile-toggle="true"]'
- )
- ).not.toBeNull();
+ const header = harness.container.querySelector(
+ '[data-label="bb-dashboard-header"]'
+ );
+ const body = harness.container.querySelector(
+ '[data-label="bb-dashboard-body"]'
+ );
+ const mainBody = harness.container.querySelector(
+ '[data-label="bb-main-body-wrapper"]'
+ );
+ const sidebar = harness.container.querySelector(
+ '[data-label="bb-dashboard-static-sidebar"]'
+ );
+ expect(header).not.toBeNull();
+ expect(body).not.toBeNull();
+ expect(header?.nextElementSibling).toBe(body);
+ expect(body?.contains(sidebar)).toBe(true);
+ expect(body?.contains(mainBody)).toBe(true);
+ expect(mainBody?.contains(header)).toBe(false);
expect(
harness.container.querySelector(
- '[data-label="bb-dashboard-static-sidebar"]'
+ '[data-testid="dashboard-header"][data-show-logo="true"][data-show-mobile-toggle="true"]'
)
).not.toBeNull();
+ expect(sidebar).not.toBeNull();
harness.unmount();
});
diff --git a/frontend/src/components/DashboardBodyShell.tsx b/frontend/src/components/DashboardBodyShell.tsx
index 0cdaf55440..71b339fb14 100644
--- a/frontend/src/components/DashboardBodyShell.tsx
+++ b/frontend/src/components/DashboardBodyShell.tsx
@@ -98,11 +98,29 @@ export function DashboardBodyShell({
mainContainer: mainContainerRef.current,
};
onReady?.(targets);
- }, [isDesktop, onReady, showHeader, showWorkspaceChrome, variant]);
+ }, [isDesktop, onReady, showWorkspaceChrome]);
return (
<div className="flex h-full flex-col overflow-hidden">
- <div className="flex flex-1 overflow-hidden">
+ {showHeader ? (
+ <nav
+ className="shrink-0 border-b border-block-border bg-white"
+ data-label="bb-dashboard-header"
+ >
+ <div className="mx-auto max-w-full">
+ <DashboardHeader
+ showLogo={showHeader}
+ showMobileSidebarToggle={showWorkspaceChrome}
+ onOpenMobileSidebar={() => setIsMobileSidebarOpen(true)}
+ />
+ </div>
+ </nav>
+ ) : null}
+
+ <div
+ className="flex flex-1 overflow-hidden"
+ data-label="bb-dashboard-body"
+ >
{showWorkspaceChrome ? (
<>
{createPortal(mobileSidebarOverlay, getLayerRoot("overlay"))}
@@ -128,21 +146,6 @@ export function DashboardBodyShell({
)}
data-label="bb-main-body-wrapper"
>
- {showHeader ? (
- <nav
- className="border-b border-block-border bg-white"
- data-label="bb-dashboard-header"
- >
- <div className="mx-auto max-w-full">
- <DashboardHeader
- showLogo={variant === "issues"}
- showMobileSidebarToggle={showWorkspaceChrome}
- onOpenMobileSidebar={() => setIsMobileSidebarOpen(true)}
- />
- </div>
- </nav>
- ) : null}
-
<div
id="bb-layout-main"
data-scroll-restoration-id={MAIN_SCROLL_RESTORATION_ID}
diff --git a/frontend/src/components/DashboardSidebar.test.tsx b/frontend/src/components/DashboardSidebar.test.tsx
index d51a3d1c74..1a554f56f0 100644
--- a/frontend/src/components/DashboardSidebar.test.tsx
+++ b/frontend/src/components/DashboardSidebar.test.tsx
@@ -4,11 +4,9 @@ import { createRoot } from "react-dom/client";
import { beforeEach, describe, expect, test, vi } from "vitest";
import {
DATABASE_ROUTE_DASHBOARD,
- SQL_EDITOR_HOME_MODULE,
WORKSPACE_ROUTE_LANDING,
WORKSPACE_ROUTE_MEMBERS,
} from "@/app/router";
-import { DatabaseChangeMode } from "@/types/proto-es/v1/setting_service_pb";
(
globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
@@ -21,9 +19,7 @@ const mocks = vi.hoisted(() => ({
params: {},
query: {},
},
- databaseChangeMode: 1,
isSaaSMode: false,
- workspaceLogo: "",
project: undefined as { name: string; title: string } | undefined,
workspace: {
name: "workspaces/default",
@@ -108,7 +104,6 @@ vi.mock("react-i18next", () => ({
}));
vi.mock("@/hooks/useAppState", () => ({
- useAppFeature: () => mocks.databaseChangeMode,
useIsSaaSMode: () => mocks.isSaaSMode,
useProject: () => mocks.project,
useRecentVisit: () => ({
@@ -118,10 +113,7 @@ vi.mock("@/hooks/useAppState", () => ({
subscription: mocks.subscription,
}),
useSwitchWorkspace: () => vi.fn(),
- useWorkspace: () => ({
- ...mocks.workspace,
- logo: mocks.workspaceLogo,
- }),
+ useWorkspace: () => mocks.workspace,
useWorkspaceList: () => mocks.workspaceList,
}));
@@ -141,7 +133,6 @@ vi.mock("@/app/router", () => ({
PROJECT_V1_ROUTE_DASHBOARD: "workspace.project",
SETTING_ROUTE_WORKSPACE_GENERAL: "setting.workspace.general",
SETTING_ROUTE_WORKSPACE_SUBSCRIPTION: "setting.workspace.subscription",
- SQL_EDITOR_HOME_MODULE: "sql-editor.home",
WORKSPACE_ROUTE_AUDIT_LOG: "workspace.audit-log",
WORKSPACE_ROUTE_CUSTOM_APPROVAL: "workspace.custom-approval",
WORKSPACE_ROUTE_DATA_CLASSIFICATION: "workspace.data-classification",
@@ -162,10 +153,6 @@ vi.mock("@/app/router", () => ({
WORKSPACE_ROUTE_WORKLOAD_IDENTITIES: "workspace.workload-identities",
}));
-vi.mock("@/assets/logo-full.svg", () => ({
- default: "/assets/logo-full.svg",
-}));
-
vi.mock("@/components/header/ProjectCreateDialog", () => ({
ProjectCreateDialog: () => null,
}));
@@ -200,9 +187,7 @@ beforeEach(async () => {
mocks.currentRoute.name = WORKSPACE_ROUTE_LANDING;
mocks.currentRoute.fullPath = "/";
mocks.currentRoute.params = {};
- mocks.databaseChangeMode = DatabaseChangeMode.PIPELINE;
mocks.isSaaSMode = false;
- mocks.workspaceLogo = "";
mocks.project = undefined;
mocks.workspace = {
name: "workspaces/default",
@@ -244,36 +229,18 @@ describe("DashboardSidebar", () => {
saas.unmount();
});
- test("uses database-change mode for the logo route and records visits", () => {
- mocks.databaseChangeMode = DatabaseChangeMode.EDITOR;
- mocks.workspaceLogo = "https://example.com/logo.png";
+ test("does not render the workspace logo in the sidebar", () => {
+ mocks.workspace.logo = "https://example.com/logo.png";
const { container, render, unmount } = renderIntoContainer(
<DashboardSidebar />
);
render();
- const logoLink = container.querySelector<HTMLAnchorElement>("nav > a");
- expect(logoLink?.getAttribute("href")).toBe("/sql-editor");
- expect(logoLink?.className).toContain("h-20");
- expect(logoLink?.className).toContain("w-full");
- expect(logoLink?.querySelector("img")?.getAttribute("src")).toBe(
- "https://example.com/logo.png"
- );
- expect(logoLink?.querySelector("img")?.className).toContain("h-full");
- expect(logoLink?.querySelector("img")?.className).toContain("w-full");
- expect(logoLink?.querySelector("img")?.className).toContain("max-w-44");
- expect(logoLink?.querySelector("img")?.className).toContain(
- "object-contain"
- );
-
- act(() => {
- logoLink?.dispatchEvent(
- new MouseEvent("click", { bubbles: true, cancelable: true })
- );
- });
-
- expect(mocks.record).toHaveBeenCalledWith("/sql-editor");
- expect(mocks.push).toHaveBeenCalledWith({ name: SQL_EDITOR_HOME_MODULE });
+ expect(container.querySelector("nav > a > img")).toBeNull();
+ expect(
+ container.querySelector("nav > div:last-child")?.className
+ ).toContain("pt-3");
+ expect(mocks.record).not.toHaveBeenCalled();
unmount();
});
@@ -291,10 +258,7 @@ describe("DashboardSidebar", () => {
expect(switcherBlock?.className).toContain("md:hidden");
expect(switcherBlock?.textContent).toContain("Default Workspace");
expect(switcherBlock?.textContent).toContain("Select project");
- expect(switcherBlock?.previousElementSibling?.tagName).toBe("A");
- expect(
- switcherBlock?.previousElementSibling?.querySelector("img")
- ).not.toBeNull();
+ expect(switcherBlock?.previousElementSibling).toBeNull();
unmount();
});
diff --git a/frontend/src/components/DashboardSidebar.tsx b/frontend/src/components/DashboardSidebar.tsx
index 784dd691be..6683bdd1ee 100644
--- a/frontend/src/components/DashboardSidebar.tsx
+++ b/frontend/src/components/DashboardSidebar.tsx
@@ -20,10 +20,8 @@ import {
ENVIRONMENT_V1_ROUTE_DASHBOARD,
INSTANCE_ROUTE_DASHBOARD,
PROJECT_V1_ROUTE_DASHBOARD,
- router,
SETTING_ROUTE_WORKSPACE_GENERAL,
SETTING_ROUTE_WORKSPACE_SUBSCRIPTION,
- SQL_EDITOR_HOME_MODULE,
useCurrentRoute,
WORKSPACE_ROUTE_AUDIT_LOG,
WORKSPACE_ROUTE_CUSTOM_APPROVAL,
@@ -44,16 +42,9 @@ import {
WORKSPACE_ROUTE_USERS,
WORKSPACE_ROUTE_WORKLOAD_IDENTITIES,
} from "@/app/router";
-import logoFull from "@/assets/logo-full.svg";
import { MobileSidebarSwitchers } from "@/components/header/HeaderBreadcrumb";
import { RouterLink } from "@/components/RouterLink";
-import {
- useAppFeature,
- useIsSaaSMode,
- useRecentVisit,
- useWorkspace,
-} from "@/hooks/useAppState";
-import { DatabaseChangeMode } from "@/types/proto-es/v1/setting_service_pb";
+import { useIsSaaSMode } from "@/hooks/useAppState";
// ---------------------------------------------------------------------------
// Types
@@ -299,9 +290,6 @@ export function DashboardSidebar() {
const rawItems = useSidebarItems();
const filteredItems = useMemo(() => filterSidebarList(rawItems), [rawItems]);
const currentRoute = useCurrentRoute();
- const databaseChangeMode = useAppFeature("bb.feature.database-change-mode");
- const workspace = useWorkspace();
- const { record } = useRecentVisit();
const currentRouteName = currentRoute.name ?? "";
// -- Expand / collapse state -----------------------------------------------
@@ -363,16 +351,6 @@ export function DashboardSidebar() {
// -- Navigation ------------------------------------------------------------
- const homeRoute = useMemo(() => {
- const target =
- databaseChangeMode === DatabaseChangeMode.EDITOR
- ? SQL_EDITOR_HOME_MODULE
- : WORKSPACE_ROUTE_LANDING;
- return {
- name: target,
- };
- }, [databaseChangeMode]);
-
const onGroupClick = useCallback((item: SidebarItem, key: string) => {
if (item.children && item.children.length > 0) {
manualToggledRef.current.add(key);
@@ -389,15 +367,6 @@ export function DashboardSidebar() {
}
}, []);
- const handleHomeClick = useCallback(() => {
- const route = router.resolve(homeRoute);
- record(route.fullPath);
- }, [homeRoute, record]);
-
- // -- Logo ------------------------------------------------------------------
-
- const logoSrc = workspace?.logo || logoFull;
-
// -- Render ----------------------------------------------------------------
const renderChildren = (children: SidebarItem[], parentIndex: number) => {
@@ -497,19 +466,8 @@ export function DashboardSidebar() {
return (
<nav className="flex-1 flex flex-col overflow-y-hidden border-r border-block-border">
- <RouterLink
- to={homeRoute}
- className="h-20 w-full shrink-0 cursor-pointer flex items-center justify-center px-4"
- onClick={handleHomeClick}
- >
- <img
- src={logoSrc}
- alt="Bytebase"
- className="h-full w-full max-w-44 object-contain"
- />
- </RouterLink>
<MobileSidebarSwitchers />
- <div className="flex-1 overflow-y-auto px-2.5 pb-4 flex flex-col gap-y-1">
+ <div className="flex-1 overflow-y-auto px-2.5 pt-3 pb-4 flex flex-col gap-y-1">
{filteredItems.map((item, i) => renderItem(item, i))}
</div>
</nav>
diff --git a/frontend/src/components/ProjectSidebar.test.tsx b/frontend/src/components/ProjectSidebar.test.tsx
index 6e062167b8..305edc8ec1 100644
--- a/frontend/src/components/ProjectSidebar.test.tsx
+++ b/frontend/src/components/ProjectSidebar.test.tsx
@@ -29,9 +29,6 @@ const mocks = vi.hoisted(() => ({
};
}
),
- workspace: {
- logo: "",
- },
}));
const t = vi.hoisted(
@@ -69,10 +66,6 @@ vi.mock("react-i18next", () => ({
}),
}));
-vi.mock("@/hooks/useAppState", () => ({
- useWorkspace: () => mocks.workspace,
-}));
-
vi.mock("@/hooks/useRecentVisit", () => ({
useRecentVisit: () => ({
record: mocks.record,
@@ -106,10 +99,6 @@ vi.mock("@/stores/app", () => {
return { useAppStore };
});
-vi.mock("@/assets/logo-full.svg", () => ({
- default: "/assets/logo-full.svg",
-}));
-
let ProjectSidebar: typeof import("./ProjectSidebar").ProjectSidebar;
const renderIntoContainer = (element: ReactElement) => {
@@ -138,7 +127,6 @@ beforeEach(async () => {
projectId: "sample",
};
mocks.defaultProject = "";
- mocks.workspace.logo = "";
({ ProjectSidebar } = await import("./ProjectSidebar"));
});
@@ -173,22 +161,16 @@ describe("ProjectSidebar", () => {
unmount();
});
- test("gives the custom logo an explicit rendered size", () => {
- mocks.workspace.logo = "https://example.com/logo.png";
+ test("does not render the workspace logo in the sidebar", () => {
const { container, render, unmount } = renderIntoContainer(
<ProjectSidebar />
);
render();
- const logoLink = container.querySelector("nav > a");
- const logo = container.querySelector("nav > a img");
- expect(logoLink?.className).toContain("h-20");
- expect(logoLink?.className).toContain("w-full");
- expect(logo?.getAttribute("src")).toBe("https://example.com/logo.png");
- expect(logo?.className).toContain("h-full");
- expect(logo?.className).toContain("w-full");
- expect(logo?.className).toContain("max-w-44");
- expect(logo?.className).toContain("object-contain");
+ expect(container.querySelector("nav > a > img")).toBeNull();
+ expect(
+ container.querySelector("nav > div:last-child")?.className
+ ).toContain("pt-3");
unmount();
});
diff --git a/frontend/src/components/ProjectSidebar.tsx b/frontend/src/components/ProjectSidebar.tsx
index b6d3a2506e..eb64c8306f 100644
--- a/frontend/src/components/ProjectSidebar.tsx
+++ b/frontend/src/components/ProjectSidebar.tsx
@@ -17,7 +17,6 @@ import {
PROJECT_V1_ROUTE_AUDIT_LOGS,
PROJECT_V1_ROUTE_DATABASE_GROUPS,
PROJECT_V1_ROUTE_DATABASES,
- PROJECT_V1_ROUTE_DETAIL,
PROJECT_V1_ROUTE_GITOPS,
PROJECT_V1_ROUTE_ISSUES,
PROJECT_V1_ROUTE_MASKING_EXEMPTION,
@@ -30,9 +29,7 @@ import {
PROJECT_V1_ROUTE_WEBHOOKS,
PROJECT_V1_ROUTE_WORKLOAD_IDENTITIES,
} from "@/app/router/handles";
-import logoFull from "@/assets/logo-full.svg";
import { RouterLink } from "@/components/RouterLink";
-import { useWorkspace } from "@/hooks/useAppState";
import { useRecentVisit } from "@/hooks/useRecentVisit";
import { useAppStore } from "@/stores/app";
import { projectNamePrefix } from "@/stores/modules/v1/common";
@@ -236,8 +233,6 @@ export function ProjectSidebar() {
const currentRouteName = route.name?.toString() ?? "";
const projectId = (route.params.projectId as string | undefined) ?? "";
- const customLogo = useWorkspace()?.logo ?? "";
-
const { record } = useRecentVisit();
const recordVisitRef = useRef(record);
recordVisitRef.current = record;
@@ -334,23 +329,6 @@ export function ProjectSidebar() {
[projectId]
);
- const homeRoute = useMemo(
- () => ({
- name: PROJECT_V1_ROUTE_DETAIL,
- params: { projectId },
- }),
- [projectId]
- );
-
- const handleHomeClick = useCallback(() => {
- const route = router.resolve(homeRoute);
- recordVisitRef.current?.(route.fullPath);
- }, [homeRoute]);
-
- // -- Logo ------------------------------------------------------------------
-
- const logoSrc = customLogo || logoFull;
-
// -- Render ----------------------------------------------------------------
const renderChildren = (children: SidebarItem[], parentIndex: number) => {
@@ -431,18 +409,7 @@ export function ProjectSidebar() {
return (
<nav className="flex-1 flex flex-col overflow-y-hidden border-r border-block-border">
- <RouterLink
- to={homeRoute}
- className="h-20 w-full shrink-0 cursor-pointer flex items-center justify-center px-4"
- onClick={handleHomeClick}
- >
- <img
- src={logoSrc}
- alt="Bytebase"
- className="h-full w-full max-w-44 object-contain"
- />
- </RouterLink>
- <div className="flex-1 overflow-y-auto px-2.5 pb-4 flex flex-col gap-y-1">
+ <div className="flex-1 overflow-y-auto px-2.5 pt-3 pb-4 flex flex-col gap-y-1">
{filteredItems.map((item, i) => renderItem(item, i))}
</div>
</nav>
diff --git a/frontend/src/lib/ga4.test.ts b/frontend/src/lib/ga4.test.ts
index 492d928c84..0195a63959 100644
--- a/frontend/src/lib/ga4.test.ts
+++ b/frontend/src/lib/ga4.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, describe, expect, test } from "vitest";
+import { afterEach, describe, expect, test, vi } from "vitest";
import { initializeGA4 } from "./ga4";
const ga4ScriptSelector = "script#bytebase-ga4-tag";
@@ -11,6 +11,7 @@ declare global {
}
afterEach(() => {
+ vi.unstubAllEnvs();
document.querySelector(ga4ScriptSelector)?.remove();
delete window.dataLayer;
delete window.gtag;
@@ -18,7 +19,17 @@ afterEach(() => {
});
describe("initializeGA4", () => {
+ test("does not load GA4 without a measurement ID", () => {
+ initializeGA4(true);
+
+ expect(document.querySelector(ga4ScriptSelector)).toBeNull();
+ expect(window.dataLayer).toBeUndefined();
+ expect(window.gtag).toBeUndefined();
+ });
+
test("does not load GA4 outside SaaS mode", () => {
+ vi.stubEnv("BB_GA4_MEASUREMENT_ID", "G-TEST");
+
initializeGA4(false);
expect(document.querySelector(ga4ScriptSelector)).toBeNull();
@@ -27,18 +38,20 @@ describe("initializeGA4", () => {
});
test("loads the shared GA4 property in SaaS mode", () => {
+ vi.stubEnv("BB_GA4_MEASUREMENT_ID", "G-TEST");
+
initializeGA4(true);
const script = document.querySelector<HTMLScriptElement>(ga4ScriptSelector);
expect(script?.async).toBe(true);
expect(script?.src).toBe(
- "https://www.googletagmanager.com/gtag/js?id=G-4BZ4JH7449"
+ "https://www.googletagmanager.com/gtag/js?id=G-TEST"
);
expect(window.dataLayer).toHaveLength(2);
expect(window.dataLayer?.[0][0]).toBe("js");
expect(window.dataLayer?.[1]).toEqual([
"config",
- "G-4BZ4JH7449",
+ "G-TEST",
{
page_location: `${window.location.origin}/`,
page_path: "/",
@@ -47,6 +60,8 @@ describe("initializeGA4", () => {
});
test("sanitizes the initial page view URL", () => {
+ vi.stubEnv("BB_GA4_MEASUREMENT_ID", "G-TEST");
+
window.history.replaceState(
null,
"",
@@ -57,7 +72,7 @@ describe("initializeGA4", () => {
expect(window.dataLayer?.[1]).toEqual([
"config",
- "G-4BZ4JH7449",
+ "G-TEST",
{
page_location: `${window.location.origin}/oauth/callback`,
page_path: "/oauth/callback",
diff --git a/frontend/src/lib/ga4.ts b/frontend/src/lib/ga4.ts
index 46a74c6a7e..26792f6255 100644
--- a/frontend/src/lib/ga4.ts
+++ b/frontend/src/lib/ga4.ts
@@ -1,4 +1,3 @@
-const GA4_MEASUREMENT_ID = "G-4BZ4JH7449";
const GA4_SCRIPT_ID = "bytebase-ga4-tag";
type GAWindow = Window & {
@@ -7,14 +6,17 @@ type GAWindow = Window & {
};
export function initializeGA4(isSaaSMode: boolean): void {
- if (!isSaaSMode || document.getElementById(GA4_SCRIPT_ID)) {
+ const measurementId = import.meta.env.BB_GA4_MEASUREMENT_ID as
+ | string
+ | undefined;
+ if (!isSaaSMode || !measurementId || document.getElementById(GA4_SCRIPT_ID)) {
return;
}
const script = document.createElement("script");
script.id = GA4_SCRIPT_ID;
script.async = true;
- script.src = `https://www.googletagmanager.com/gtag/js?id=${GA4_MEASUREMENT_ID}`;
+ script.src = `https://www.googletagmanager.com/gtag/js?id=${measurementId}`;
document.head.appendChild(script);
const gaWindow = window as GAWindow;
@@ -23,7 +25,7 @@ export function initializeGA4(isSaaSMode: boolean): void {
gaWindow.dataLayer?.push(args);
};
gaWindow.gtag("js", new Date());
- gaWindow.gtag("config", GA4_MEASUREMENT_ID, {
+ gaWindow.gtag("config", measurementId, {
page_location: `${window.location.origin}${window.location.pathname}`,
page_path: window.location.pathname,
});