:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(session-replay): add Unity onboarding support (#94235)
Manoel Aranda Neto17b35cf13ecc
diff --git a/docs/onboarding/session-replay/index.ts b/docs/onboarding/session-replay/index.tsindex 1bbf2c7dcd90..493235100964 100644--- a/docs/onboarding/session-replay/index.ts+++ b/docs/onboarding/session-replay/index.ts@@ -10,6 +10,7 @@ export { FlutterInstallation } from './flutter'export { FramerInstallation } from './framer'export { IOSInstallation } from './ios'export { KMPInstallation } from './kmp'+export { UnityInstallation } from './unity'export { WebInstallation } from './web'export { NextJSInstallation } from './nextjs'export { NuxtInstallation } from './nuxt'diff --git a/docs/onboarding/session-replay/unity.tsx b/docs/onboarding/session-replay/unity.tsxnew file mode 100644index 000000000000..7986ba3f947e--- /dev/null+++ b/docs/onboarding/session-replay/unity.tsx@@ -0,0 +1,112 @@+import { OnboardingComponentsContext, createInstallation } from 'scenes/onboarding/shared/OnboardingDocsContentWrapper'++import { StepDefinition } from '../steps'++export const getUnitySteps = (ctx: OnboardingComponentsContext): StepDefinition[] => {+ const { CalloutBox, CodeBlock, Markdown, dedent, snippets } = ctx+ const SessionReplayFinalSteps = snippets?.SessionReplayFinalSteps++ return [+ {+ title: 'Install the Unity SDK',+ badge: 'required',+ content: (+ <>+ <Markdown>+ {dedent`+ Session replay requires Unity 2021.3 LTS or later with the .NET Standard 2.1 API Compatibility Level.++ In the Unity Editor:++ 1. Open **Window > Package Manager**.+ 2. Select **Add package from git URL** from the **+** menu.+ 3. Enter the following URL:+ `}+ </Markdown>+ <CodeBlock+ blocks={[+ {+ language: 'text',+ code: 'https://github.com/PostHog/posthog-unity.git?path=com.posthog.unity',+ },+ ]}+ />+ </>+ ),+ },+ {+ title: 'Enable session recordings in project settings',+ badge: 'required',+ content: (+ <Markdown>+ Go to your PostHog [Project Settings](https://us.posthog.com/settings/project-replay) and enable+ **Record user sessions**. Session recordings will not work without this setting enabled.+ </Markdown>+ ),+ },+ {+ title: 'Configure PostHog with session replay',+ badge: 'required',+ content: (+ <>+ <Markdown>+ Enable `SessionReplay` in your PostHog configuration. You can also configure session replay in+ **Edit > Project Settings > PostHog** in the Unity Editor. The `SessionReplayConfig`+ values below are the SDK defaults. Adjust them to match your app's requirements.+ </Markdown>+ <CodeBlock+ blocks={[+ {+ language: 'csharp',+ file: 'GameManager.cs',+ code: dedent`+ using PostHogUnity;+ using PostHogUnity.SessionReplay;++ PostHog.Setup(new PostHogConfig+ {+ ApiKey = "<ph_project_token>",+ Host = "<ph_client_api_host>",+ SessionReplay = true,+ SessionReplayConfig = new PostHogSessionReplayConfig+ {+ ThrottleDelaySeconds = 1.0f,+ ScreenshotQuality = 80,+ ScreenshotScale = 0.75f,+ CaptureNetworkTelemetry = true,+ CaptureLogs = false,+ MinLogLevel = SessionReplayLogLevel.Error,+ }+ });+ `,+ },+ ]}+ />+ <Markdown>+ The SDK captures screenshots, touch and mouse input, and optional console logs. Session replay+ requires `AsyncGPUReadback` support and is automatically disabled on WebGL.+ </Markdown>+ <CalloutBox type="caution" title="No masking support">+ <Markdown>+ The Unity SDK uses screenshot-based capture and cannot mask text, images, or other UI+ elements. Screenshots may contain sensitive information. Do not display personal data or+ secrets during recorded sessions.+ </Markdown>+ </CalloutBox>+ <Markdown>+ Unity session replay uses local SDK configuration. Configure capture options and sampling in+ code when the SDK starts. See the [Unity session replay+ docs](https://posthog.com/docs/session-replay/installation/unity) for all available options.+ </Markdown>+ </>+ ),+ },+ {+ title: 'Watch session recordings',+ badge: 'recommended',+ content: <>{SessionReplayFinalSteps && <SessionReplayFinalSteps />}</>,+ },+ ]+}++export const UnityInstallation = createInstallation(getUnitySteps)diff --git a/frontend/src/scenes/onboarding/legacy/sdks/session-replay/SessionReplaySDKInstructions.test.ts b/frontend/src/scenes/onboarding/legacy/sdks/session-replay/SessionReplaySDKInstructions.test.tsnew file mode 100644index 000000000000..3cf374cb87f9--- /dev/null+++ b/frontend/src/scenes/onboarding/legacy/sdks/session-replay/SessionReplaySDKInstructions.test.ts@@ -0,0 +1,17 @@+import { SDKKey } from '~/types'++import { getAvailableSDKs } from '../getAvailableSDKs'+import { SessionReplaySDKDocsLinkOverrides, SessionReplaySDKInstructions } from './SessionReplaySDKInstructions'++describe('SessionReplaySDKInstructions', () => {+ it('makes Unity selectable with session replay instructions and docs', () => {+ const availableSDKs = getAvailableSDKs(SessionReplaySDKInstructions, {}, SessionReplaySDKDocsLinkOverrides)+ const unitySDK = availableSDKs.find(({ key }) => key === SDKKey.UNITY)++ expect(SessionReplaySDKInstructions[SDKKey.UNITY]).not.toBeUndefined()+ expect(unitySDK).toMatchObject({+ key: SDKKey.UNITY,+ docsLink: 'https://posthog.com/docs/session-replay/installation/unity',+ })+ })+})diff --git a/frontend/src/scenes/onboarding/legacy/sdks/session-replay/SessionReplaySDKInstructions.tsx b/frontend/src/scenes/onboarding/legacy/sdks/session-replay/SessionReplaySDKInstructions.tsxindex 3f466321a453..b4df71f09832 100644--- a/frontend/src/scenes/onboarding/legacy/sdks/session-replay/SessionReplaySDKInstructions.tsx+++ b/frontend/src/scenes/onboarding/legacy/sdks/session-replay/SessionReplaySDKInstructions.tsx@@ -15,6 +15,7 @@ import {RemixInstallation,SessionReplayFinalSteps,SvelteInstallation,+ UnityInstallation,VueInstallation,WebflowInstallation,WebInstallation,@@ -22,7 +23,7 @@ import {import { JS_WEB_SNIPPETS } from 'scenes/onboarding/shared/jsWebSnippets'-import { SDKInstructionsMap, SDKKey } from '~/types'+import { SDKDocsLinkOverrides, SDKInstructionsMap, SDKKey } from '~/types'import { withOnboardingDocsWrapper } from '../shared/onboardingWrappers'@@ -34,6 +35,10 @@ const SNIPPETS = {SessionReplayFinalSteps,}+export const SessionReplaySDKDocsLinkOverrides: SDKDocsLinkOverrides = {+ [SDKKey.UNITY]: 'https://posthog.com/docs/session-replay/installation/unity',+}+// JS Web SDKsconst SessionReplayWebInstructionsWrapper = withOnboardingDocsWrapper({Installation: WebInstallation,@@ -125,6 +130,10 @@ const SessionReplayRNInstructionsWrapper = withOnboardingDocsWrapper({snippets: SNIPPETS,wizardIntegrationName: 'React Native',})+const SessionReplayUnityInstructionsWrapper = withOnboardingDocsWrapper({+ Installation: UnityInstallation,+ snippets: SNIPPETS,+})export const SessionReplaySDKInstructions: SDKInstructionsMap = {[SDKKey.JS_WEB]: SessionReplayWebInstructionsWrapper,@@ -147,4 +156,5 @@ export const SessionReplaySDKInstructions: SDKInstructionsMap = {[SDKKey.REACT_NATIVE]: SessionReplayRNInstructionsWrapper,[SDKKey.FLUTTER]: SessionReplayFlutterInstructionsWrapper,[SDKKey.KMP]: SessionReplayKMPInstructionsWrapper,+ [SDKKey.UNITY]: SessionReplayUnityInstructionsWrapper,}diff --git a/products/session_replay/frontend/onboarding/steps.tsx b/products/session_replay/frontend/onboarding/steps.tsxindex c0ea9c3db5b5..27bc9c5e58cb 100644--- a/products/session_replay/frontend/onboarding/steps.tsx+++ b/products/session_replay/frontend/onboarding/steps.tsx@@ -5,7 +5,10 @@ import { SESSION_REPLAY_MINIMUM_DURATION_OPTIONS } from 'lib/constants'import { OnboardingProductConfiguration } from 'scenes/onboarding/legacy/OnboardingProductConfiguration'import { type ProductConfigOption } from 'scenes/onboarding/legacy/onboardingProductConfigurationLogic'import { OnboardingInstallStep } from 'scenes/onboarding/legacy/sdks/OnboardingInstallStep'-import { SessionReplaySDKInstructions } from 'scenes/onboarding/legacy/sdks/session-replay/SessionReplaySDKInstructions'+import {+ SessionReplaySDKDocsLinkOverrides,+ SessionReplaySDKInstructions,+} from 'scenes/onboarding/legacy/sdks/session-replay/SessionReplaySDKInstructions'import { INSTALL_DEDUP_KEYS, type ProductOnboardingProvider } from 'scenes/onboarding/legacy/types'import { getMaskingConfigFromLevel, getMaskingLevelFromConfig } from 'scenes/session-recordings/utils'import { teamLogic } from 'scenes/teamLogic'@@ -91,7 +94,12 @@ export const sessionReplayOnboarding: ProductOnboardingProvider = {role: ctx.role,setupTaskId: SetupTaskId.SetupSessionRecordings,dedupKey: INSTALL_DEDUP_KEYS.POSTHOG_JS,- render: () => <OnboardingInstallStep sdkInstructionMap={SessionReplaySDKInstructions} />,+ render: () => (+ <OnboardingInstallStep+ sdkInstructionMap={SessionReplaySDKInstructions}+ sdkDocsLinkOverrides={SessionReplaySDKDocsLinkOverrides}+ />+ ),}if (ctx.role === 'secondary') {diff --git a/rust/feature-flags/src/handler/session_recording.rs b/rust/feature-flags/src/handler/session_recording.rsindex 3ad445762133..94f6af2d9a11 100644--- a/rust/feature-flags/src/handler/session_recording.rs+++ b/rust/feature-flags/src/handler/session_recording.rs@@ -6,11 +6,12 @@ use axum::http::HeaderMap;use regex;use serde_json::{json, Value};-const AUTHORIZED_MOBILE_CLIENTS: &[&str] = &[+const AUTHORIZED_MOBILE_AND_DESKTOP_CLIENTS: &[&str] = &["posthog-android","posthog-ios","posthog-react-native","posthog-flutter",+ "posthog-unity",];// Hard-coded values set for the session recording beta, still haven't come up with more sensible@@ -189,7 +190,7 @@ fn parse_domain(url: Option<&str>) -> Option<String> {////// Returns true if:/// - Origin or Referer hostname matches one of the allowed domains (supports wildcards)-/// - User-Agent indicates an authorized mobile client (android, ios, react-native, flutter)+/// - User-Agent indicates an authorized mobile or desktop clientpub fn on_permitted_domain(recording_domains: &[String], headers: &HeaderMap) -> bool {let origin = headers.get("Origin").and_then(|v| v.to_str().ok());let referer = headers.get("Referer").and_then(|v| v.to_str().ok());@@ -203,10 +204,13 @@ pub fn on_permitted_domain(recording_domains: &[String], headers: &HeaderMap) ->hostname_in_allowed_url_list(recording_domains, origin_hostname.as_deref())|| hostname_in_allowed_url_list(recording_domains, referer_hostname.as_deref());- let is_authorized_mobile_client =- user_agent.is_some_and(|ua| AUTHORIZED_MOBILE_CLIENTS.iter().any(|&kw| ua.contains(kw)));+ let is_authorized_mobile_or_desktop_client = user_agent.is_some_and(|ua| {+ AUTHORIZED_MOBILE_AND_DESKTOP_CLIENTS+ .iter()+ .any(|&kw| ua.contains(kw))+ });- is_authorized_web_client || is_authorized_mobile_client+ is_authorized_web_client || is_authorized_mobile_or_desktop_client}#[cfg(test)]@@ -325,6 +329,17 @@ mod tests {assert!(!on_permitted_domain(&recording_domains, &headers));}+ #[test]+ fn test_on_permitted_domain_with_unity_user_agent() {+ use axum::http::HeaderMap;++ let recording_domains = vec!["https://web-only.com".to_string()];+ let mut headers = HeaderMap::new();+ headers.insert("User-Agent", "posthog-unity/1.0.0".parse().unwrap());++ assert!(on_permitted_domain(&recording_domains, &headers));+ }+#[test]fn test_on_permitted_domain_with_wildcards() {use axum::http::HeaderMap;diff --git a/rust/hypercache-server/src/sanitize.rs b/rust/hypercache-server/src/sanitize.rsindex be981e810ae6..c647798fa8d5 100644--- a/rust/hypercache-server/src/sanitize.rs+++ b/rust/hypercache-server/src/sanitize.rs@@ -9,11 +9,12 @@use axum::http::HeaderMap;use serde_json::{json, Value};-const AUTHORIZED_MOBILE_CLIENTS: &[&str] = &[+const AUTHORIZED_MOBILE_AND_DESKTOP_CLIENTS: &[&str] = &["posthog-android","posthog-ios","posthog-react-native","posthog-flutter",+ "posthog-unity",];/// Sanitize cached config before returning to clients.@@ -98,7 +99,7 @@ pub fn sanitize_surveys_for_client(payload: &mut Value) {////// Returns true if:/// - Origin or Referer hostname matches one of the allowed domains (supports wildcards)-/// - User-Agent indicates an authorized mobile client (android, ios, react-native, flutter)+/// - User-Agent indicates an authorized mobile or desktop clientpub fn on_permitted_domain(recording_domains: &[String], headers: &HeaderMap) -> bool {let origin = headers.get("Origin").and_then(|v| v.to_str().ok());let referer = headers.get("Referer").and_then(|v| v.to_str().ok());@@ -116,10 +117,13 @@ pub fn on_permitted_domain(recording_domains: &[String], headers: &HeaderMap) ->let is_authorized_web_client = hostname_matches(&permitted_domains, origin_hostname.as_deref())|| hostname_matches(&permitted_domains, referer_hostname.as_deref());- let is_authorized_mobile_client =- user_agent.is_some_and(|ua| AUTHORIZED_MOBILE_CLIENTS.iter().any(|&kw| ua.contains(kw)));+ let is_authorized_mobile_or_desktop_client = user_agent.is_some_and(|ua| {+ AUTHORIZED_MOBILE_AND_DESKTOP_CLIENTS+ .iter()+ .any(|&kw| ua.contains(kw))+ });- is_authorized_web_client || is_authorized_mobile_client+ is_authorized_web_client || is_authorized_mobile_or_desktop_client}fn parse_domain(url: Option<&str>) -> Option<String> {@@ -380,7 +384,7 @@ mod tests {}#[test]- fn test_on_permitted_domain_mobile_user_agent() {+ fn test_on_permitted_domain_mobile_and_desktop_user_agent() {let domains = vec!["https://web-only.com".to_string()];for ua in [@@ -388,12 +392,13 @@ mod tests {"posthog-ios/2.0.0","posthog-react-native/1.0.0","posthog-flutter/1.0.0",+ "posthog-unity/1.0.0",] {let mut headers = HeaderMap::new();headers.insert("User-Agent", ua.parse().unwrap());assert!(on_permitted_domain(&domains, &headers),- "Expected mobile UA '{ua}' to be permitted"+ "Expected mobile or desktop UA '{ua}' to be permitted");}}