Analytics
docs

Lighthouse API Route

The plugin proxies requests to the Google PageSpeed Insights API through a Next.js route — keeping your optional API key server-side.

Why a proxy route? The PageSpeed Insights API can be called without an API key, but rate limits are strict. A proxy route lets you add an optional PAGESPEED_API_KEY to lift those limits without exposing the key to the browser.

Next.js App Router

Create the file app/api/pagespeed/route.ts in your Next.js frontend package:

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

The exported GET handler forwards the request to PageSpeed Insights, optionally injects your API key, and caches the response for 5 minutes.

What the Route Does

URL Validation

Requires a url query param. Returns 400 if missing or if strategy is not 'mobile' or 'desktop'.

Category Forwarding

Passes performance, accessibility, best-practices, and seo categories to PageSpeed by default. Override via ?category= params.

Optional API Key

Reads PAGESPEED_API_KEY from the server environment and appends it to the upstream request if present.

Response Caching

Sets Cache-Control: public, s-maxage=300, stale-while-revalidate=60 on successful responses.

Query Parameters

ParamRequiredDescription
urlYesThe full URL to audit, e.g. https://mysite.com/blog/post-1
strategyNo'mobile' (default) or 'desktop'
categoryNoOne or more of: performance, accessibility, best-practices, seo. Defaults to all four.

Environment Variables

PAGESPEED_API_KEYOptional

Google API key with the PageSpeed Insights API enabled. Without it the API still works but is rate-limited to ~25 requests/day.

Get a key at Google Cloud → APIs & Services → PageSpeed Insights API.

.env.local
# .env.local
PAGESPEED_API_KEY=AIzaSy...   # optional but recommended

Custom API URL

The plugin defaults to /api/pagespeed. If you place the route elsewhere, configure it in the plugin:

sanity.config.ts
lighthousePlugin({
  apiUrl: '/api/my-pagespeed',
  siteUrl: 'https://mysite.com',
  documentTypes: [{ type: 'post', slugField: 'slug', pathPrefix: '/blog' }],
})