Skip to content

Commit 4952ddb

Browse files
authored
feat(landing): add HubSpot tracking script for hosted marketing site (#5565)
* feat(landing): add HubSpot tracking script for hosted marketing site - Loads the HubSpot loader in the landing route group only, gated by isHosted - Not loaded for self-hosted/OSS deployments - Adds the loader's companion scripts (analytics, form-tracking, banner) and their beacon hosts to CSP, verified against the actual scripts' network calls * fix(landing): scope HubSpot CSP hosts to the landing route group only Greptile flagged that the HubSpot script/connect hosts were added to the shared CSP arrays used by every route, including /workspace, /login, and /signup — even though the HubSpot loader only ever renders inside the (landing) route group. - Move the HubSpot hosts out of STATIC_SCRIPT_SRC/STATIC_CONNECT_SRC - Add generateLandingRuntimeCSP(), which extends the shared runtime policy with the HubSpot hosts, mirroring the existing getChatEmbedCSPPolicy() pattern for route-scoped CSP variants - Wire it into proxy.ts's catch-all branch, which is what actually serves the marketing/landing site; /workspace, /login, /signup keep the unmodified shared policy * fix(landing): track HubSpot pageviews on client-side landing navigations Cursor Bugbot flagged that the HubSpot loader only auto-fires a pageview on the initial load. Since LandingLayout persists across client-side navigations between landing routes, subsequent Link navigations never told HubSpot about the route change, undercounting pageviews. Add HubspotPageViewTracker, a small client component using the standard Next.js App Router pattern (usePathname/useSearchParams in a Suspense boundary) to push a manual pageview through HubSpot's _hsq queue on every navigation after the first. * simplify(landing): drop unnecessary Suspense from HubSpot pageview tracker usePathname() alone doesn't require a Suspense boundary to preserve static rendering — only useSearchParams() does. The tracker only needs the path, not the query string, so drop useSearchParams and the Suspense wrapper entirely. Simpler, and no risk to the landing site's static rendering/LCP. * fix(landing): exclude non-landing routes from the landing CSP fallback Greptile's second pass caught that proxy.ts's catch-all branch (which serves generateLandingRuntimeCSP()) also handles several non-landing pages that fall through the earlier explicit branches: /verify, /sso, /reset-password (auth sub-pages), /resume/[workflowId] (interfaces), /f/[token] (file shares), /playground, and the authenticated/callbackUrl invite fallthrough. None of these render the HubSpot loader, so they shouldn't get its CSP allowance either. Add an explicit non-landing path prefix list and only fall back to generateRuntimeCSP() (the tight policy) for those, keeping generateLandingRuntimeCSP() for everything else in the catch-all. * fix(landing): add /unsubscribe to non-landing paths, fix tracker remount bug - Greptile correctly flagged /unsubscribe as another top-level page outside (landing) that reaches the CSP fallback branch; add it to the exclusion list - Cursor caught that the per-mount useRef in HubspotPageViewTracker resets whenever LandingLayout remounts (e.g. leaving the landing site and coming back), but next/script dedupes the loader by id and won't re-fire the auto-tracked pageview on remount — so that return visit was silently dropped. Move the flag to module scope so it reflects the actual once-per-browser-session lifetime of the loader script, not per-mount * fix(landing): track query-only landing navigations in HubSpot pageviews Cursor caught that the tracker only depended on usePathname(), so client-side navigations that change only the query string (blog/library pagination, careers filters) never fired a pageview at all, and setPath dropped the search string even when the path did change. Add useSearchParams() back (the officially documented Next.js pattern for tracking all route changes) and depend on the full path+query string. Wrap the tracker in a local Suspense boundary, as required to keep the route statically rendered — the fallback is null and the component renders nothing, so this has no LCP/visual cost. * test(proxy): add regression coverage for the non-landing path classifier Exports isNonLandingPath and covers the exact prefix-boundary cases (e.g. /f vs /ffoo, /resume vs /resumes) that the CSP routing fix depends on, so this logic is verified by CI rather than my own ad-hoc checks. * fix(landing): exclude /landing-preview from the landing CSP fallback Greptile caught that /landing-preview calls notFound() in production (see app/landing-preview/page.tsx) and its subroutes (marks-lab, readme-tour-capture) don't render the (landing) layout either, so none of them ever load the HubSpot tracker — but the CSP fallback was still classifying the whole prefix as landing. * chore(landing): remove the /landing-preview test scaffold It was a temporary route for visual iteration (404s in production) — not needed anymore, and Greptile had just flagged it as another route that falsely inherited the landing CSP allowance. Removing it outright is simpler than maintaining an exclusion for it. Also removes SandboxWorkspacePermissionsProvider, which existed solely to support the deleted readme-tour-capture page and has no other callers. * refactor(landing): fix invalid const assertion, trim comments - Fixed HUBSPOT_SCRIPT_SRC/HUBSPOT_CONNECT_SRC: 'as const' cannot wrap a ternary expression directly (TS1355) — caught by a full project typecheck I ran specifically to verify this PR, not by lint/tests alone. Rewrote using the same conditional-spread-inside-array-literal pattern already used by every other array in this file (e.g. STATIC_FRAME_SRC) - Trimmed comments across all four touched files down to only the non-obvious 'why' (module-scope tracking flag, HubSpot CSP scoping rationale), matching this codebase's terse comment style elsewhere * revert(landing): drop landing-scoped CSP, put HubSpot in the shared policy Cursor caught a fundamental problem with the landing-scoped CSP: the Content-Security-Policy header is fixed to the document's initial HTTP response and is NOT re-applied on Next.js client-side (soft) navigation. Both the landing navbar's ChipLink to /login and AuthShell's Link back to / are soft navigations (confirmed directly in the source, not assumed). That means: - /login -> / (soft nav): the browser keeps /login's CSP, which never allowed HubSpot hosts, so the loader gets silently blocked on landing. - / -> /login (soft nav): the browser keeps the landing CSP, which is MORE permissive than /login's, undoing the tightening entirely. A per-route CSP is fundamentally incompatible with this app's client-side-routed navigation. Greptile's original 'CSP too broad on /workspace' concern was valid in isolation, but the fix built across the last several rounds doesn't actually work — it's neither reliably tighter nor reliably functional, and each round's patch (exclusion list entries, /landing-preview handling) was really just papering over that core issue. Revert to a single shared CSP for the whole app, matching exactly how GTM/GA/ahrefs are already handled in this same file: HubSpot hosts land in STATIC_SCRIPT_SRC/STATIC_CONNECT_SRC under the existing isHosted gate. /workspace's CSP header technically allows origins it never requests (same accepted tradeoff as GTM/GA), but the tracking script only ever renders in the (landing) layout — matching the CSP scope Greptile originally objected to. This is now provably correct because it can't desync: proxy.ts, csp.ts, and proxy.test.ts are byte-for-byte identical to origin/staging except for the HubSpot host list itself. * fix(csp): drop overbroad *.hubspot.com connect-src wildcard Greptile correctly flagged that *.hubspot.com is far broader than anything the tracker actually needs — it covers HubSpot's entire product surface (app, api, marketing), not just the tracking endpoints. Re-checked my own network trace from earlier: the pageview beacon itself is an image pixel (new Image() to track.hubspot.com/__pto.gif), which is governed by img-src (already wide open to any https: origin), not connect-src. The *.hubspot.com entry was an unverified guess for the forms-API/banner fetch calls I couldn't pin down through minification — removing it since I can't confirm what it was actually protecting, keeping only the verified *.hscollectedforms.net entry.
1 parent 08320d5 commit 4952ddb

8 files changed

Lines changed: 68 additions & 1702 deletions

File tree

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
'use client'
2+
3+
import { useEffect } from 'react'
4+
import { usePathname, useSearchParams } from 'next/navigation'
5+
6+
declare global {
7+
interface Window {
8+
_hsq?: unknown[][]
9+
}
10+
}
11+
12+
// next/script dedupes by id and never reloads on remount, so this must be
13+
// module-scope (not a ref) to survive LandingLayout unmounting/remounting.
14+
let hasTrackedInitialPageView = false
15+
16+
/**
17+
* The HubSpot loader only auto-tracks the first page load; LandingLayout
18+
* persists across client-side navigations, so HubSpot never sees the rest.
19+
* Pushes a manual pageview through `_hsq` on every navigation after the first.
20+
*/
21+
export function HubspotPageViewTracker() {
22+
const pathname = usePathname()
23+
const searchParams = useSearchParams()
24+
const query = searchParams.toString()
25+
26+
useEffect(() => {
27+
if (!hasTrackedInitialPageView) {
28+
hasTrackedInitialPageView = true
29+
return
30+
}
31+
32+
window._hsq = window._hsq || []
33+
window._hsq.push(['setPath', query ? `${pathname}?${query}` : pathname])
34+
window._hsq.push(['trackPageView'])
35+
}, [pathname, query])
36+
37+
return null
38+
}

apps/sim/app/(landing)/layout.tsx

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,13 @@
11
import type { ReactNode } from 'react'
2+
import { Suspense } from 'react'
23
import type { Metadata } from 'next'
4+
import Script from 'next/script'
5+
import { isHosted } from '@/lib/core/config/env-flags'
36
import { SITE_URL } from '@/lib/core/utils/urls'
47
import { LandingShell } from '@/app/(landing)/components'
8+
import { HubspotPageViewTracker } from '@/app/(landing)/hubspot-page-view-tracker'
9+
10+
const HUBSPOT_SCRIPT_SRC = 'https://js-na2.hs-scripts.com/246720681.js' as const
511

612
/**
713
* Route-group layout for the entire landing family - the home page, platform and
@@ -24,5 +30,18 @@ export const metadata: Metadata = {
2430
}
2531

2632
export default function LandingLayout({ children }: { children: ReactNode }) {
27-
return <LandingShell>{children}</LandingShell>
33+
return (
34+
<LandingShell>
35+
{children}
36+
{/* HubSpot tracking — hosted only */}
37+
{isHosted && (
38+
<>
39+
<Script id='hs-script-loader' src={HUBSPOT_SCRIPT_SRC} strategy='afterInteractive' />
40+
<Suspense fallback={null}>
41+
<HubspotPageViewTracker />
42+
</Suspense>
43+
</>
44+
)}
45+
</LandingShell>
46+
)
2847
}

0 commit comments

Comments
 (0)