Session replay installation

Last updated:

|Edit this page

Session replay enables you to record users navigating through your website or mobile app and play back the individual sessions to watch how real users use your product.

Step one: Install our JavaScript web library

If you already have our JavaScript library or snippet installed, you can skip this step.

Option 1: Add the JavaScript snippet to your HTML Recommended

This is the simplest way to get PostHog up and running. It only takes a few minutes.

Copy the snippet below and replace <ph_project_api_key> and <ph_client_api_host> with your project's values, then add it within the <head> tags at the base of your product - ideally just before the closing </head> tag. This ensures PostHog loads on any page users visit.

You can find the snippet pre-filled with this data in your project settings.

HTML
<script>
!function(t,e){var o,n,p,r;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(".");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement("script")).type="text/javascript",p.crossOrigin="anonymous",p.async=!0,p.src=s.api_host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",(r=t.getElementsByTagName("script")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a="posthog",u.people=u.people||[],u.toString=function(t){var e="posthog";return"posthog"!==a&&(e+="."+a),t||(e+=" (stub)"),e},u.people.toString=function(){return u.toString(1)+".people (stub)"},o="init capture register register_once register_for_session unregister unregister_for_session getFeatureFlag getFeatureFlagPayload isFeatureEnabled reloadFeatureFlags updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures on onFeatureFlags onSessionId getSurveys getActiveMatchingSurveys renderSurvey canRenderSurvey getNextSurveyStep identify setPersonProperties group resetGroups setPersonPropertiesForFlags resetPersonPropertiesForFlags setGroupPropertiesForFlags resetGroupPropertiesForFlags reset get_distinct_id getGroups get_session_id get_session_replay_url alias set_config startSessionRecording stopSessionRecording sessionRecordingStarted captureException loadToolbar get_property getSessionProperty createPersonProfile opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing clear_opt_in_out_capturing debug".split(" "),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);
posthog.init('<ph_project_api_key>', {api_host: 'https://us.i.posthog.com', person_profiles: 'identified_only'})
</script>

Once the snippet is added, PostHog automatically captures $pageview and other events like button clicks. You can then enable other products, such as session replays, within your project settings.

ES5 Support

If you need ES5 support for example to track Internet Explorer 11 replace /static/array.js in the snippet with /static/array.full.es5.js

Option 2: Install via package manager

yarn add posthog-js

And then include it in your files:

Web
import posthog from 'posthog-js'
posthog.init('<ph_project_api_key>', { api_host: 'https://us.i.posthog.com', person_profiles: 'identified_only' })

If you don't want to send test data while you're developing, you can do the following:

Web
if (!window.location.host.includes('127.0.0.1') && !window.location.host.includes('localhost')) {
posthog.init('<ph_project_api_key>', { api_host: 'https://us.i.posthog.com', person_profiles: 'identified_only' })
}

If you're using React or Next.js, checkout our React SDK or Next.js integration.

Advanced option - bundle all required extensions

By default, the PostHog JS library will only load the core functionality, lazy-loading extensions such as Surveys or the Session Replay 'recorder' when needed. This can cause issues if you have a Content Security Policy (CSP) that blocks inline scripts or if you want to optimize your bundle at build time to ensure all dependencies are ready immediately. In addition environments like the Chrome Extension store will reject code that loads remote code. To solve this issue we have multiple import options available.

Please note - with any of the no-external options, the Toolbar will be unavailable as this is only possible as a runtime dependency loaded directly from us.posthog.com

Web
// No external code loading possible (this disables all extensions such as Replay, Surveys, Exceptions etc.)
import posthog from 'posthog-js/dist/module.no-external'
// No external code loading possible but all external dependencies pre-bundled
import posthog from 'posthog-js/dist/module.full.no-external'
// All external dependencies pre-bundled and with the ability to load external scripts (primarily useful is you use Site Apps)
import posthog from 'posthog-js/dist/module.full'
// Finally you can also import specific extra dependencies
import "posthog-js/dist/recorder"
import "posthog-js/dist/surveys"
import "posthog-js/dist/exception-autocapture"
import "posthog-js/dist/tracing-headers"
import "posthog-js/dist/web-vitals"
import posthog from 'posthog-js/dist/module.no-external'
// All other posthog commands are the same as usual
posthog.init('<ph_project_api_key>', { api_host: 'https://us.i.posthog.com', person_profiles: 'identified_only' })

NOTE: You should ensure if using this option that you always import posthog-js from the same module, otherwise multiple bundles could get included. At this time posthog-js/react does not work with any module import other than the default.

Step two: Enable session recordings in your project settings

Enable session recordings in your PostHog Project Settings.

Enable session recordings in your PostHog'

Once enabled, the library will start recording sessions by default.

