Astro

Last updated:

|Edit this page

PostHog makes it easy to get data about traffic and usage of your Astro app. Integrating PostHog into your site enables analytics about user behavior, custom events capture, session recordings, feature flags, and more.

This guide walks you through integrating PostHog into your Astro app using the JavaScript Web SDK.

Installation

In your src/components folder, create a posthog.astro file:

Terminal
cd ./src/components
# or 'cd ./src && mkdir components && cd ./components' if your components folder doesnt exist
touch posthog.astro

In this file, add your Web snippet which you can find in your project settings. Be sure to include the is:inline directive to prevent Astro from processing it, or you will get Typescript and build errors that property 'posthog' does not exist on type 'Window & typeof globalThis'.

posthog.astro
---
// src/components/posthog.astro
---
<script is:inline>
!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+"/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="capture identify alias people.set people.set_once set_config register register_once unregister opt_out_capturing has_opted_out_capturing opt_in_capturing reset isFeatureEnabled onFeatureFlags getFeatureFlag getFeatureFlagPayload reloadFeatureFlags group updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures getActiveMatchingSurveys getSurveys getNextSurveyStep onSessionId".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'
}
)
</script>

The next step is to a create a Layout where we will use posthog.astro. Create a new file PostHogLayout.astro in your src/layouts folder:

Terminal
cd .. && cd .. # move back to your base directory if you're still in src/components/posthog.astro
cd ./src/layouts
# or 'cd ./src && mkdir layouts && cd ./layouts' if your layouts folder doesn't exist yet
touch PostHogLayout.astro

Add the following code to PostHogLayout.astro:

PostHogLayout.astro
---
import PostHog from '../components/posthog.astro'
---
<head>
<PostHog />
</head>

Lastly, update index.astro to wrap your existing app components with the new Layout:

index.astro
---
import PostHogLayout from '../layouts/PostHogLayout.astro';
---
<PostHogLayout>
<!-- your existing app components -->
</PostHogLayout>

Next steps

For any technical questions for how to integrate specific PostHog features into Astro (such as analytics, feature flags, A/B testing, surveys, etc.), have a look at our JavaScript Web SDK docs.

Alternatively, the following tutorials can help you get started:

Questions? Ask Max AI.

It's easier than reading through 563 docs articles.

Community questions

  • Joe
    24 days ago

    Astro + React Project approach

    Hey Posthog team!

    Say if I were to have an astro project that also uses React, what would be the best approach in terms of setting up Posthog? Currently, i have a PostHog client in a .ts file that I am calling in individual components. But i doubt that will scale well.

    Am i able to have a Posthog web snippet in the head of my astro layout component, then use posthog-js in my react components as normal? thanks!

    • Rafael(he/him)
      24 days agoSolution

      Yeah, you can simply call posthog.capture and it'll use the globally configured posthog instance. You don't even need to wait until posthog is finished loading, we'll be able to send the events captured before we actually download our script - thanks to that initializer function :)

  • Erik
    5 months ago

    Posthog tags deleting meta tags

    when is placed after the and another after tag (it only seems to work if open tag) it changes the code when viewed in a browser to delete all the head data (open graph, twitter cards, and other traditional meta tags. Tried placing in body outside body- if its anywhere else, it shows a blank page with just the posthog code visible when viewing source.

    • Ian
      5 months ago

      Can you send an example?

  • Joachim
    6 months ago

    Capture events not working

    I migrated from using posthog.init a top-level tsx to the above setup with astro, but not my posthog.capture events stopped working (all other website clicks, etc. works still). Do I need to initialise twice - or do I have a mistake somewhere?

    • Steven(he/him)
      6 months agoSolution

      Hey Joachim, Could you please open a support ticket for this by using the 'Help' tab in the righthand sidebar while you're logged in? That'll include additional info about your account and configs that will help us to troubleshoot. Thanks!

  • Hk
    9 months ago
    • Marcus
      9 months ago

      Hey, could you share your posthog.init config?

    • Hk
      Author9 months ago

      NVM. The astro one was caused by auto format. My editor auto formats the inline script. Didn't know this could have difference.

      The docusaurus one still doesn't work. I simply followed https://posthog.com/docs/libraries/docusaurus, provided api key and app url to the plugin.

Was this page useful?

Next article

Bubble

PostHog makes it easy to get data about traffic and usage of your Bubble app. Integrating PostHog into your site enables analytics about user behavior, custom events capture, session recordings, feature flags, and more. This guide walks you through integrating PostHog into your Bubble app using the JavaScript Web SDK . Installation First, sign up to PostHog . Then, go to your project settings and copy your web snippet . It looks like this: With the snippet copied, go to your Bubble site…

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