sanity-plugin-posthog
v1.0.2
Published
Get posthog analytics right into the sanity studio
Readme
PostHog Analytics Plugin for Sanity
A Sanity Studio plugin that displays PostHog page analytics directly in your CMS.
Features
- 📊 Real-time page analytics for specific pages
- 📈 7-day pageview trends with visual charts
- 🎯 Page-specific metrics (not global analytics)
- ⚡ Direct PostHog integration with HogQL queries
- 🔧 Configurable via environment variables or plugin config
Installation
npm install sanity-plugin-posthogSetup
Option 1: Environment Variables (Recommended)
Create studio/.env.local:
SANITY_STUDIO_POSTHOG_URL=https://us.posthog.com
SANITY_STUDIO_POSTHOG_PROJECT_ID=your-project-id
SANITY_STUDIO_POSTHOG_PERSONAL_API_KEY=phx_your-api-keyOption 2: Plugin Configuration
// sanity.config.ts
import {defineConfig} from 'sanity'
import {PosthogAnalyticsPlugin} from 'sanity-plugin-posthog'
export default defineConfig({
// ...
plugins: [
PosthogAnalyticsPlugin({
posthogUrl: 'https://us.posthog.com',
posthogProjectId: 'your-project-id',
posthogPersonalApiKey: 'phx_your-api-key',
}),
],
})How to Get PostHog Credentials
PostHog URL: Choose your region
- US:
https://us.posthog.com - EU:
https://eu.posthog.com
- US:
Project ID: Found in PostHog Settings > Project
Personal API Key:
- Go to PostHog Settings > Personal API Keys
- Create new key (starts with
phx_)
Usage
To add the analytics view to your document types, use the AnalyticsView component in your document structure:
// structure/index.ts or your document type definition
import {AnalyticsView} from 'sanity-plugin-posthog'
export const pageType = defineType({
name: 'page',
type: 'document',
fields: [
// your fields...
{
name: 'slug',
type: 'slug',
options: {
source: 'title'
}
}
],
// Add analytics view
views: [
{
component: AnalyticsView,
title: 'Analytics'
}
]
})Features
- Shows 7-day pageview data for the specific page
- Displays total views and daily breakdown chart
- Updates in real-time based on your PostHog data
- Works with any document that has a
slugfield
Requirements
- Sanity Studio v3+
- PostHog account with API access
- Document types with
slugfield
Architecture
Following Sanity's best practices:
- Environment variables handled securely
- Plugin accepts configuration object
- Modular structure with proper TypeScript types
- Follows the recommended plugin pattern from Sanity docs
Troubleshooting
"PostHog credentials not configured"
- Ensure your environment variables are set correctly
- Restart your development server after adding
.env.local - Check that your API key starts with
phx_
"No analytics data found"
- Verify your page slug matches the URL path in PostHog
- Check that pageview events are being tracked on your site
- Ensure the document has a
slugfield populated
API Errors
- Verify your PostHog project ID is correct
- Check that your personal API key has the necessary permissions
- Ensure you're using the correct PostHog URL for your region
