API Route
The plugin needs a Next.js API route to securely fetch data from the Google Analytics Data API.
Why an API route? The plugin's dashboard runs in the browser but needs to authenticate with Google using a private key. The API route acts as a secure backend proxy — it handles authentication and fetches GA4 data without exposing your credentials to the client.
Next.js App Router
Create the file app/api/analytics/route.ts in your Next.js web/frontend package:
export { GET } from 'sanity-plugin-ga-dashboard/api'That's it! The plugin exports a pre-built GET handler that handles everything: authentication, data fetching, and response formatting.
What the API Route Does
The exported GET handler performs the following:
JWT Authentication
Creates a signed JWT using your service account private key, then exchanges it for a Google OAuth access token.
Token Caching
Caches the access token in memory for ~1 hour (with a 60-second buffer), avoiding unnecessary token requests.
16 Parallel GA4 Queries
Executes 16 different GA4 API reports simultaneously using Promise.allSettled() for maximum performance.
Response Caching
Sets HTTP cache headers: 5-minute public cache with 60-second stale-while-revalidate for fast subsequent loads.
Error Resilience
Individual report failures don't break the entire dashboard — failed reports return empty data while others continue working.
Query Parameters
The API route accepts a range query parameter to control the date range:
?range=7Last 7 days?range=14Last 14 days?range=30Last 30 days (default)?range=90Last 90 daysGA4 Reports Fetched
The API handler fetches the following 16 reports in parallel:
Custom API URL
By default, the dashboard fetches from /api/analytics. If your API route is at a different path, configure it in the plugin:
googleAnalyticsPlugin({
apiUrl: '/api/custom-analytics-path'
})Monorepo Setup
In a monorepo (e.g., with studio and frontend), the API route goes in the frontend package since that's where Next.js runs:
your-project/
├── studio/
│ ├── sanity.config.ts ← Plugin registered here
│ └── package.json ← Install plugin here
└── frontend/
│ ├── src/app/api/analytics/
│ │ └── route.ts ← API route here
│ ├── .env.local ← Environment variables here
│ └── package.json ← Install plugin here too
└── package.jsonImportant: Make sure the environment variables (GA_PROPERTY_ID, GA_SERVICE_ACCOUNT_EMAIL, GA_PRIVATE_KEY) are set in the web package's .env.local since that's where the API route runs. See Environment Variables →