Andrea D'Attero
Andrea D'Attero

Reputation: 65

Get web vitals of website using puppeteer and web-vitals in NextJS

I am building a simple tool in NextJS that given a URL executes puppeteer and returns the web vitals however when doing so I can't retrieve the results it doesn't print anything, what could be the reason for this?

const browser = await puppeteer.launch({ headless: false,  });
const website = await browser.newPage();

await website.goto(request.url, {waitUntil: 'networkidle0'});

// inject the web vitals library into the page
await website.addScriptTag({url: 'https://unpkg.com/web-vitals@2/dist/web-vitals.umd.js'});

// listen for web vitals metrics from the page
website.exposeFunction('onReport', ({name, value}: any) => {
    console.log(`${name}: ${value}`);
});

const onReport = (data: any) => {
    console.log(data);
}

await website.evaluate(() => {
    webVitals.getCLS(console.log);
    webVitals.getFID(console.log);
    webVitals.getLCP(console.log);
    webVitals.getTTFB(console.log);
    webVitals.getFCP(console.log);
});

await browser.close();

Upvotes: 0

Views: 730

Answers (1)

Barry Pollard
Barry Pollard

Reputation: 46040

The web-vitals script depends on performance observers that may not fire immediately. In particular LCP is not finalised until there is an interaction on the page, and CLS is not finalised until the end of the page load.

You do use await website.evaluate(()... but that only "awaits" for the setting up of the performance observers. You then immediately close the page.

I would suggest navigating to another page, or moving the page to hidden, rather than calling await browser.close(); immediately afterwards and you may see these being called. This incidentally is what the web-vitals library does itself for it's tests as you can see in the LCP tests or the CLS tests.

Upvotes: 2

Related Questions