They can be toggled off in the by setting the disable_session_recording: true flag in the config.

Users who opt out of event capturing will not have their sessions recorded.

Note on using Segment's SDK: Session Replay does not work if you send data using Segment's SDK as this data is not collected. If you use Segment, you may want to add the PostHog library as well – (make sure to only send regular event data from one source).

How to ignore sensitive elements

You may want to hide sensitive text or elements in your replays. See our privacy controls docs for how to do this.

How to record sessions across different domains

PostHog automatically captures sessions across subdomains (e.g. posthog.com and us.posthog.com), but recording sessions across different domains (e.g. posthog.com and hogflix.com) requires a bit more setup.

To do this, you need to pass the session_id from the first domain to the second domain (for example, as a URL parameter). You can get this value by calling posthog.get_session_id().

Below is an example of how this looks like in Next.js:

JavaScript
// first domain
'use client'
import { usePostHog } from 'posthog-js/react'
export default function FirstDomain() {
const posthog = usePostHog()
return (
<div>
<h1>Welcome to the first domain</h1>
<button onClick={
() => window.location.href = `https://seconddomain.com/?session_id=${posthog.get_session_id()}`
}>
Go to the second domain
</button>
</div>
)
}

On the second domain, bootstrap the PostHog initialization using the session ID.

JavaScript
// second domain
'use client'
import posthog from 'posthog-js'
import { PostHogProvider } from 'posthog-js/react'
import { useSearchParams } from 'next/navigation'
export function PHProvider({ children }) {
const searchParams = useSearchParams()
const sessionId = searchParams.get('session_id')
if (typeof window !== 'undefined') {
posthog.init('<ph_project_api_key>', {
api_host: 'https://us.i.posthog.com',
bootstrap: {
sessionID: sessionId
}
})
}
return <PostHogProvider client={posthog}>{children}</PostHogProvider>
}

With this setup, PostHog tracks the user's session across domains and captures a single, combined replay.

