When your site has dozens of pages, running PageSpeed manually for each one isn’t practical. With PageSpeed Insights API v5, you can automatically measure your entire site’s performance, generate reports, and trigger measurements with one click from your admin panel.
Auto
Full-site measurement
Markdown
Report generation
One-click
Admin UI
Free
API cost
1API Key Setup
PageSpeed Insights API uses an API key from Google Cloud Console. You can call it without a key, but the daily quota is very limited—get a key.
API Key Provisioning Steps
Go to Google Cloud Console and create a project
Navigate to APIs & Services → Library, search 'PageSpeed Insights API' and enable it
Go to APIs & Services → Credentials, select 'Create Credentials → API key'
Store the API key in an environment variable (PAGESPEED_API_KEY)
For security, restrict the API key by HTTP referrer or IP
Never hardcode your API key
Always store API keys in environment variables and keep them out of Git. Exposed keys let others drain your quota.
2API Call Implementation
PageSpeed Insights API v5 is a REST API. Pass a URL and strategy (mobile/desktop) as parameters and it returns Lighthouse-based performance data as JSON.
lib/pagespeed.ts — API call function
interface PageSpeedResult {
url: string;
strategy: "mobile" | "desktop";
scores: {
performance: number;
accessibility: number;
bestPractices: number;
seo: number;
};
metrics: {
fcp: string; // First Contentful Paint
lcp: string; // Largest Contentful Paint
cls: string; // Cumulative Layout Shift
tbt: string; // Total Blocking Time
};
}
export async function measurePageSpeed(
url: string,
strategy: "mobile" | "desktop" = "mobile"
): Promise<PageSpeedResult> {
const apiKey = process.env.PAGESPEED_API_KEY;
const apiUrl = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed"
+ `?url=${encodeURIComponent(url)}`
+ `&strategy=${strategy}`
+ `&key=${apiKey}`
+ "&category=performance&category=accessibility"
+ "&category=best-practices&category=seo";
const res = await fetch(apiUrl);
const data = await res.json();
const categories = data.lighthouseResult.categories;
const audits = data.lighthouseResult.audits;
return {
url,
strategy,
scores: {
performance: Math.round(categories.performance.score * 100),
accessibility: Math.round(categories.accessibility.score * 100),
bestPractices: Math.round(categories["best-practices"].score * 100),
seo: Math.round(categories.seo.score * 100),
},
metrics: {
fcp: audits["first-contentful-paint"].displayValue,
lcp: audits["largest-contentful-paint"].displayValue,
cls: audits["cumulative-layout-shift"].displayValue,
tbt: audits["total-blocking-time"].displayValue,
},
};
}| Score Range | Rating | Meaning |
|---|---|---|
| 90-100 | Good | Excellent performance |
| 50-89 | Needs Improvement | Optimization recommended |
| 0-49 | Poor | Immediate action needed |
3Sequential Full-Site Measurement
To measure every page on your site, you need sequential measurement, not parallel. Each PageSpeed API call takes 20–30 seconds, and parallel calls will burn through your quota quickly.
Sequential full-site measurement
const pages = [
{ url: "https://example.com/", name: "Home" },
{ url: "https://example.com/blog", name: "Blog" },
{ url: "https://example.com/services", name: "Services" },
{ url: "https://example.com/support", name: "Support" },
// ... full page list
];
async function measureAll() {
const results: PageSpeedResult[] = [];
for (const page of pages) {
console.log(`Measuring: ${page.name} (${page.url})`);
try {
const result = await measurePageSpeed(page.url, "mobile");
results.push(result);
console.log(` Performance: ${result.scores.performance}`);
} catch (error) {
console.error(` Failed: ${page.name}`);
}
// Delay between requests to protect quota (3s)
await new Promise(resolve => setTimeout(resolve, 3000));
}
return results;
}Add at least 3 seconds between requests
Each API call runs a full Lighthouse analysis, so responses are slow. Without delays, you’ll hit 429 (Too Many Requests) errors. A 3–5 second gap keeps things stable.
4Markdown Report Generation
Saving results as Markdown makes them easy to commit to Git or share on Slack. A table format gives an at-a-glance view of site-wide performance.
Markdown report generator
function generateMarkdownReport(
results: PageSpeedResult[]
): string {
const date = new Date().toISOString().split("T")[0];
let md = `# PageSpeed Report\n`;
md += `Date: ${date}\n\n`;
md += `| Page | Perf | A11y | BP | SEO | LCP |\n`;
md += `|------|------|------|-----|-----|-----|\n`;
for (const r of results) {
const path = new URL(r.url).pathname || "/";
md += `| ${path} `;
md += `| ${r.scores.performance} `;
md += `| ${r.scores.accessibility} `;
md += `| ${r.scores.bestPractices} `;
md += `| ${r.scores.seo} `;
md += `| ${r.metrics.lcp} |\n`;
}
const avg = results.reduce(
(sum, r) => sum + r.scores.performance, 0
) / results.length;
md += `\n**Average Performance: ${Math.round(avg)}**\n`;
return md;
}Sample Report Output
| Page | Perf | A11y | BP | SEO | LCP |
|---|---|---|---|---|---|
| / | 92 | 100 | 100 | 100 | 1.2s |
| /blog | 88 | 96 | 100 | 100 | 1.8s |
| /services | 76 | 100 | 96 | 100 | 2.4s |
5Admin UI Integration
Embedding PageSpeed measurement in your admin panel lets non-developers check performance status easily. One "Measure All" button scans every page and displays results.
Admin PageSpeed page (simplified)
"use client";
import { useState } from "react";
export default function PageSpeedAdmin() {
const [results, setResults] = useState([]);
const [measuring, setMeasuring] = useState(false);
const [progress, setProgress] = useState("");
const handleMeasure = async () => {
setMeasuring(true);
setProgress("Starting measurement...");
const res = await fetch("/api/admin/pagespeed", {
method: "POST",
});
// Receive progress via Server-Sent Events
const reader = res.body?.getReader();
// ... process results ...
setMeasuring(false);
};
return (
<div>
<h1>PageSpeed Measurement</h1>
<button onClick={handleMeasure} disabled={measuring}>
{measuring ? progress : "Measure All Pages"}
</button>
{/* Results table */}
</div>
);
}Show real-time progress
With 20 pages, measurement takes several minutes. Use Server-Sent Events or polling to show progress like "3/20 measuring: /blog" for better UX.
6Quota Management and Caveats
PageSpeed Insights API is free but has daily quotas. Manage them to prevent excessive calls and maintain stable operation.
| Item | No API Key | With API Key |
|---|---|---|
| Daily quota | ~50 calls | 25,000 calls |
| Per-minute limit | ~5 calls | ~60 calls |
| Response time | 10-30s (depends on page complexity) | |
| Cost | Completely free | |
# Quota protection tips
// 1. Delay between requests (minimum 3s)
await new Promise(r => setTimeout(r, 3000));
// 2. Daily measurement cap
const MAX_DAILY_MEASUREMENTS = 100;
const todayCount = await getTodayMeasurementCount();
if (todayCount >= MAX_DAILY_MEASUREMENTS) {
throw new Error("Daily measurement limit exceeded");
}
// 3. Cache results (prevent duplicate measurements)
const cached = await getCachedResult(url);
if (cached && isRecent(cached, 24)) { // Within 24 hours
return cached;
}Scores vary between runs
PageSpeed scores fluctuate based on network conditions, server load, and CDN cache state. Average 3–5 runs for more accurate results, but only apply multiple runs to critical pages to conserve quota.
Summary Checklist
PageSpeed API Automation Essentials
- ✓Get an API key from Google Cloud Console and store it as an environment variable
- ✓Build an API call function that parses performance, accessibility, and SEO scores
- ✓Measure pages sequentially with at least 3 seconds between requests
- ✓Generate Markdown reports for Git commits or Slack sharing
- ✓Integrate one-click measurement into your admin UI
- ✓Manage daily quotas and cache results to prevent duplicate measurements
This article is based on PageSpeed Insights API v5. API specifications and quota policies may change at Google’s discretion—check the official documentation. Non-commercial sharing is welcome. For commercial use, please reach out via our contact page.
Need Site Performance Optimization?
From building PageSpeed automation tools to performance optimization consulting, Treeru helps you systematically manage your entire site’s performance.
Request Performance Consultation