Playwright Browser Session Metadata: Setup and Usage
In this article
Attaching metadata to browser sessions in Playwright allows you to tag specific test runs, browser contexts, or sessions with custom identifiers such as environment names, user IDs, or build numbers. This is primarily achieved by leveraging the browserContext options and integrating with external reporting tools or custom logging wrappers, as Playwright does not have a native "metadata" object that persists inside the browser's internal engine. By associating session data with your test execution, you can filter logs, categorize screenshots, and trace failures back to specific configurations in a CI/CD pipeline.
What You'll Need
- Node.js installed on your local machine or server.
- A Playwright project initialized (
npm init playwright@latest). - A basic understanding of asynchronous JavaScript/TypeScript.
- An optional reporting tool (like Allure or Playwright's built-in HTML reporter) to visualize the metadata.
Step-by-Step
- Define Your Metadata Schema: Before writing code, determine what data points are essential for your session. Common examples include
environment(staging, production),browserType(chromium, firefox),testCaseId, andtimestamp. - Create a Custom Context Wrapper: Since Playwright contexts are isolated, you should create a helper function to launch your browser and context while associating your metadata with that specific instance.
- Implement Context-Level Tagging: When creating a context using
browser.newContext(), you can pass options that act as session metadata, such asuserAgentorviewport. For custom business metadata, store these values in a variable mapped to the context ID. - Integrate with Test Annotations: Use
test.info().annotationsto attach metadata directly to the Playwright test report. This ensures that the metadata is linked to the session results. Example:test.info().annotations.push({ type: 'SessionID', description: 'sess_12345' }); - Pass Metadata to Page Objects: If using the Page Object Model (POM), pass the session metadata into the constructor of your page classes. This allows your page methods to include the metadata in any custom logs or API calls they make.
- Log Session Metadata on Failure: Implement a
test.afterEachhook that checks if a test failed. If it did, log the associated session metadata alongside the screenshot or trace file to make debugging easier. - Export Metadata to External Reports: If using a third-party reporter, use the reporter's API to inject the session metadata into the final XML or JSON output, ensuring the data survives after the browser session is closed.
Common Mistakes
- Confusing Browser and Context: Attempting to attach metadata to the
browserobject rather than thebrowserContext. Metadata should be context-specific because different contexts can represent different users or sessions. - Hardcoding Metadata: Putting environment variables directly in the test scripts. Use a
.envfile or CI environment variables to keep metadata dynamic. - Overloading Annotations: Adding too much verbose data to
test.info().annotations, which can bloat the HTML report and make it difficult to navigate. - Ignoring Context Isolation: Assuming that metadata attached to one page will automatically be available to a new page opened in a different context.
Tips
- Use UUIDs: Generate a Unique Universal Identifier (UUID) for every session. This prevents collisions when running tests in parallel across multiple workers.
- Leverage Fixtures: Create a custom Playwright fixture that automatically attaches the required metadata to every session, reducing boilerplate code in your test files.
- Sync with CI: Map your metadata to your CI build ID (e.g.,
process.env.GITHUB_RUN_ID) to link browser sessions directly to specific code commits. - Conditional Metadata: Only attach heavy metadata (like full system logs) when a specific flag is set (e.g.,
DEBUG=true) to keep report sizes manageable.
Troubleshooting
If your metadata is not appearing in the reports, first verify that you are calling the annotation method inside the test block. Annotations added outside the test scope will not be captured by the reporter.
If you find that metadata is being overwritten during parallel execution, ensure you are not using a global variable to store session data. Instead, use the test` fixture or pass the data through the browserContext object to maintain thread safety.
When metadata is missing from screenshots or traces, remember that Playwright's built-in trace viewer captures the browser state, not your JavaScript variables. You must explicitly name your trace files using the session metadata (e.g., await context.tracing.stop({ path: `trace-${sessionId}.zip` });) to maintain the link.
Frequently Asked Questions
Does Playwright have a built-in metadata object for sessions?
No, Playwright does not have a dedicated metadata property on the browser object. You must use test annotations, custom wrappers, or file-naming conventions to track session data.
Can I send session metadata to the server via headers?
Yes, you can use browser.newContext({ extraHTTPHeaders: { 'X-Session-ID': '123' } }) to attach metadata to every network request made during that session.
Will metadata persist if I restart the browser?
No. Browser contexts are ephemeral. Once the context is closed, any metadata associated with that specific instance in memory is lost unless it has been written to a report or database.
How do I attach metadata to a session in headed mode?
The process is identical for both headed and headless modes. Metadata is handled at the Playwright API level, regardless of whether the browser UI is visible.
Can I use metadata to filter tests in the Playwright reporter?
While the default reporter allows viewing annotations, advanced filtering usually requires a custom reporter or a third-party tool like Allure that can categorize tests based on the attached metadata tags.