diff --git a/example-apps/gatsby/README.md b/example-apps/gatsby/README.md index 2e15cfa6..8be6c1aa 100644 --- a/example-apps/gatsby/README.md +++ b/example-apps/gatsby/README.md @@ -1,11 +1,11 @@ # PostHog Gatsby example -A minimal [Gatsby](https://www.gatsbyjs.com) 5 site that uses the community [`gatsby-plugin-posthog`](https://github.com/PostHog/gatsby-plugin-posthog) plugin to add PostHog analytics, session replay, feature flags and error tracking. +A minimal [Gatsby](https://www.gatsbyjs.com) 5 site that uses the [PostHog JavaScript SDK](https://posthog.com/docs/libraries/js) (`posthog-js`) to add PostHog analytics, session replay, feature flags and error tracking. ## Features - **Product analytics**: pageviews, autocapture and a custom `burrito_considered` event -- **Session replay**: recordings start with the plugin's posthog-js snippet +- **Session replay**: recordings start when posthog-js initializes - **Feature flags**: `isFeatureEnabled()` gates a tip in the demo page - **Error tracking**: `captureException()` from a try/catch - **User identification**: a demo sign-in that calls `identify()`, and a sign-out that calls `reset()` @@ -31,7 +31,7 @@ GATSBY_POSTHOG_HOST=https://us.i.posthog.com Get your project token from your [PostHog project settings](https://app.posthog.com/project/settings). Use `https://eu.i.posthog.com` as the host for an EU Cloud project. -If the token is missing, the site still builds and runs. `gatsby-config.ts` leaves the plugin out and logs a warning outside production. +If the token is missing, the site still builds and runs. `gatsby-browser.ts` skips `posthog.init()`, and `gatsby-config.ts` logs a warning outside production. ### 3. Run the site @@ -44,45 +44,56 @@ pnpm build && pnpm serve ``` . -├── gatsby-config.ts # Registers gatsby-plugin-posthog with the token and host from env +├── gatsby-browser.ts # Initializes posthog-js when the site loads in the browser +├── gatsby-config.ts # Loads .env and warns when the token is missing └── src/ - ├── pages/ - │ └── index.tsx # Demo page: identify, custom event, feature flag, error capture - └── posthog.d.ts # Types for window.posthog + └── pages/ + └── index.tsx # Demo page: identify, custom event, feature flag, error capture ``` ## Key integration points -### Plugin setup (gatsby-config.ts) +### SDK setup (gatsby-browser.ts) ```typescript -{ - resolve: "gatsby-plugin-posthog", - options: { - apiKey: token, - apiHost: host, - isEnabledDevMode: true, - initOptions: { - defaults: "2026-08-30", - capture_pageview: false, - }, - }, +import posthog from "posthog-js" + +export const onClientEntry: GatsbyBrowser["onClientEntry"] = () => { + const token = process.env.GATSBY_POSTHOG_PROJECT_TOKEN + if (!token) return + + posthog.init(token, { + api_host: process.env.GATSBY_POSTHOG_HOST || "https://us.i.posthog.com", + defaults: "2026-08-30", + capture_pageview: "history_change", + }) } ``` -The plugin injects the posthog-js snippet into the page head and exposes the client as `window.posthog`. It has no `defaults` option of its own, but `initOptions` is passed through to `posthog.init()`, so `defaults` goes there. The plugin captures its own `$pageview` on every route change, including the first page load, so `capture_pageview: false` stops the SDK from sending a second one. +`onClientEntry` runs once in the browser, before the first page renders, so PostHog initializes before any page code calls it. Gatsby changes routes with the History API, so `capture_pageview: "history_change"` captures a `$pageview` on the first page load and on each route change. You do not need an `onRouteUpdate` handler. With `defaults` dated `2025-05-24` or later, `capture_pageview` is already `"history_change"`. This example sets it explicitly to make the behavior clear. + +Gatsby inlines `GATSBY_`-prefixed environment variables into the browser bundle at build time. `gatsby-config.ts` loads `.env` with `dotenv`, so the token and host are available to `gatsby-browser.ts`. The token ends up in the generated JavaScript, which is expected for a project token. -The plugin only loads PostHog in production builds unless `isEnabledDevMode` is `true`. The token is read in `gatsby-config.ts` at build time and ends up in the generated HTML, which is expected for a project token. +### Migrating from gatsby-plugin-posthog + +The `gatsby-plugin-posthog` plugin is deprecated. To move to `posthog-js`: + +1. Remove `gatsby-plugin-posthog` from the `plugins` array in `gatsby-config` and uninstall it. +2. Install `posthog-js` and initialize it in `gatsby-browser` as shown above. +3. Remove any manual `$pageview` captures in `onRouteUpdate`. If you keep them, each route change sends two pageviews. +4. Import `posthog` from `posthog-js` instead of using `window.posthog`. ### Identify, capture and reset (src/pages/index.tsx) ```typescript -window.posthog?.identify(username, { username }) -window.posthog?.capture("user_logged_in") +import posthog from "posthog-js" + +posthog.identify(username, { username }) +posthog.capture("user_logged_in") -window.posthog?.capture("burrito_considered", { total_considerations: n }) +posthog.capture("burrito_considered", { total_considerations: n }) -window.posthog?.reset() // on sign-out +posthog.reset() // on sign-out ``` Identify once when the user signs in, with your own stable user id (a primary key or UUID, never an email), and call `reset()` on sign-out. @@ -90,9 +101,9 @@ Identify once when the user signs in, with your own stable user id (a primary ke ### Feature flags and error capture ```typescript -window.posthog?.isFeatureEnabled("burrito-tip") +posthog.isFeatureEnabled("burrito-tip") -window.posthog?.captureException(err) +posthog.captureException(err) ``` ## Reverse proxy diff --git a/example-apps/gatsby/gatsby-browser.ts b/example-apps/gatsby/gatsby-browser.ts new file mode 100644 index 00000000..55ec4ca5 --- /dev/null +++ b/example-apps/gatsby/gatsby-browser.ts @@ -0,0 +1,15 @@ +import type { GatsbyBrowser } from "gatsby" +import posthog from "posthog-js" + +export const onClientEntry: GatsbyBrowser["onClientEntry"] = () => { + const token = process.env.GATSBY_POSTHOG_PROJECT_TOKEN + // Without a token, posthog-js would initialize with an empty key, so skip it + if (!token) return + + posthog.init(token, { + api_host: process.env.GATSBY_POSTHOG_HOST || "https://us.i.posthog.com", + defaults: "2026-08-30", + // Gatsby routes with the History API, so capture a $pageview on each route change + capture_pageview: "history_change", + }) +} diff --git a/example-apps/gatsby/gatsby-config.ts b/example-apps/gatsby/gatsby-config.ts index 83eae3c8..a93dfa12 100644 --- a/example-apps/gatsby/gatsby-config.ts +++ b/example-apps/gatsby/gatsby-config.ts @@ -1,12 +1,10 @@ import type { GatsbyConfig } from "gatsby" import dotenv from "dotenv" +// Loads .env so GATSBY_-prefixed variables get inlined into the browser bundle dotenv.config({ quiet: true }) -const token = process.env.GATSBY_POSTHOG_PROJECT_TOKEN -const host = process.env.GATSBY_POSTHOG_HOST || "https://us.i.posthog.com" - -if (!token && process.env.NODE_ENV !== "production") { +if (!process.env.GATSBY_POSTHOG_PROJECT_TOKEN && process.env.NODE_ENV !== "production") { console.warn( "GATSBY_POSTHOG_PROJECT_TOKEN variable required by PostHog is missing or un-configured, this causes events to be silently missed. This error stops appearing once GATSBY_POSTHOG_PROJECT_TOKEN is configured" ) @@ -16,28 +14,6 @@ const config: GatsbyConfig = { siteMetadata: { title: "Burrito consideration app", }, - plugins: [ - // Without a token the plugin would initialize PostHog with an empty key, so leave it out - ...(token - ? [ - { - resolve: "gatsby-plugin-posthog", - options: { - apiKey: token, - apiHost: host, - // Load PostHog during `gatsby develop` too - isEnabledDevMode: true, - // Passed through to posthog.init() - initOptions: { - defaults: "2026-08-30", - // The plugin captures a $pageview on every route change, including the first - capture_pageview: false, - }, - }, - }, - ] - : []), - ], } export default config diff --git a/example-apps/gatsby/package.json b/example-apps/gatsby/package.json index 04dc8497..ce49054f 100644 --- a/example-apps/gatsby/package.json +++ b/example-apps/gatsby/package.json @@ -11,7 +11,7 @@ "dependencies": { "dotenv": "^18.0.10", "gatsby": "^5.16.1", - "gatsby-plugin-posthog": "^1.0.1", + "posthog-js": "^1.448.0", "react": "^19.3.1", "react-dom": "^19.3.1" }, diff --git a/example-apps/gatsby/pnpm-lock.yaml b/example-apps/gatsby/pnpm-lock.yaml index dd21b211..cab2700a 100644 --- a/example-apps/gatsby/pnpm-lock.yaml +++ b/example-apps/gatsby/pnpm-lock.yaml @@ -14,9 +14,9 @@ importers: gatsby: specifier: ^5.16.1 version: 5.16.1(babel-eslint@10.1.0(eslint@7.32.0))(bare-buffer@3.7.1)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(type-fest@0.21.3)(typescript@7.0.2) - gatsby-plugin-posthog: - specifier: ^1.0.1 - version: 1.0.1(gatsby@5.16.1(babel-eslint@10.1.0(eslint@7.32.0))(bare-buffer@3.7.1)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(type-fest@0.21.3)(typescript@7.0.2))(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + posthog-js: + specifier: ^1.448.0 + version: 1.448.0(@types/react@19.3.0)(react@19.3.1) react: specifier: ^19.3.1 version: 19.3.1 @@ -1219,6 +1219,15 @@ packages: resolution: {integrity: sha512-//0sR/cow/s4ICQaYoAobOl4aU8cjU6x/V24V7XkKotb9+O+3zySIYp146vpaobYHnxa4pZX8NkV54Z5AwbDKA==} engines: {node: '>=12'} + '@posthog/browser-common@0.10.8': + resolution: {integrity: sha512-TQmqLVNFoKaL4dDV5Q8AScX2dIwdq8By2cj2KU1hMGe88tn7Usbf3U/hv5okhobEojntqJeslPIRBrG79Su+vg==} + + '@posthog/core@1.67.3': + resolution: {integrity: sha512-BAVJB+ADAjFNBVZKCRbMi5+WMJaSFHHIEId0/ebvAwhOVIMmK4mVrktGGjx9zJBHLe82JdQVVRhpaOwLgoBMgA==} + + '@posthog/types@1.425.0': + resolution: {integrity: sha512-VaAlT5cl2wQ8mRkC3agp32YqI1HCZyeDE9qc5cziXgtbqK8kGeodhqZpJgSIPz0wAl3yRtKN4yOL+d7wxDRPww==} + '@rtsao/scc@1.1.0': resolution: {integrity: sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g==} @@ -1330,6 +1339,9 @@ packages: '@types/semver@7.8.0': resolution: {integrity: sha512-1mAINjtQCXXeLkJ9ehXkwOcBpqtLxiVtKhpUf83DdRNdQKV0iXZpaHYqRr7nj+wvxuJzoAmAwXI+sCNMv1CzLQ==} + '@types/trusted-types@2.0.7': + resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==} + '@types/ws@8.18.2': resolution: {integrity: sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==} @@ -2457,6 +2469,9 @@ packages: resolution: {integrity: sha512-GrwoxYN+uWlzO8uhUXRl0P+kHE4GtVPfYzVLcUxPL7KNdHKj66vvlhiweIHqYYXWlw+T8iLMp42Lm67ghw4WMQ==} engines: {node: '>= 4'} + dompurify@3.4.17: + resolution: {integrity: sha512-B/pSlYVHQ58kqISD/yDjuJ1yfzI34m1gF4lAod2bwSRhiN4K5Cl3H8Af7hqB2PmTL911tdEudnnXn5FnhRoz0w==} + domutils@2.8.0: resolution: {integrity: sha512-w96Cjofp72M5IIhpjgobBimYEfoPjx1Vx0BSX9P30WBdZW2WIKU0T1Bd0kz2eNZ9ikjKgHbEyKx8BB6H1L3h3A==} @@ -2853,6 +2868,9 @@ packages: fbjs@3.0.5: resolution: {integrity: sha512-ztsSx77JBtkuMrEypfhgc3cI0+0h+svqeie7xHbh1k/IKdcydnvadp/mUaGgjAOXQmQSxsqgaRhS3q9fy+1kxg==} + fflate@0.4.9: + resolution: {integrity: sha512-zdxgIEddhfsyCaWpJ2SdXEP8ZMrKJ6+5jl4OupODcywU0IhRk6gdXuVGcPICyfx2H97hVK7xmJtRLPjkxAX8Vw==} + figures@3.2.0: resolution: {integrity: sha512-yaduQFRKLXYOGgEn6AZau90j3ggSOyiqXU0F9JZfeXYhNa+Jk4X+s45A2zg5jns87GAFa34BBm2kXw4XpNcbdg==} engines: {node: '>=8'} @@ -3038,13 +3056,6 @@ packages: peerDependencies: gatsby: ^5.0.0-next - gatsby-plugin-posthog@1.0.1: - resolution: {integrity: sha512-RIyDTj/XcMvmV6Vs6HJa8zQFGcQr52LcS4iD76g5WfFB705hFOAPchIISFoFMQd3qN1n3m4jUinhA/uuhN43Qg==} - peerDependencies: - gatsby: ^2.0.0 - react: ^16.4.2 - react-dom: ^16.4.2 - gatsby-plugin-typescript@5.16.0: resolution: {integrity: sha512-+eE2mfmNU+AxnSCBIFU1oJIETMpfvAsBywFDPwtwDLlNl7GyQnvv0kz2OvR+jG8kjlUwBrR+71LJCg8Ydc5CSw==} engines: {node: '>=18.0.0 <26'} @@ -4486,6 +4497,25 @@ packages: resolution: {integrity: sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==} engines: {node: ^10 || ^12 || >=14} + posthog-js@1.448.0: + resolution: {integrity: sha512-MX5/l3J5a/NPGCHcPDGh+UnbarZeoSed7ukfx9FKPmNXL4CAwtgsjnJFqlx+f6FpzO6Hfo7WWfUY+9WIavSwjA==} + peerDependencies: + '@types/react': '>=16.8.0' + react: '>=16.8.0' + peerDependenciesMeta: + '@types/react': + optional: true + react: + optional: true + + preact@10.29.8: + resolution: {integrity: sha512-ej2aVZ+vZ8WO7tvlQWRM9N63A0KzF9q4mWJfDUHgYaIofWY9hu74QdnQrjoPMmZi2/nZ5gN0bJCQF49xQqx09Q==} + peerDependencies: + preact-render-to-string: '>=5' + peerDependenciesMeta: + preact-render-to-string: + optional: true + prebuild-install@7.1.3: resolution: {integrity: sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==} engines: {node: '>=10'} @@ -4549,6 +4579,9 @@ packages: resolution: {integrity: sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA==} engines: {node: '>=0.6'} + query-selector-shadow-dom@1.0.1: + resolution: {integrity: sha512-lT5yCqEBgfoMYpf3F2xQRK7zEr1rhIIZuceDK6+xRkJQ4NMbHTwXqk4NkwDwQMNqXgG9r9fyHnzwNVs6zV5KRw==} + query-string@6.14.1: resolution: {integrity: sha512-XDxAeVmpfu1/6IjyT/gXHOl+S0vQ9owggJ30hhWKdHAsNPOcasn5o9BW0eejZqL2e4vMjhAxoW3jVHcD6mbcYw==} engines: {node: '>=6'} @@ -5442,6 +5475,12 @@ packages: weak-lru-cache@1.2.3: resolution: {integrity: sha512-pF0uTATIDYJFeEX4GDD5zjOe2jU9EJbBRcpcGPonUcao7eSp2hl6VA0b2Ims9jisMX33x6zgnozvaBCEsXNGPw==} + web-vitals@6.2.1: + resolution: {integrity: sha512-rLcLXA2sx6+9dE88NHFubwTtGxpK4yYBLj6qHPdFoCaLr0cXGb4efOqtKLlm4loGA4OEKHIQKMKzZkKyOh5ctw==} + + web-vitals@6.2.3: + resolution: {integrity: sha512-Dmy+vdO1UPMqXiAtZSNayhl4f794Bxfd94W4HIj2HlYtczEQfEOon969memlcpcHrTuOKLa5baFjX7WbgmOq+A==} + webidl-conversions@3.0.1: resolution: {integrity: sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==} @@ -7130,6 +7169,21 @@ snapshots: '@pnpm/network.ca-file': 1.0.2 config-chain: 1.1.13 + '@posthog/browser-common@0.10.8': + dependencies: + '@posthog/core': 1.67.3 + '@posthog/types': 1.425.0 + dompurify: 3.4.17 + preact: 10.29.8 + transitivePeerDependencies: + - preact-render-to-string + + '@posthog/core@1.67.3': + dependencies: + '@posthog/types': 1.425.0 + + '@posthog/types@1.425.0': {} + '@rtsao/scc@1.1.0': {} '@sideway/address@4.1.5': @@ -7253,6 +7307,9 @@ snapshots: '@types/semver@7.8.0': {} + '@types/trusted-types@2.0.7': + optional: true + '@types/ws@8.18.2': dependencies: '@types/node': 26.6.6 @@ -8536,6 +8593,10 @@ snapshots: dependencies: domelementtype: 2.3.0 + dompurify@3.4.17: + optionalDependencies: + '@types/trusted-types': 2.0.7 + domutils@2.8.0: dependencies: dom-serializer: 1.4.1 @@ -9140,6 +9201,8 @@ snapshots: transitivePeerDependencies: - encoding + fflate@0.4.9: {} + figures@3.2.0: dependencies: escape-string-regexp: 1.0.5 @@ -9425,13 +9488,6 @@ snapshots: - react-native-b4a - supports-color - gatsby-plugin-posthog@1.0.1(gatsby@5.16.1(babel-eslint@10.1.0(eslint@7.32.0))(bare-buffer@3.7.1)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(type-fest@0.21.3)(typescript@7.0.2))(react-dom@19.3.1(react@19.3.1))(react@19.3.1): - dependencies: - '@babel/runtime': 7.29.13 - gatsby: 5.16.1(babel-eslint@10.1.0(eslint@7.32.0))(bare-buffer@3.7.1)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(type-fest@0.21.3)(typescript@7.0.2) - react: 19.3.1 - react-dom: 19.3.1(react@19.3.1) - gatsby-plugin-typescript@5.16.0(gatsby@5.16.1(babel-eslint@10.1.0(eslint@7.32.0))(bare-buffer@3.7.1)(react-dom@19.3.1(react@19.3.1))(react@19.3.1)(type-fest@0.21.3)(typescript@7.0.2)): dependencies: '@babel/core': 7.29.13 @@ -11034,6 +11090,26 @@ snapshots: picocolors: 1.1.1 source-map-js: 1.2.2 + posthog-js@1.448.0(@types/react@19.3.0)(react@19.3.1): + dependencies: + '@posthog/browser-common': 0.10.8 + '@posthog/core': 1.67.3 + '@posthog/types': 1.425.0 + core-js: 3.51.0 + dompurify: 3.4.17 + fflate: 0.4.9 + preact: 10.29.8 + query-selector-shadow-dom: 1.0.1 + web-vitals: 6.2.3 + web-vitals-soft-navs: web-vitals@6.2.1 + optionalDependencies: + '@types/react': 19.3.0 + react: 19.3.1 + transitivePeerDependencies: + - preact-render-to-string + + preact@10.29.8: {} + prebuild-install@7.1.3: dependencies: detect-libc: 2.1.2 @@ -11109,6 +11185,8 @@ snapshots: es-define-property: 1.0.1 side-channel: 1.1.1 + query-selector-shadow-dom@1.0.1: {} + query-string@6.14.1: dependencies: decode-uri-component: 0.2.2 @@ -12136,6 +12214,10 @@ snapshots: weak-lru-cache@1.2.3: {} + web-vitals@6.2.1: {} + + web-vitals@6.2.3: {} + webidl-conversions@3.0.1: {} webpack-dev-middleware@5.3.4(webpack@5.98.0(postcss@8.5.32)): diff --git a/example-apps/gatsby/src/pages/index.tsx b/example-apps/gatsby/src/pages/index.tsx index c0dbb144..468a429f 100644 --- a/example-apps/gatsby/src/pages/index.tsx +++ b/example-apps/gatsby/src/pages/index.tsx @@ -1,5 +1,6 @@ import * as React from "react" import type { HeadFC, PageProps } from "gatsby" +import posthog from "posthog-js" // Stands in for your auth system: each username gets a stable user id, the way a user // record's primary key would. Identify with that id, never with the username or email. @@ -22,31 +23,31 @@ const IndexPage: React.FC = () => { e.preventDefault() if (!username) return - window.posthog?.identify(getUserId(username), { username }) - window.posthog?.capture("user_logged_in") + posthog.identify(getUserId(username), { username }) + posthog.capture("user_logged_in") setUser(username) setUsername("") } const handleLogout = () => { - window.posthog?.reset() + posthog.reset() setUser(null) setConsiderations(0) } const handleConsider = () => { - window.posthog?.capture("burrito_considered", { + posthog.capture("burrito_considered", { total_considerations: considerations + 1, }) setConsiderations(considerations + 1) - setShowTip(window.posthog?.isFeatureEnabled("burrito-tip") === true) + setShowTip(posthog.isFeatureEnabled("burrito-tip") === true) } const handleError = () => { try { throw new Error("Demo burrito error") } catch (err) { - window.posthog?.captureException(err) + posthog.captureException(err) } } diff --git a/example-apps/gatsby/src/posthog.d.ts b/example-apps/gatsby/src/posthog.d.ts deleted file mode 100644 index 94d52c47..00000000 --- a/example-apps/gatsby/src/posthog.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -// The Gatsby plugin loads posthog-js with a script snippet and exposes it as window.posthog -interface PostHogSnippet { - identify(distinctId: string, personProperties?: Record): void - capture(event: string, properties?: Record): void - captureException(error: unknown): void - isFeatureEnabled(key: string): boolean | undefined - reset(): void -} - -interface Window { - posthog?: PostHogSnippet -} diff --git a/example-apps/gatsby/tsconfig.json b/example-apps/gatsby/tsconfig.json index db38f341..968aa37d 100644 --- a/example-apps/gatsby/tsconfig.json +++ b/example-apps/gatsby/tsconfig.json @@ -10,5 +10,5 @@ "skipLibCheck": true, "esModuleInterop": true }, - "include": ["src", "gatsby-config.ts"] + "include": ["src", "gatsby-config.ts", "gatsby-browser.ts"] }