Analytics
docs

Quick Start

Get GA4 analytics, Search Console, and Lighthouse running in your Sanity Studio in 5 steps.

1. Install the Plugin

Terminal
npm install sanity-plugin-analytics

2. Register in Sanity Config

sanity.config.ts
import { defineConfig } from 'sanity'
import { sanityAnalyticsPlugin } from 'sanity-plugin-analytics'

export default defineConfig({
  name: 'your-project',
  title: 'Your Project',
  projectId: 'your-project-id',
  dataset: 'production',
  plugins: [
    sanityAnalyticsPlugin({
      analytics: {},
      searchConsole: {},
      lighthouse: {
        siteUrl: 'https://yoursite.com',
        documentTypes: [{ type: 'post', slugField: 'slug', pathPrefix: '/blog' }],
      },
    }),
  ],
  schema: {
    types: [/* your schemas */],
  },
})

3. Create the API Route

Create a Next.js API route that the plugin uses to fetch GA4 data:

app/api/analytics/route.ts
export { GET } from 'sanity-plugin-analytics/api/analytics'

4. Set Up Google Cloud

Create a Google Cloud service account and add it to your GA4 property:

1Go to Google Cloud Console → IAM & Admin → Service Accounts
2Create a new service account and generate a JSON key
3Enable the "Google Analytics Data API" in your Google Cloud project
4Go to GA4 → Admin → Property Access Management → add the service account email as Viewer

See the detailed Google Cloud setup guide →

5. Add Environment Variables

.env.local
# .env.local
GA_PROPERTY_ID=123456789
GA_SERVICE_ACCOUNT_EMAIL=my-service-account@my-project.iam.gserviceaccount.com
GA_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\nYOUR_KEY_HERE\n-----END PRIVATE KEY-----\n"

# Search Console (same service account email above)
SEARCH_CONSOLE_SITE_URL=https://yoursite.com

# Lighthouse (optional — lifts rate limit)
PAGESPEED_API_KEY=AIzaSy...

Get these values from your Google Cloud service account JSON key file. See Environment Variables →

That's it! Open your Sanity Studio — you'll see a new “Analytics” tool in the navigation. It contains three tabs: GA4 dashboard (7 views), Search Console (7 views), and Lighthouse (per-page performance scores for mobile and desktop).