Questions?

  • Yonatan
    2 days ago

    Black screen on session replays in the past 3 days

    All of the replays looks just black screen from the past 3 days. we did added cloudfront, might be related? also and we are using local proxy for sending the requests to posthog (using react router v7 framework mode), but its been a few weeks with the proxy and everything worked as expected.

  • Andreas
    13 days ago

    Broken on M1 Pro Mac after version 1.0.0

    MacOS Sonoma 14.7.2 on an Apple M1 Pro.

    I am unable to build my Expo/React Native project when using posthog-react-native-session-replay version 1.0.2 or 1.0.3. Version 1.0.0 works. I am getting the error below when building locally, but it works to build on EAS.

    --- xcodebuild: WARNING: Using the first of multiple matching destinations: { platform:iOS Simulator, id:575932BE-0EB5-498E-8869-CF963E8C3C1C, OS:17.5, name:iPhone SE (3rd generation) } { platform:iOS Simulator, id:575932BE-0EB5-498E-8869-CF963E8C3C1C, OS:17.5, name:iPhone SE (3rd generation) } ** BUILD FAILED **

    The following build commands failed: SwiftEmitModule normal arm64 Emitting\ module\ for\ posthog_react_native_session_replay (in target 'posthog-react-native-session-replay' from project 'Pods') SwiftCompile normal arm64 /node_modules/posthog-react-native-session-replay/ios/PosthogReactNativeSessionReplay.swift (in target 'posthog-react-native-session-replay' from project 'Pods') Building workspace AppName with scheme AppName and configuration Debug (3 failures)

    • Andreas
      Authora day agoSolution

      Sorry about the late reply. I had to do a full reinstall of my Mac for unrelated reasons, and it seems to work again now. Must've been some sort of cache issue i suppose. Although non of the cache pruning flags/commands worked.

  • Tal
    22 days ago

    Mask images

    How do I mask images in session recordnig?

  • Tal
    22 days ago

    Mask Images

    Is it possible to mask images in session recording?

    • Chris
      21 days ago

      Hey Tal,

      Only text or input elements are masked automatically. You can add the CSS class name ph-no-capture to the images which should not be recorded. A block of the same size of the image will appear when you play back the recordings.

      Example HTML:

  • Ilo
    a month ago

    Disable session recording on Sensitive screens

    How do I disable session recording on some sensitive screens of my Flutter app? We wouldn't want to see or record the user password on login screen when he is typing.

  • Andreas
    a month ago

    Redacted data showing

    We are testing out posthog-react-native-session-replay ^0.1.9 and we noticed that redacted data isn't actually redacted during some animations. The black rectangles stays in place while the screen itself is moving. Is this a known issue? Not being able to redact data properly makes it hard to use the feature in accordance with GDPR

    • Manoel(he/him)
      a month ago

      Thanks, I've created this issue and Ioannis will take a look shortly.

  • Shehan
    a month ago

    Can we block specific pages in session recording?

    In my React Native app, I need to block certain pages, such as the payment page, from being recorded. How can I prevent session recording on specific pages in my app?

    • Manoel(he/him)
      a month ago

      Hello, sadly, this is not possible right now; check out this issue that would give you the ability to start/stop recording whenever you want; please upvote so we can eventually prioritize it.

      You can though, mask all sensitive components in the payment page

  • Robin
    2 months ago

    PostHogAndroid can't SessionReplay when instantiated using with()

    I'm working with PostHogAndroid and I have session replay and events setup. I noticed I was not getting any session replays if I instantiated PostHogAndroid using the with() function provided in the SDK. Is there anyway to get around this, I'd like to not refactor our analytics service in order to accommodate session replays.

  • Jayven
    2 months ago

    Wireframe mode for React Native

    Hi, I'm working on implementing session replay in a React Native app and noticed that while Android and iOS support wireframe mode, Ract Native doesn't. May I know what's the reason for this?

    Going into the implementation via RN, I assume that it uses the Android and iOS SDKs to power it. Some clarifications on how this SDK is implemented would be great and whether the wireframe mode is in the pipeline for RN (performance is important for mobile as the beautiful blog post written pointed out by PostHog).

    Thank you!

  • Nilanjan
    2 months ago

    'react/renderer/animations/primitives.h' file not found

    Hi, I'm encountering an issue while integrating session replay into my app. After installing posthog-react-native-session-replay and building the app, I get the error: 'react/renderer/animations/primitives.h' file not found. I'm using Expo prebuild. Has anyone faced a similar issue or have any insights on how to resolve this?!Group 1.png

    • Ioannis
      2 months ago

      Hey Nilanjan,

      Apologies for that! Please see this related issue here.

      Make sure that you are on version 0.1.9 for posthog-react-native-session-replay plugin, and the build errors should be resolved.

      We are currently working on a proper fix for this which should be out soon.

      Best, Ioannis

  • Zeeshan
    2 months ago

    Start/Stop session recording functions not available for React Native SDK

    Hi, is there any way to enable/disable session recording manually via posthog for React native SDK.

    https://posthog.com/tutorials/limit-session-recordings

    The functions mentioned here are not available in React Native SDK.

    • Manoel(he/him)
      2 months ago

      Hello,

      Not yet, there's an issue here already, feel free to upvote so we can eventually prioritize it.

      Thanks, Manoel

  • Akshay
    3 months ago

    PostHog Debug Session replay session id not rotated, sessionId 019xxxxxxxxxxxx01 and currentSessionId undefined.

    import React, { useEffect } from "react"; import { Stack } from "expo-router"; import { SafeAreaProvider } from "react-native-safe-area-context"; import { useRouter } from "expo-router"; import { AuthProvider, useAuth } from "../src/context/auth"; import { ActivityIndicator, AppState, View } from "react-native"; import { ThemeProvider } from "./ThemeContext"; import { usePostHog, PostHogProvider } from 'posthog-react-native'

    function RootLayoutNav() { const { isLoggedIn, token, isLoading } = useAuth(); const router = useRouter();

    useEffect(() => { if (!isLoading) { if (isLoggedIn && token) { router.replace("/(home)/home"); } else { router.replace("/(auth)/login"); } } }, [isLoggedIn, token, isLoading, router]);

    if (isLoading) { return ( <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}> ); }

    return ( <Stack screenOptions={{ headerShown: false }}> <Stack.Screen name="(auth)" /> ); }

    export default function RootLayout() {

    const posthog = usePostHog();

    useEffect(() => { const handleAppStateChange = (nextAppState) => { if (nextAppState === 'active') { posthog?.capture('App Became Active'); } else if (nextAppState === 'background') { posthog?.flush(); } };

    const subscription = AppState.addEventListener('change', handleAppStateChange);
    return () => {
    subscription.remove();
    };

    }, [posthog]);

    return ( <PostHogProvider apiKey="phc_5I....kjj" options={{ host: 'https://us.i.posthog.com', enableSessionReplay: true, }} autocapture={true} debug >

    • Tim
      2 months ago

      The fix is in 3.6.2 of posthog-react-native. Get the latest and you should be good. If you do want to see more info btw, then you can set debug to true in the PostHogProvider.

  • Yarik
    4 months ago

    Session recording

    I use a paid subscription. • How can I increase the session replay retention to one year? • I know that I can download a session using the specific API, but my question is: how can I replay this session? For instance, if I download the session from the API and save it in my database, how can I replay it later?

  • Naresh
    4 months ago

    Activity logs but not able see the recordings

    I have disabled the recording session for my project, but I am unable to see the recording session. I got the message "Recording not found. It might be lost in space." I am not able to figure out what to do. Could you please help me understand what I did wrong?

    • Naresh
      Author4 months agoSolution

      Sorry Correction --> recording session is unabled even i am not able to see the recordings.

    • 4 months ago
      This answer was marked as unhelpful and is only visible to you.

      To enable session recordings, you need to follow these steps:

      1. First, ensure session recordings are enabled in your PostHog Project Settings (1)

      2. Make sure disable_session_recording is not set to true in your PostHog initialization. Here's how to properly initialize with recordings enabled:

      posthog.init('<ph_project_api_key>', {
      api_host: 'https://us.i.posthog.com',
      disable_session_recording: false,
      })

      (1)

      1. Verify your domain is added to the authorized domains list in your project settings (2)

      If you're still not seeing recordings after these steps, check that:

      • Users haven't opted out of event capturing (users who opt out won't have their sessions recorded) (1)
      • You're not using Segment's SDK (Session Replay doesn't work with Segment's SDK) (1)

      If you need more specific control over which sessions to record, you can use features like:

      • URL trigger conditions (2)
      • Event trigger conditions (2)
      • Feature flags (2)
      • Sampling (2)
  • Ross
    4 months ago

    Session Replay's Not working

    Hi, I followed the setup guide to enable session replays in our expo react native app and enabled session replays in our posthog project configuration. We have autocapture enabled but mainly use custom events / screen captures. We have installed the session replay package and enabled it within posthog. Then we pushed to test flight and open testing for the play store to test the setup and session recording features, but sadly no session replays have been recorded. I'm wondering if you are able to help me understand why the sessions are not being recorded in the app.

    If I can provide any further info let me know. Looking forward to your help!

    • Manoel(he/him)
      4 months agoSolution

      Hello Ross,

      I noticed you are using the RN SDK 3.1.1, as you can see in the linked docs:

      Requires PostHog React Native SDK version >= 3.2.0, and it's recommended to always use the latest version.

      Please upgrade the SDK to the latest version and try again.

      Also, enable the debug mode by calling posthog.debug() and check out the logs, that may help find what is going on, thanks.

  • Eduardo
    5 months ago

    Recordings with custom fonts

    Hello hi! I noticed that the sessions recordings do not load correctly the font used for the website, is there some configuration needed so that we can see the session more in line with the experience of the website? btw amazing product, liking it so far :)

    • Jared
      2 months ago

      Following with the same issue!

  • Guy
    5 months ago

    Is there support for recording electron apps?

    I can send events, but is there an option to record an electron app session?

    • Benjamin
      5 months ago

      i am able to record on development version of my electron app

  • ERICK
    5 months ago

    Session replay react-native web

    Hello

    Is there a plan for session replay to be released for react-native web?

    • Manoel(he/him)
      5 months ago

      Hello, not in the near future but upvote this issue so we can get a feeling if many people would need it.

  • Tyler
    6 months ago

    How to Un-Hide Form Inputs

    We appreciate that PostHog takes privacy seriously - but there are a couple fields in our platform that don't have sensitive information but instead are key configuration settings on our platform - so we need to see what users are typing so we can troubleshoot when it doesn't work. It seems like every user input field in screen recording is censored. How can we modify this? Is it something to do with the "attributes" of the input field in our Website code or is it a setting in PostHog?

    Thanks! Love the product so far!

    • Zeeshan
      2 months ago

      Same question from me regarding Session replay Masking of custom sensitive inputs for React Native.

      "ph-no-capture" is not working is we give autoCapture = true in the Posthog config.

  • Rajiv
    6 months ago

    Is Event Autocapture required for Session Replay?

    Is it possible to use Session Replay if Event Autocapture is disabled?

    • Paul(he/him)
      6 months agoSolution

      Hey Rajiv,

      You can use session replay without autocapture of events.

      If you have autocaptured events you can use them to search for sessions and can see their information alongside the recordings in the inspector

      But you can use them separately!

    • Rajiv
      Author6 months ago

      Hi Paul,

      Good to know. Thank you!

Was this page useful?

Next article

How to watch recordings

To watch recordings, you can visit the Replay page. When watching replays, you can change the playback speed, as well as select the option 'skip inactivity' - this skips parts of the recording where the user was inactive on the page. You can also watch recordings by clicking on any data point in an insight. This opens a list of persons and displays a "watch recording" button if available. This is especially useful in funnels , where you can drill down and watch recordings of users who…

Read next article

PostHog.com doesn't use third party cookies - only a single in-house cookie.

No data is sent to a third party.

Ursula von der Leyen, President of the European Commission