Search Console API Route
The plugin needs a Next.js API route to securely fetch data from the Google Search Console 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 Search Console data without exposing your credentials to the client.
Next.js App Router
Create the file app/api/search-console/route.ts in your Next.js web/frontend package:
export { GET, POST } from 'sanity-plugin-ga-dashboard/search-console-api'That's it! The plugin exports pre-built GET and POST handlers that handle everything: authentication, data fetching, sitemap management, and response formatting.
What the API Route Does
The exported handlers perform the following:
JWT Authentication
Creates a signed JWT using your service account private key, then exchanges it for a Google OAuth access token with Search Console scope.
Token Caching
Caches the access token in memory for ~1 hour (with a 60-second buffer), avoiding unnecessary token requests.
8 Parallel SC Queries
The GET handler executes 8 different Search Console API queries 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 query failures don't break the entire dashboard — failed queries return empty data while others continue working.
Sitemap Management (POST)
The POST handler lets you submit new sitemaps or re-submit existing ones directly from the dashboard.
Query Parameters
The GET handler accepts a range query parameter to control the date range:
?range=7Last 7 days?range=28Last 28 days (default)?range=90Last 90 days?range=180Last 180 daysData Fetched
The GET handler fetches the following 8 reports in parallel:
Custom API URL
By default, the dashboard fetches from /api/search-console. If your API route is at a different path, configure it in the plugin:
searchConsolePlugin({
apiUrl: '/api/custom-search-console-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 ← GA API route
│ │ └── search-console/
│ │ └── route.ts ← SC API route
│ ├── .env.local ← Environment variables here
│ └── package.json ← Install plugin here too
└── package.jsonImportant: Make sure the environment variables (GA_SERVICE_ACCOUNT_EMAIL, GA_PRIVATE_KEY, SEARCH_CONSOLE_SITE_URL) are set in the web package's .env.local since that's where the API route runs. See Search Console Setup →