Monitoring Performance with the PageSpeed Insights API
Tags: pagespeedinsights, webperf, monitoring, webdev
Published: 2020-01-06 17:57:42

---
title: Monitoring Performance with the PageSpeed Insights API
published: true
description: The PageSpeed Insights API provides free access to performance monitoring for web pages and returns data with suggestions for how to improve.
tags:
  - pagespeed insights
  - web performance
  - monitoring
cover_image: https://thepracticaldev.s3.amazonaws.com/i/pcz7jyevnnr0p04pom6w.png
---

The [PageSpeed Insights API](https://developers.google.com/speed/docs/insights/v5/get-started) provides free access to performance monitoring for web pages and returns data with suggestions for how to improve. The V5 API includes lab data from [Lighthouse](https://developers.google.com/web/tools/lighthouse/) and real-world data from the [Chrome User Experience Report](https://developers.google.com/web/tools/chrome-user-experience-report/) (CrUX).

```js
const url = 'https://wordpress.org';
const apiCall = `https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=${url}`;
const response = await fetch(apiCall);
const json = await response.json();
```

Teams use the API to build dashboards, custom reports and custom integrations with other user-experience measurement tools. The [responses](https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=https://web.dev) from the API could be used to monitor and graph any of the data from the [PageSpeed Insights](https://developers.google.com/speed/pagespeed/insights/) (PSI) tool:

![pagespeed insights v5 report](https://thepracticaldev.s3.amazonaws.com/i/u4qdum9zuzpegcgfd5ub.png)

<table>
    <tbody>
        <tr>
            <td width="50%"><img alt="psi-score" src="https://thepracticaldev.s3.amazonaws.com/i/57akesqxqn34287w0t6t.png" width="100px"></td>
            <td>The PSI score (<strong>json.lighthouseResult.categories.performance.score</strong>) is determined by running Lighthouse to analyze lab data about the page. A score at or above 90 is considered fast and below 50 is considered to be slow. See the <a href="https://developers.google.com/speed/docs/insights/v5/about">FAQ</a> for the latest on scoring and <a href="http://bit.ly/perf-variance">bit.ly/perf-variance</a> to learn about score variance.</td>
        </tr>
        <tr>
            <td width="50%"><img alt="psi fcp" src="https://thepracticaldev.s3.amazonaws.com/i/79cwcgeaqgpxe31rm24p.png"></td>
            <td>If available, PSI will report field metric values (<strong>json.loadingExperience.metrics</strong>) for First Contentful Paint and First Input Delay data from the Chrome User Experience Report for the origin or page URL.</td>
        </tr>
        <tr>
            <td><img alt="psi lab" src="https://thepracticaldev.s3.amazonaws.com/i/fcistgkvi0g8eejdwvq0.png"></td>
            <td>PSI uses Lighthouse to analyze a URL, generating a performance score that factors in a number of different metrics in a lab setting, like Time to Interactive (<strong>json.lighthouseResult.audits['interactive']</strong>). </td>
        </tr>
        <tr>
            <td><img alt="psi opportunities" src="https://thepracticaldev.s3.amazonaws.com/i/ndzeuvsbolityvaqk5ut.png"></td>
            <td>The Lighthouse report opportunities (e.g <strong>json.lighthouseResult.audits['uses-rel-preload']</strong>, <strong>json.lighthouseResult.audits['offscreen-images']</strong> etc.) provide suggestions how to improve the page’s performance metrics.</td>
        </tr>
        <tr>
            <td><img alt="psi opportunities" src="https://thepracticaldev.s3.amazonaws.com/i/99bh4bdevelrr8hwc2ft.png"></td>
            <td>Thumbnail screenshots from the load of your site are available as base64 images via <strong>json.lighthouseResult.audits['screenshot-thumbnails']</strong>. The last screenshot from pageload is available via <strong>json.lighthouseResult.audits['final-screenshot']</strong>.</td>
        </tr>
    </tbody>
</table>

It's possible to build highly customized reports using PSI data. e.g VRBO, a vacation rentals site, graph real-world data from the PSI API to [track long term performance trends](https://youtu.be/iaWLXf1FgI0?t=650) to ensure their speed remains competitive within the travel industry:

![pagespeed insights rum](https://thepracticaldev.s3.amazonaws.com/i/s4zq6yupk51po85vyyzh.png)


[web.dev/measure](https://web.dev/measure) uses the exact same backend as PageSpeed Insights and uses this data for historical measurement over time:

![web.dev/measure](https://thepracticaldev.s3.amazonaws.com/i/oys8cnrq2mp7mt33i0ux.png)

It's helpful to become familiar with the [structure of the PSI API response](https://developers.google.com/speed/docs/insights/v5/reference/pagespeedapi/runpagespeed#response). There's extensive metrics info available for lab and field/real-world:

```js
const url = 'https://wordpress.org';
const apiCall = `https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=${url}`;
fetch(apiCall)
  .then(response => response.json())
  .then(json => {
      // Real-world metrics
      const cruxMetrics = {
      "First Contentful Paint": json.loadingExperience.metrics.FIRST_CONTENTFUL_PAINT_MS.category,
      "First Input Delay": json.loadingExperience.metrics.FIRST_INPUT_DELAY_MS.category
      };
      // Lab metrics
      const lighthouse = json.lighthouseResult;
      const lighthouseMetrics = {
      'First Contentful Paint': lighthouse.audits['first-contentful-paint'].displayValue,
      'Speed Index': lighthouse.audits['speed-index'].displayValue,
      'Time To Interactive': lighthouse.audits['interactive'].displayValue,
      };
      // ...
});
```

Responses from the PSI API are focused on performance data. That said, you can supply the `?category` argument to specify any additional Lighthouse audit categories you would like data for:

```sh
curl -i "https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=https://web.dev&category=pwa&category=performance&category=accessibility&category=best-practices&category=seo"
```

You can also supply a `locale` or `strategy` argument (`desktop` or `mobile` - which simulates a page load on a median-class device (Moto G4) on a mobile network).

Lighthouse is starting to support [Stack Packs](https://developers.google.com/web/updates/2019/01/lighthouse-platform-packs) - stack-specific recommendations, providing more detailed guidance on how to implement optimizations (e.g WordPress). PSI's API responses also support this so if you're testing a WordPress site, these strings are included ([demo URL for wordpress.org](https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=https://wordpress.org)):

![pagespeed insights wordpress](https://thepracticaldev.s3.amazonaws.com/i/rv6y90wcbt16ud92gx0m.png) 

The PageSpeed Insights Tool also supports fetching PSI API data and rendering it with our official [Lighthouse Viewer](https://googlechrome.github.io/lighthouse/viewer). Pass `?psiurl` as a [parameter](https://googlechrome.github.io/lighthouse/viewer/?psiurl=https://web.dev&category=accessibility&category=performance&category=pwa&category=best-practices&category=seo) to see this in action:

![pagespeed insights lighthouse viewer](https://thepracticaldev.s3.amazonaws.com/i/l123uat6nwv58zpag8fe.png)

One of the tools we built on top of PSI is the [psi](https://github.com/GoogleChromeLabs/psi) Node module, offering convenient performance reporting in your build process.

```js
const psi = require('psi');

(async () => {
  // Get the PageSpeed Insights report
  const { data } = await psi('https://web.dev');
  console.log('Speed score:', data.lighthouseResult.categories.performance.score);

  // Output a formatted report to the terminal
  await psi.output('https://theverge.com');
  console.log('Done');
})();
```

The output of `psi` looks a little like this when used as a CLI with PageSpeed Insights V5:

![pagespeed insights node module build process output](https://thepracticaldev.s3.amazonaws.com/i/jzygdf3q2mzov4d5phr3.png)

To try out the PSI API, check out this [Glitch demo](https://glitch.com/~psi-demo) using both Lighthouse and CrUX data.

![pagespeed insights live demo](https://thepracticaldev.s3.amazonaws.com/i/nlizibqpkipterbkf8gx.png)

You can also use [Google Sheets](https://sheets.google.com) and a cron job to automate monitoring multiple URLs (e.g competitors) by regularly pinging the PSI API. A handy [guide](https://dev.to/chromiumdev/a-step-by-step-guide-to-monitoring-the-competition-with-the-chrome-ux-report-4k1o) and sheet you can copy are available.

![pagespeed insights google sheets](https://thepracticaldev.s3.amazonaws.com/i/nnuhaxf3hjaxabktyz63.png) 

## What about third-party resources?

We know third-party scripts are costly. In the top 4 million sites, [~2700 origins](https://github.com/patrickhulce/third-party-web) are responsible for ~57% of all script execution time. Lighthouse exposes an impact summary for third-party code, available via the API from <strong>json.lighthouseResult.audits['third-party-summary']</strong>.

<img src="https://thepracticaldev.s3.amazonaws.com/i/931ppc3mh0pvgli0wm6q.png">

## PageSpeed Insights API Limits

For infrequent usage, the PSI API functions without an API key. 

If you intend to make multiple queries per second however, it is recommended to sign up for a PSI [API key](https://developers.google.com/speed/docs/insights/v5/get-started). API keys have a daily limit of 25,000 queries a day or 400 queries per 100 seconds. This should be enough for most dashboarding needs. It is also possible to request a higher quota if needed.

<img width="75%" src="https://thepracticaldev.s3.amazonaws.com/i/hvzzw6hmt5g1qynsqk6w.png" alt="pagespeed insights api limits"/>

## What's next for the PSI API?

We hope to bring metrics like [Largest Contentful Paint](https://web.dev/lcp/) and [Cumulative Layout Shift](https://web.dev/cls/) to Lighthouse, CrUX and PageSpeed Insights in 2020. We may also explore better hosted API options for obtaining field-data from CrUX. In the interim, you may be interested in [Crux.run](https://crux.run/), a fast mirror of CrUX reporting data which also has an API. 

## Additional reading

* [How PageSpeed Works - Calibre Blog](https://calibreapp.com/blog/how-pagespeed-works)
* [Why is my Lighthouse score different from PSI? - DebugBear](https://www.debugbear.com/blog/why-is-my-lighthouse-score-different-from-pagespeed-insights)
* [PageSpeed Insights Monitoring - Treo](https://medium.com/@treo/pagespeed-insights-monitoring-4109c9c01a10)
* [Automate Google PageSpeed Insights with Apps Script](https://ithoughthecamewithyou.com//post/automate-google-pagespeed-insights-with-apps-script)
* [Monitoring the competition with the Chrome UX Report](https://dev.to/chromiumdev/a-step-by-step-guide-to-monitoring-the-competition-with-the-chrome-ux-report-4k1o)
* [What's in the PageSpeed score?](https://medium.com/expedia-group-tech/whats-in-the-google-pagespeed-score-a5fc93f91e91)
* [Treo Lighthouse field performance plugin](https://github.com/treosh/lighthouse-plugin-field-performance) (uses the API)

*With thanks to Shane Exterkamp for his review*