GEMINI LABJP
NANOLITE — Nano Banana 2 Lite is here: Google's fastest and most cost-efficient Gemini Image model, made for running lightweight image generation cheaplyOMNIFLASH — Gemini Omni Flash is in public preview, a natively multimodal model that lets enterprises and developers build custom, dynamic video workflowsAGENTS — Managed Agents expand with background: true for async server-side runs and polling, remote MCP server integration, and refreshing credentials across interactionsMEMORY — The Memory Bank IngestEvents API is generally available, decoupling event ingestion from memory generation so you can stream content continuouslyTHROUGHPUT — Provisioned Throughput now lets you submit up to seven pending orders for the same model and regionDEPRECATE — Image generation models shut down on August 17, and the Grok 4.1 family on the Gemini Enterprise Agent Platform on August 20NANOLITE — Nano Banana 2 Lite is here: Google's fastest and most cost-efficient Gemini Image model, made for running lightweight image generation cheaplyOMNIFLASH — Gemini Omni Flash is in public preview, a natively multimodal model that lets enterprises and developers build custom, dynamic video workflowsAGENTS — Managed Agents expand with background: true for async server-side runs and polling, remote MCP server integration, and refreshing credentials across interactionsMEMORY — The Memory Bank IngestEvents API is generally available, decoupling event ingestion from memory generation so you can stream content continuouslyTHROUGHPUT — Provisioned Throughput now lets you submit up to seven pending orders for the same model and regionDEPRECATE — Image generation models shut down on August 17, and the Grok 4.1 family on the Gemini Enterprise Agent Platform on August 20
Articles/Dev Tools
Dev Tools/2026-04-08Intermediate

Auto-Diagnose and Optimize Core Web Vitals with the Gemini API

Learn how to use the Gemini API to automatically diagnose and improve Core Web Vitals (LCP, CLS, INP). Fetch PageSpeed Insights data, send it to Gemini, and get actionable code-level optimization suggestions.

gemini102core-web-vitalsseo3web-performancelcpclsinppagespeed

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.

Share

Thank You for Reading

Gemini Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.

  • Copy-paste ready implementation code
  • New advanced guides published daily
  • $5/mo or $10 for lifetime access
View Membership →

If you found this article helpful, a small tip ($1.50) would mean a lot to us. Your support helps keep this site ad-free and covers server and hosting costs.

Related Articles

Dev Tools2026-07-02
After the One-Click Deploy — Hardening an AI Studio Gemini App on Cloud Run for Real Production Use
AI Studio's one-click deploy to Cloud Run gives you a working URL in minutes — but not a production service. A practical checklist for API key storage, authentication, cost ceilings, and observability, with copy-paste gcloud commands.
Dev Tools2026-06-30
Tracing Which Prompt Revision Moved Your Quality — Prompt Versioning for a Gemini Pipeline
Editing prompts in place erases the trail: when quality shifts you can't tell whether the model moved or your wording did. Here's a small system that pins prompts by content hash, stamps every generation with the model ID and revision, and bisects a quality drop down to the exact revision boundary, with copy-paste Python.
Dev Tools2026-06-17
Running Gemini Chat History on Redis — Field Notes on Not Losing Conversation State in Production
Keep a Gemini ChatSession in process memory and it evaporates on every redeploy or scale event. Here is how I back it with Redis in production, covering token budgets, concurrent sends, SDK coupling, and graceful degradation, with the code I actually run.
📚RECOMMENDED BOOKS
Build a Large Language Model (From Scratch)
Sebastian Raschka
LLM Dev
Prompt Engineering for LLMs
Berryman & Ziegler
Prompting
AI Engineering
Chip Huyen
AI Eng
* Contains affiliate links
See all →