Load the Pulse analytics SDK after consent

React · React · intermediate · modification

Marketing asked for product analytics on the dashboard, and AppSec signed off on the Pulse SDK with SRI. `src/analytics/loadPulse.js` (new) adds the SDK's script tag once, with the integrity hash from AppSec and CORS mode, and resolves with `window.Pulse` when it loads or rejects when it fails. `src/analytics/AnalyticsLoader.jsx` (new) loads it once the visitor has consented, calls `Pulse.init` with the site key and logs a warning if loading fails. `src/App.jsx` mounts the loader with the consent flag. `src/analytics/loadPulse.test.jsx` (new) tests the script tag's attributes, the load and error paths, and the loader with and without consent.

Dashboard SPA on React 18.3 (Vite 5, function components, `StrictMode` in `main.jsx`). Tests run with `npm test`: Vitest 2 with @testing-library/react 16 in jsdom. Existing and unchanged: `useConsent()` returns `{ analytics, setAnalytics }`, where `analytics` is a boolean read from the consent cookie; it can go from `false` to `true` once while the page is open (the banner's Accept button), and withdrawing consent reloads the page. `ConsentBanner` and `Dashboard` are existing components. `VITE_PULSE_SITE_KEY` is set in `.env.development` and `.env.production`; the site key is public by design. The CSP header set by nginx includes `script-src 'self' https://cdn.jsdelivr.net`, which allows scripts from that host and carries no hashes, and `connect-src 'self' https://collect.pulse-analytics.io`, which already allows Pulse's collector (added when AppSec reviewed the vendor); the SDK sends its events only to that collector. jsDelivr serves npm files at `https://cdn.jsdelivr.net/npm/<package>@<version>/<file>` with `Access-Control-Allow-Origin: *`. Pulse SDK facts (vendor docs): executing `dist/pulse.min.js` defines `window.Pulse`; `Pulse.init({ siteKey })` starts tracking and records page views itself, client-side navigation included. 3.4.1 is the newest release on npm when this PR is opened, and the vendor publishes new releases to npm without notice to its customers.

Requirements

Files touched

Review this PR

React practice