Save Chrome Performance Timelines with Puppeteer
In this article
Saving Chrome performance timelines with Puppeteer allows developers to capture a detailed trace of every event occurring within the browser's engine, including rendering, scripting, and network activity. This process involves utilizing the Chrome DevTools Protocol (CDP) to start a tracing session, executing the desired page interactions, and then stopping the session to export a JSON file. This file can be uploaded directly into the Chrome DevTools Performance tab (chrome://inspect) to visualize bottlenecks, identify long-running tasks, and optimize the Critical Rendering Path.
What You'll Need
- Node.js installed on your local machine (LTS version recommended).
- A project directory initialized with
npm init -y. - The
puppeteerpackage installed vianpm install puppeteer. - A filesystem module (built-in
fs) to save the resulting trace file. - Basic familiarity with asynchronous JavaScript (async/await).
Step-by-Step
- Initialize the Puppeteer Browser: Start by launching a headless or headful browser instance. For performance profiling, it is often better to use
headless: "new"orfalseto ensure the rendering environment closely matches a real user's experience. Create a new page instance within the browser context. - Establish a CDP Session: Puppeteer provides a high-level API, but performance tracing requires the Chrome DevTools Protocol. Use
page.target().createCDPSession()to create a session. This session allows you to send low-level commands directly to the browser engine that are not exposed via the standard Puppeteer page methods. - Define the Tracing Categories: You must tell Chrome exactly what events to record, otherwise the resulting file will be empty or missing critical data. The
Tracing.startTracingmethod accepts acategoriesarray. To get a comprehensive view, include"devtools.timeline","disabled-by-default-scheduling","disabled-by-default-v8", and"blink.user_timing". If you only need network data, you can limit these to reduce the file size. - Start the Tracing Session: Call
await client.send('Tracing.startTracing', { categories: categories }). From this exact moment, the browser begins recording every event in the specified categories. It is crucial to start the trace immediately before the action you wish to measure to avoid capturing unnecessary idle time. - Perform the Page Actions: Navigate to your target URL using
page.goto()or interact with elements usingpage.click()orpage.type(). If you are measuring page load performance, ensure you wait for thenetworkidle0ornetworkidle2event to ensure all asynchronous requests have completed. - Stop the Tracing Session: Once the interactions are complete, call
await client.send('Tracing.stopTracing'). This command stops the recording and returns a promise that resolves to an object containing the trace events. - Extract and Format the Trace Data: The response from
stopTracingcontains an array of events. This data is usually returned as a JSON object. You will need to extract thetraceEventsarray from the response to ensure the file is compatible with the Chrome DevTools viewer. - Save the File to Disk: Use
fs.writeFileSync()to save the JSON data to a file (e.g.,trace.json). UseJSON.stringify(data, null, 2)to ensure the output is properly formatted. - Analyze the Results: Open a fresh Chrome browser window and navigate to
chrome://inspector open the DevTools Performance tab. Click the "Upload" (up arrow) icon and select yourtrace.jsonfile. The browser will then render the timeline, showing you the exact execution flow of the page.
Common Mistakes
One of the most frequent errors is starting the tracing session too early. If you call startTracing before page.goto(), you may capture the overhead of the browser initializing the navigation, which can skew your results. Conversely, stopping the trace before the page has fully settled (e.g., before lazy-loaded images or late-firing scripts have executed) leads to incomplete data.
Another common pitfall is forgetting to include the disabled-by-default categories. Chrome disables high-overhead tracing events by default to preserve performance. If you only use the standard devtools.timeline category, you will miss deep V8 engine insights and detailed scheduling information, leaving you with a superficial timeline that doesn't explain why a frame was dropped.
Developers also often forget to close the browser instance. While the trace file is saved to disk, leaving multiple headless Chrome processes running in the background can consume significant system RAM, eventually slowing down the machine and affecting the timing accuracy of subsequent performance tests.
Tips
To get the most accurate data, always run your performance tests in a "clean" environment. This means using an incognito context or clearing the browser cache and cookies before starting the trace. Cached assets load significantly faster than first-time visits, which can hide critical network bottlenecks.
If you are dealing with a very large page, the trace file can grow to hundreds of megabytes, potentially crashing the DevTools viewer. To mitigate this, be selective with your categories. Instead of using all available categories, identify exactly what you are looking for—such as "v8" for JavaScript execution or "blink" for layout and painting—and only enable those.
For automated regression testing, consider comparing the total duration of the "Main" thread tasks across different versions of your application. While the JSON file is meant for human eyes, you can programmatically parse the traceEvents array to find events with the name RunTask and calculate the sum of their durations.
Troubleshooting
The trace file is empty or contains very few events: This usually happens if the stopTracing command is called too quickly after startTracing, or if the categories provided are misspelled. Double-check that you are using the exact string names for the categories. Also, ensure you are awaiting the page.goto() promise fully before stopping the trace.
Chrome DevTools refuses to load the JSON file: This is typically a formatting issue. The Chrome Performance tab expects an array of events or a specific JSON wrapper. If you saved the entire response object from the CDP session instead of just the traceEvents array, the viewer may fail. Ensure your file starts with [ and ends with ], or follows the JSON trace format specification.
Performance results vary wildly between runs: Performance tracing is sensitive to system load. If your CPU is spiking due to other background applications, the "Main" thread will show artificial delays. To fix this, run your Puppeteer scripts on a dedicated server or a CI runner with consistent resource allocation. Avoid running the browser in headful mode if you are measuring raw execution speed, as rendering the UI adds overhead.
Frequently Asked Questions
Can I capture network requests in the same trace?
Yes, by including the "devtools.timeline" category, network events are captured. However, for more detailed network analysis (like headers and payloads), it is better to use page.on('request') and page.on('response') alongside the trace.
Does headless mode affect the performance timeline?
Yes, headless mode can be faster because it skips some of the GPU-accelerated painting processes. If you are debugging visual jank or layout shifts, run Puppeteer with headless: false to get a more realistic representation of the user's experience.
How do I identify a "Long Task" in the saved JSON?
In the trace events, look for events where the duration exceeds 50ms. In the visual DevTools viewer, these are typically highlighted with a red flag or a red bar at the top of the Main thread section.
Is there a limit to how long a tracing session can run?
There is no hard time limit, but there is a memory limit. Chrome stores trace events in a buffer; if the session runs for too long or captures too many events, the buffer may overflow, causing the browser to crash or the trace to be truncated.
Can I use this to measure Core Web Vitals?
While the trace provides the raw data used to calculate Core Web Vitals (like LCP and CLS), it is easier to use the Puppeteer page.evaluate() method to call the PerformanceObserver API directly within the browser to get these specific metrics.