Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 36 ยท Protocols and APIs

Browser Testing with k6 and Web Vitals

Understand the k6 browser module: drive Chromium with page and locator APIs, read Core Web Vitals, and combine one real browser with many protocol-level users in a hybrid test.

Protocol-level tests (the HTTP, WebSocket and gRPC modules) are cheap and can simulate thousands of users, but they do not execute JavaScript, render pages or paint pixels. The server can answer in 80 ms while the page still feels slow because a huge script blocks the main thread. The k6 browser module adds a real Chromium browser to k6, so you can measure what a person actually sees.

Honesty note. Neither k6 nor Chromium runs on this site, so the browser code below is read-only. The runnable blocks are Node stand-ins that illustrate the measurement ideas (page load as the sum of many requests, and a hybrid test), not the real browser module.

What a browser test looks like

The module's API will feel familiar if you have used Playwright. Every browser action is asynchronous, so the script uses async/await:

JavaScript
import { browser } from 'k6/browser';
import { check } from 'k6';

export const options = {
  scenarios: {
    ui: {
      executor: 'shared-iterations',
      options: { browser: { type: 'chromium' } },
    },
  },
  thresholds: {
    browser_web_vital_lcp: ['p(75)<2500'],
    checks: ['rate==1'],
  },
};

export default async function () {
  const page = await browser.newPage();
  try {
    await page.goto('https://shop.example.test/');

    await page.locator('input[name="q"]').fill('keyboard');
    await Promise.all([
      page.waitForNavigation(),
      page.locator('button[type="submit"]').click(),
    ]);

    const title = await page.locator('h1').textContent();
    check(title, { 'results header shown': (t) => t.includes('keyboard') });
  } finally {
    await page.close(); // always close, or the browser leaks memory
  }
}

Points to notice:

  • The browser is requested in a scenario with browser: { type: 'chromium' } (scenarios and executors are covered in chapter 4 of this course; see also the track overview).
  • page.locator() finds elements lazily and waits for them, so you rarely need manual sleeps.
  • Click-driven navigation is paired with waitForNavigation() inside Promise.all, otherwise the script races ahead of the page.
  • page.close() belongs in finally.
  • You can take screenshots with page.screenshot({ path: 'step1.png' }), which is useful while debugging.

Web vitals and browser metrics

The module records the Core Web Vitals and related timings as k6 metrics:

Metric What it measures
browser_web_vital_lcp Largest Contentful Paint: when the main content appears
browser_web_vital_cls Cumulative Layout Shift: how much the page jumps around
browser_web_vital_inp Interaction to Next Paint: responsiveness after input
browser_web_vital_fcp First Contentful Paint
browser_web_vital_ttfb Time to first byte
browser_http_req_duration Duration of the requests the browser makes

You use them in thresholds exactly like built-in HTTP metrics. Typical "good" targets from the web-vitals guidance are LCP under 2.5 s, INP under 200 ms and CLS under 0.1, measured at the 75th percentile of users.

Why one browser is not a load test

A headless Chromium takes hundreds of megabytes of memory and a lot of CPU. A protocol VU needs a few megabytes. If you try to simulate 1,000 users with 1,000 browsers, your load generator is the bottleneck and the numbers become meaningless. So the browser module is used for two jobs:

  1. Frontend performance checks at low concurrency (a handful of browsers).
  2. Hybrid tests: lots of protocol VUs generate the load, while one or two browser VUs measure the experience of a real user while the system is busy.
flowchart LR
    A["Scenario: api_load<br/>200 protocol VUs"] --> S["System under test"]
    B["Scenario: ui_probe<br/>1 browser VU"] --> S
    S --> M["Metrics:<br/>http_req_duration, LCP, INP"]

A hybrid test: the API scenario creates the load, the browser scenario reports how the page feels.

Node.js Stand-in: page load is many requests, not one

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Hybrid scenarios in practice

In a real script you declare two scenarios that start together. The API scenario uses an executor such as ramping-vus and the browser scenario uses shared-iterations with one VU:

JavaScript
export const options = {
  scenarios: {
    api_load: {
      executor: 'ramping-vus',
      exec: 'api',
      stages: [
        { duration: '2m', target: 200 },
        { duration: '5m', target: 200 },
        { duration: '1m', target: 0 },
      ],
    },
    ui_probe: {
      executor: 'constant-vus',
      exec: 'ui',
      vus: 1,
      duration: '8m',
      options: { browser: { type: 'chromium' } },
    },
  },
  thresholds: {
    'http_req_duration{scenario:api_load}': ['p(95)<400'],
    'browser_web_vital_lcp{scenario:ui_probe}': ['p(75)<3000'],
  },
};

Each scenario's exec names the exported function it runs. Tagging thresholds by scenario keeps the two worlds from contaminating each other's numbers.

Node.js Stand-in: a probe user measured while background load runs

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Practical advice

  • Run browser tests on a machine with enough RAM and CPU, and keep concurrency small (single digits).
  • Use page.waitForSelector or locators, not fixed sleeps.
  • Block irrelevant third-party calls (analytics, ads) with page.route-style filtering when they add noise.
  • Record screenshots on failure only; screenshots on every iteration slow the run.
  • Start with the page that earns the most revenue (home, search, checkout) and one stable user journey.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why can a protocol-level test report fast responses while real users see a slow page?

    A protocol test measures server responses. Script execution, rendering and layout happen in the browser and are invisible to it.
  2. 2. Which metric measures how long the main content takes to appear?

    LCP, Largest Contentful Paint, marks when the main content is painted. CLS is layout shift.
  3. 3. What is the recommended use of the browser module in a load test?

    Browsers are heavy. Use a few for frontend metrics, usually next to protocol scenarios that generate the real load.
  4. 4. Why use Promise.all with waitForNavigation() and a click?

    Starting to wait for the navigation at the same moment as the click guarantees the navigation is not missed.

Summary

  • The browser module drives real Chromium with Playwright-like async APIs.
  • It records web vitals (LCP, CLS, INP, FCP, TTFB) as thresholdable metrics.
  • Browsers are heavy: use few of them, often in a hybrid test next to protocol VUs.
  • Always close pages and tag thresholds per scenario.

Next: Built-in Metrics