What are Playwright Environment Variables?
How to Use Environment Variables in Playwright in 2026
You run a Playwright test locally, and everything works perfectly. Login succeeds, navigation passes, and assertions complete.
Then you run the same test in staging or CI, and it breaks. The base URL is different, credentials have changed, and some API endpoints point to another backend. Fixing it by editing the test works once, but repeats every time the environment changes.
As your test suite grows, maintaining environment-specific values inside the code becomes unmanageable. This is where Playwright env variables help. They let you keep URLs, credentials, API keys, and feature flags outside the test scripts so the same tests run across local, staging, and CI environments.
This guide shows how Playwright env variables work, how to set them up using .env files, process.env, CLI arguments, and CI pipelines, and how to manage multi-environment test execution efficiently.
What Are Playwright Environment Variables
Playwright environment variables are key-value pairs used to store configuration and sensitive information outside your test code. They allow tests to dynamically adapt to different environments without requiring changes to the scripts themselves.
For example, you might store:
- Base URLs for local, staging, or production
- API keys or tokens needed for authentication
- Feature flags or other environment-specific settings
Using environment variables keeps your test code clean, secure, and maintainable, while making it easy to run the same suite across multiple environments.
In Playwright, these variables can be accessed using process.env, injected via CI/CD pipelines, or defined in .env files, giving you flexibility depending on your workflow.
Importance of Environment Variables in Playwright Projects
Imagine running a full test suite locally. Everything works perfectly. Now you push the same suite to a staging environment. Suddenly, tests fail because the base URL is different, credentials have changed, or some API endpoints point to staging services.
You could hardcode values in each environment, but that quickly becomes unmanageable, especially as your test suite grows.
This is where environment variables become indispensable. They let you decouple configuration from test logic, so the same tests adapt dynamically to any environment. Instead of editing scripts for each environment, your tests read values from a centralized source, such as .env files, process.env, or CI pipelines.
Consider real-world scenarios:
- You’re running parallel tests in CI, each targeting a different environment. Without env variables, you’d need separate test files or conditional logic scattered across scripts.
- Your application uses feature flags that differ per environment. Hardcoding these in tests makes enabling or disabling features cumbersome.
- Credentials or API tokens need to stay secure. Embedding them in code risks leaks, whereas env variables keep secrets outside the repository.
By using Playwright env variables, you ensure tests are reliable, secure, and maintainable, while also supporting multi-environment execution without duplicating test logic.
Common Ways to Manage Environment Variables in Playwright
There are several practical ways to manage Playwright env variables, each suited to different scenarios. Choosing the right method depends on how dynamic your environments are, whether you’re running locally or in CI, and how secure the data needs to be.
1. Using .env Files
.env files are simple text files that store key-value pairs, like:
BASE_URL=https://staging.example.com API_KEY=abc123
You can load them in Playwright using packages like dotenv. This approach is ideal when you have multiple environments for local testing and want an easy, human-readable way to change configurations without touching the code.
2. Using process.env
Playwright can access any environment variable available in the system via process.env. For example:
const baseUrl = process.env.BASE_URL;This is useful when CI pipelines or containerized environments inject variables at runtime. It ensures your tests automatically pick up the correct values without modifying files.
3. Using CLI Arguments
You can pass variables directly when running tests, for example:
BASE_URL=https://staging.example.com npx playwright testThis is handy for ad-hoc test runs or quick overrides, giving flexibility without changing .env files or config.
4. Using the Playwright Config File
Playwright’s playwright.config.ts allows you to define environment-specific settings, such as projects for staging or production. You can read environment variables here to dynamically adjust base URLs, retries, and test parameters.
Each approach has trade-offs: .env files are easy to manage locally, process.env works best in CI, CLI arguments offer flexibility for quick runs, and the config file gives centralized control over project-wide settings.
How to Set Up Environment Variables in Playwright
Setting up Playwright env variables correctly ensures your tests run smoothly across all environments. Here’s a practical approach that combines the methods discussed:
Step 1: Create .env Files for Each Environment
Maintain separate files for local, staging, and production:
.env.local .env.staging .env.production
Each file contains environment-specific values like BASE_URL, API_KEY, or feature flags. This keeps configuration organized and easy to switch.
Step 2: Load .env Files in Your Tests
Use a package like dotenv at the start of your test setup:
import * as dotenv from 'dotenv'; dotenv.config({ path: `.env.${process.env.NODE_ENV}` });
Set the NODE_ENV when running tests to pick the correct environment.
Step 3: Access Variables with process.env
Inside your test or Playwright config, reference variables like this:
const baseUrl = process.env.BASE_URL; await page.goto(baseUrl);
Step 4: Pass Variables via CLI or CI
Override or inject variables at runtime when needed:
NODE_ENV=staging BASE_URL=https://staging.example.com npx playwright testThis is especially useful for CI pipelines, where secrets or environment-specific values should not be committed to files.
Step 5: Configure Playwright Projects for Multiple Environments
In playwright.config.ts, define projects for different environments:
projects: [ { name: 'staging', use: { baseURL: process.env.BASE_URL } }, { name: 'production', use: { baseURL: process.env.BASE_URL } } ]
This allows running the same tests across environments automatically.
Advanced Environment Configuration in Playwright
As your test suite grows, running the same tests across multiple environments quickly becomes complex. Hardcoding URLs, credentials, or tokens leads to repetitive edits and fragile tests. Advanced environment configuration in Playwright solves this with projects, global setup, fixtures, and environment-specific control.
1. Running Playwright Projects for Different Environments
Running the same test suite on staging and production requires switching URLs or maintaining duplicate files if projects aren’t used.
Scenario: You need to run the same test suite on staging and production without editing each test.
// playwright.config.ts projects: [ { name: 'staging', use: { baseURL: process.env.STAGING_URL } }, { name: 'production', use: { baseURL: process.env.PROD_URL } } ]
Outcome: Run all environments in parallel with isolated configurations per project.
2. Computing Runtime Environment Variables with Global Setup
Some environment variables are dynamic—like temporary tokens, session keys, or generated URLs. Hardcoding them or updating .env files manually is error-prone.
Scenario: You need API tokens or session keys generated at runtime before tests start.
// global-setup.ts import { FullConfig } from '@playwright/test'; export default async (config: FullConfig) => { const token = await fetchTokenFromAuthServer(); process.env.API_TOKEN = token; };
Outcome: Tests always use correct runtime values automatically without manual updates.
3. Managing Environment Variables with Playwright Fixtures
If multiple tests need the same configuration, scattering process.env references makes tests messy. Fixtures allow injecting variables directly into test functions.
Scenario: You have dozens of tests that require a baseUrl and an authToken. Using fixtures:
- The test receives them automatically.
- No repetitive code in each test.
// fixtures.ts import { test as base } from '@playwright/test'; export const test = base.extend({ baseUrl: process.env.BASE_URL, authToken: process.env.API_TOKEN });
Outcome: Tests stay clean, reusable, and consistent across environments.
4. Running Playwright Tests Across Environments in CI Pipelines
CI pipelines often need secure injection of environment variables. Instead of committing .env files, pipelines can pass variables at runtime.
Scenario: Your CI pipeline needs to run the same test suite across staging and production without exposing secrets.
# Example for GitHub Actions or other CI STAGING_URL=https://staging.example.com API_KEY=${{ secrets.API_KEY }} npx playwright test
Outcome: The same test suite runs in CI for multiple environments without exposing secrets in code.
5. Running Environment-Specific Tests with Tags in Playwright
Some tests only apply to certain environments like production-only smoke tests. Using Playwright annotations or tags, you can mark these tests, and combine them with environment variables to control execution.
Scenario: A staging-only feature shouldn’t block production runs. Tagging ensures only relevant tests execute per environment.
// example.spec.ts test.describe.configure({ mode: 'parallel' }); test('@staging Verify new feature', async ({ page }) => { // test code });
Outcome: Fine-grained control over which tests run where, keeping your pipelines fast and reliable.
Recommended Practices for Managing Environment Variables in Playwright
Before setting up environment variables, it’s important to follow practices that make your Playwright tests reliable, maintainable, and secure across multiple environments. Proper management prevents fragile tests, accidental credential leaks, and unnecessary duplication, while keeping your suite easy to scale.
- Keep variables out of test code: Store URLs, credentials, and API keys in .env files, CI secrets, or config files instead of hardcoding them.
- Use clear, consistent naming: Names like BASE_URL, API_TOKEN, or FEATURE_FLAG_X make it obvious what each variable controls.
- Separate variables per environment: Maintain dedicated .env files for local, staging, and production, or use CI/CD secrets for each environment.
- Leverage Playwright config and fixtures: Define environment-specific projects and inject variables via fixtures to reduce repetitive process.env calls.
- Secure sensitive information: Avoid committing secrets; use CI/CD secret managers or runtime injection.
- Use CLI overrides for temporary runs: Pass variables via CLI for ad-hoc tests without touching configuration files.
Conclusion
Managing environment variables in Playwright is essential for running tests reliably across local, staging, and production environments. They allow you to decouple configuration from test code, keep sensitive information secure, and maintain a scalable, maintainable test suite.
By using .env files, process.env, CLI overrides, and Playwright projects, you can handle multi-environment setups efficiently. Techniques like global setup, fixtures, and environment-specific test tags further simplify complex workflows.
FAQs
You can store API keys in CI/CD secret managers (GitHub Actions, GitLab, Jenkins, etc.) and inject them at runtime using process.env. This keeps secrets out of your repository and .env files, ensuring secure access during test execution.
Yes, but it requires careful setup. You can update process.env values or use fixtures to provide different configuration mid-test. However, switching environments often involves clearing sessions or contexts to avoid conflicts.
Each parallel worker inherits the current environment variables. To avoid conflicts, ensure that environment-specific data (like URLs or tokens) are isolated per worker—for example, by using different baseURL values via Playwright projects.
Store feature flags as environment variables or configuration objects per environment. Use fixtures to inject the relevant flags into tests, so tests automatically respect the environment without hardcoding logic.
Start by logging process.env values at the start of tests or using console.log/cy.log. Verify that .env files or CI-injected variables are loaded correctly. Comparing the values used in local vs CI runs often identifies mismatches quickly.
Yes, using fixtures or global setup. You can compute a value once in a fixture or global setup and make it available to all tests, ensuring consistency without reloading .env files or recomputing values multiple times.
Related Articles
Playwright Install Guide: Setup for Node, Python, Java & .NET
Learn how to install Playwright step by step for Node.js, Python, Java, and .NET. Verify installatio...
Playwright Architecture: Client, Server, Browsers Explained
Playwright architecture defines how tests interact with browsers through its core components. Learn ...
Master Playwright Config for Efficient Test Automation
Playwright config defines how tests run and behave. Learn how to configure browsers, devices, and pa...