Why Combining Gemini API with Core Web Vitals Is a Game-Changer
Core Web Vitals — Google's benchmark for page experience — have a direct impact on search rankings. The three key metrics are LCP (Largest Contentful Paint), CLS (Cumulative Layout Shift), and INP (Interaction to Next Paint). Getting all three into the "Good" range is crucial for both SEO and user experience, yet interpreting the raw data from Lighthouse or PageSpeed Insights and knowing exactly what to fix is often far from straightforward.
That's where the Gemini API comes in. By piping your PageSpeed Insights data into Gemini, you can automate the leap from "here are your scores" to "here's the specific code change that will help." In this guide, we'll build a TypeScript script that fetches real-world metrics and generates a prioritized, code-level optimization report using Gemini.
A Quick Refresher on the Three Core Metrics
Before we dive into the implementation, let's revisit what each metric measures and what constitutes a "Good" score.
- LCP (Largest Contentful Paint): Time until the page's largest visible element is rendered. Aim for under 2.5 seconds. Hero images and large text blocks are frequent culprits; image optimization and server response time are the main levers.
- CLS (Cumulative Layout Shift): A score measuring how much page content shifts unexpectedly during load. Keep it below 0.1. Late-loading fonts and dynamically injected content are typical causes.
- INP (Interaction to Next Paint): How quickly the page responds visually after a user interaction (click, tap, etc.). Target under 200ms. Heavy JavaScript and main-thread blocking are primary contributors.
Manually diagnosing all three and producing code recommendations takes time. Let's automate it.
Step 1: Fetch Core Web Vitals from PageSpeed Insights API
The PageSpeed Insights API is free to use and returns field data (real-user measurements) in JSON format. You can generate an API key from the Google Cloud Console.
// pagespeed.ts — Retrieve Core Web Vitals from PageSpeed Insights API
import fetch from "node-fetch";
const PSI_API_KEY = "YOUR_PAGESPEED_API_KEY"; // Replace with your actual key
interface CoreWebVitals {
lcp: number; // seconds
cls: number;
inp: number; // milliseconds
fcp: number; // First Contentful Paint (informational)
ttfb: number; // Time to First Byte (informational)
}
export async function fetchCoreWebVitals(url: string): Promise<CoreWebVitals> {
const endpoint =
`https://www.googleapis.com/pagespeedonline/v5/runPagespeed` +
`?url=${encodeURIComponent(url)}&key=${PSI_API_KEY}&strategy=mobile`;
const res = await fetch(endpoint);
const data = (await res.json()) as any;
const m = data.loadingExperience?.metrics ?? {};
return {
lcp: (m.LARGEST_CONTENTFUL_PAINT_MS?.percentile ?? 0) / 1000,
cls: (m.CUMULATIVE_LAYOUT_SHIFT_SCORE?.percentile ?? 0) / 100,
inp: m.INTERACTION_TO_NEXT_PAINT?.percentile ?? 0,
fcp: (m.FIRST_CONTENTFUL_PAINT_MS?.percentile ?? 0) / 1000,
ttfb: m.EXPERIMENTAL_TIME_TO_FIRST_BYTE?.percentile ?? 0,
};
}
// Example usage: fetchCoreWebVitals("https://example.com").then(console.log)
// Expected output: { lcp: 3.2, cls: 0.18, inp: 240, fcp: 1.8, ttfb: 820 }Step 2: Send the Data to Gemini API for Diagnosis
Once we have the raw metrics, we build a structured prompt and call gemini-2.5-flash — an efficient model that delivers strong analytical quality at low cost.
// analyze.ts — Auto-diagnose Core Web Vitals with the Gemini API
import { GoogleGenAI } from "@google/genai";
import { fetchCoreWebVitals } from "./pagespeed";
const GEMINI_API_KEY = "YOUR_GEMINI_API_KEY";
const client = new GoogleGenAI({ apiKey: GEMINI_API_KEY });
async function analyzeCoreWebVitals(targetUrl: string): Promise<string> {
// Step 1: Retrieve live metrics
const m = await fetchCoreWebVitals(targetUrl);
// Step 2: Build the diagnostic prompt
const prompt = `
You are a web performance optimization expert.
Analyze the Core Web Vitals measurements below and provide:
1. A classification for each metric (Good / Needs Improvement / Poor)
2. The top 3 highest-priority issues with step-by-step fix instructions
3. Concrete code examples (HTML/CSS/JavaScript/Next.js as appropriate)
4. Expected improvement ranges after each fix
## Target URL
${targetUrl}
## Measured Core Web Vitals
- LCP: ${m.lcp.toFixed(2)}s (target: ≤ 2.5s)
- CLS: ${m.cls.toFixed(3)} (target: ≤ 0.1)
- INP: ${m.inp}ms (target: ≤ 200ms)
- FCP: ${m.fcp.toFixed(2)}s (informational)
- TTFB: ${m.ttfb}ms (informational)
`;
// Step 3: Call Gemini
const response = await client.models.generateContent({
model: "gemini-2.5-flash",
contents: [{ role: "user", parts: [{ text: prompt }] }],
});
return response.candidates?.[0]?.content?.parts?.[0]?.text ?? "";
}
// Run it
analyzeCoreWebVitals("https://example.com").then((report) => {
console.log("=== Core Web Vitals Diagnostic Report ===");
console.log(report);
});
/*
Sample output (excerpt):
## Diagnosis
- LCP: 3.20s → Poor (exceeds 2.5s target)
- CLS: 0.180 → Poor (exceeds 0.1 target)
- INP: 240ms → Needs Improvement
## Priority 1 — Fix LCP
Add fetchpriority="high" to your hero image and enable the priority
prop in next/image. Expected improvement: 0.8–1.2 seconds.
<img src="/hero.jpg" fetchpriority="high" ... />
*/Practical Tips for Getting Better Suggestions from Gemini
The richer the context you give Gemini, the more targeted its suggestions will be.
For LCP: Paste your HTML <head> section and the CSS for your hero area into the prompt. Gemini will catch missing <link rel="preload"> tags, incorrectly configured lazy loading, or third-party scripts that delay rendering.
For CLS: Include font-loading configuration and any CSS that involves height: auto on images or videos. Gemini is effective at identifying missing font-display: swap settings and images without explicit dimensions.
For INP: Export a Chrome DevTools performance trace (JSON) and include the long task summary in your prompt. Gemini can pinpoint useEffect hooks that trigger unnecessary re-renders and suggest debouncing or memoization strategies.
If you want to surface these reports as a live dashboard, the patterns from Building an AI Chat App with Gemini API and Next.js map directly onto this use case.
For even deeper optimization work involving automated testing pipelines, the advanced patterns in Gemini Function Calling: Production-Ready Implementation Guide show how to structure multi-step analysis with structured outputs.
Looking back
Core Web Vitals sit at the intersection of SEO and user experience — improving them benefits both search rankings and the people who visit your site. By combining the PageSpeed Insights API with the Gemini API, you can move from raw scores to code-level fixes in a single automated workflow.
Use the script in this article as a starting point and extend it into a scheduled monitoring system or a CI gate to keep your performance regressions in check.
For a broader look at how AI can accelerate your content and SEO work, Gemini for SEO and Content Creation: A Practical Guide is a great next read.