Environment Variables Management using Playwright in 2025

On This Page Understanding Environment VariablesJune 17, 2026 · 14 min read · Tool Comparison

Environment Variables Management using Playwright in 2025

In, environment variables are expend to configure test settings such as base URLs, credential, and other environment-specific value. They enable dynamic test execution across different environs without modifying the exam codification, ensuring flexibleness and scalability.

Overview

Managing environment variables expeditiously is all-important for scalable and secure Playwright test mechanization. By leverage environs variables, squad can well configure and swap between different environment, ascertain flexibility and scalability in their examination workflows.

Methods for Using Environment Variables in Playwright:

  • .env Files:Store environment-specific variable in .env files and use the dotenv software to load them into Playwright trial.
  • Process Environment (process.env):Access environment variables directly in your test code using process.env.VARIABLE_NAME.
  • Playwright Config File:Define environment variables in playwright.config.ts to customize test configurations like base URL, credentials, etc.
  • CI/CD Integration:Inject surround variable into tests via CI/CD tools (e.g., GitHub Actions, CircleCI) to securely cope different environs during automated testing.
  • Command-Line Arguments:Pass environment variables when go Playwright tests via the dictation line, such as STAGING=true npx playwright exam.

This clause search the importance of environment variable in Playwright, common method for managing them, best practices, and advanced configurations for multi-environment orchestration.

Understanding Environment Variables

Environment variables are key-value pairs utilize to store configuration settings and sensitive data that an application or service needs to function. In the context of and, environment variables enable active configuration of examination settings without hardcoding values into the codebase.

They let you to separate the configuration from the application logic, making it easier to switch between different environments (e.g., development, scaffolding, production) without alter the source code.

In Playwright, environment variable are used to care dynamic configurations, such as URLs, API keys, authentication credentials, and characteristic flags. By using environs variables, you can well adjust test demeanor depending on the environment, guarantee that the same trial code run seamlessly in different stages of the deployment pipeline.

For model, instead of hardcoding a base URL for your application in the test script, you can use an environs variable like BASE_URL and load it dynamically based on the surround. This makes the trial more flexible, recyclable, and secure, as sensible data can be managed outside the codebase.

Read More:

Why Environment Variables Are Critical in Playwright?

Environment variable play a vital persona in Playwright test automation by offering flexibility, protection, and scalability. Here are the key understanding why they are critical in Playwright:

  • Environment Flexibility:They enable unlined switching between different environments (dev, staging, production) without altering test code, ensuring reproducible test execution across all stages.
  • Security: Sensitive data like API keys and credentials are store in environment variables, trim the jeopardy of exposure in code and protecting critical info during test runs.
  • Configurability:Environment variable externalize configurations like URLs and tokens, create it easy to adjust settings for different environments without code change.
  • Maintainability:Managing configurations through environment variable take to cleaner, more maintainable tryout by allowing update to settings without change the codification.
  • Scalability:In large projects, environment variable enable scalable prove across multiple environments and configurations, simplifying automation in.

By desegregate surroundings variable into Playwright tests, teams can ensure a more full-bodied, secure, and effective testing workflow.

Mutual Approaches to Manage Environment Variables

There are several effective method for managing environment variables in Playwright, each offering flexibility and security:

Using .env Files

The most common approach is to store environment-specific variable in .env files. Using the dotenv software, you can charge these variable into your Playwright tests dynamically, continue configuration separate from code. This let for easy management of variable for different environment (e.g., .env.dev, .env.prod).

Process Environment (process.env)

Playwright grant direct access to environment variable using process.env.VARIABLE_NAME. This method permit you reference variable in your examination scripts or configuration files, ensuring they adapt to the environment they are executed in without the need for hardcoding values.

CI/CD Integration

In modern examination workflows, environment variables are often shoot during the pipeline setup. Tools like GitHub Actions,, and grant you to firmly legislate surround variable as part of the pipeline, ensuring that sensitive info (like API key and credentials) remains protected while be employ in test runs.

Command-Line Arguments

Environment variable can also be passed directly via the command line when running Playwright tests. This is especially useful for short-term overrides, such as specifying a different surroundings with a elementary command like STAGING=true npx playwright test.

Playwright Configuration File

Variables can be accessed and utilized within the playwright.config.ts file, where you can delimit dynamic settings (like bag URLs or retries) found on surroundings variables. This centralizes the contour for multiple environments in one spot.

Each approach provides a different level of control and flexibleness, and oftentimes, a combination of these methods is used to manage environs variables effectively across different stages of test automation.

Read More:

Setting Up Environment Variables in Playwright

Setting up environment variables in Playwright involves a few key steps to guarantee your exam are dynamic and pliable across different environment. Here & # 8217; s a simple guide to get commence:

1. Install the dotenv Package

First, install the dotenv bundle, which helps payload environment variables from a .env file into your Playwright configuration.

npm install dotenv

2. Create .env Files

Create a .env file in your task root directory. This file will store key-value pairs for your environment variable (e.g., BASE_URL, API_KEY). You can receive different .env file for different environments like .env.dev, .env.prod, etc.

Example .env file:

BASE_URL=https: //staging.example.com API_KEY=your_api_key_here

3. Load Environment Variables in playwright.config.ts

In your Playwright configuration file (playwright.config.ts), use the dotenv package to load the environment variable from the .env file.

importation {defineConfig} from ' @ playwright/test '; import * as dotenv from 'dotenv '; // Load .env file dotenv.config (); exportation default defineConfig ({use: {baseURL: process.env.BASE_URL, // Accessing the environment variable},});

4. Access Environment Variables in Tests

In your Playwright tryout files, you can admission the environment variable using process.env. This allows you to dynamically load datum based on the environment.

Example:

signification {examination, expect} from & # 8216; @ playwright/test & # 8217;;

trial (& # 8216; should laden the correct base URL & # 8217;, async ({page}) = & gt; {
await page.goto (process.env.BASE_URL);
anticipate (page.url ()) .toBe (process.env.BASE_URL);
});

5. Using Environment Variables in CI/CD

In CI/CD pipelines, you can firmly surpass environment variables to Playwright tests without including them in .env files. For example, in GitHub Actions, you can set surround variable in the workflow YAML file:

jobs:
test:
runs-on: ubuntu-latest
env:
BASE_URL: $ {{secrets.BASE_URL}}
API_KEY: $ {{secrets.API_KEY}}

By following these steps, you can set up environment variables in Playwright to plow different environments, manage sensitive data firmly, and maintain scalable and maintainable test mechanisation workflows.

Talk to Expert

Advanced Configuration: Playwright Projects and Multi-Environment Test Orchestration

Use Playwright Projects to sit each target environment (dev/stage/prod) as a first-class config, so engineer them locally and in CI.

1. Project-per-environment config

Playwright, allowing each projection to have its own environment apparatus, including browser/device settings and environment variables. Here & # 8217; s how you can implement this apply a project-per-environment approach:

// playwright.config.ts
import {defineConfig, devices} from & # 8216; @ playwright/test & # 8217;;
import * as dotenv from & # 8216; dotenv & # 8217;;

For autonomous testing across multiple user personas, check out SUSATest — it explores your app like 10 different real users.

const ENV = process.env.ENV?? & # 8216; dev & # 8217;;
dotenv.config ({path: ` .env. $ {ENV} `}); // .env.dev | .env.staging | .env.prod

function requireEnv (name: string) {
const v = process.env [name];
if (! v) throw new Error (` Missing env: $ {gens} `);
return v;
}

export nonpayment defineConfig ({
reporter: [[& # 8216; html & # 8217;], [& # 8216; leaning & # 8217;]],
timeout: 30_000,
projects: [
{
gens: & # 8216; chromium-dev & # 8217;,
use: {
& # 8230; devices [& # 8216; Desktop Chrome & # 8217;],
baseURL: requireEnv (& # 8216; BASE_URL & # 8217;),
httpCredentials: process.env.BASIC_AUTH_USER
? {username: requireEnv (& # 8216; BASIC_AUTH_USER & # 8217;), password: requireEnv (& # 8216; BASIC_AUTH_PASS & # 8217;)}
: undefined,
extraHTTPHeaders: {& # 8216; x-api-key & # 8217;: requireEnv (& # 8216; API_KEY & # 8217;)},
},
},
{
name: & # 8216; webkit-staging & # 8217;,
use: {
& # 8230; devices [& # 8216; Desktop Safari & # 8217;],
baseURL: requireEnv (& # 8216; BASE_URL_STAGING & # 8217;),
extraHTTPHeaders: {& # 8216; x-api-key & # 8217;: requireEnv (& # 8216; API_KEY_STAGING & # 8217;)},
},
},
// Add prod, mobile, etc.
],
});

This setup ensures that each environment has its own configuration and environment variables, making the test form highly adaptable and maintainable.

2. Planetary apparatus to figure per-run value

Generate run-scoped values (e.g., auth tokens, tryout data IDs) erstwhile and unwrap via process.env.

// global-setup.ts
significance {request, FullConfig} from & # 8216; @ playwright/test & # 8217;;
export default async function (config: FullConfig) {
const ctx = await request.newContext ({baseURL: process.env.AUTH_BASE_URL});
const resp = await ctx.post (& # 8216; /token & # 8217;, {data: {clientId: process.env.CLIENT_ID, secret: process.env.CLIENT_SECRET}});
const {accessToken} = await resp.json ();
process.env.ACCESS_TOKEN = accessToken; // used by all projects
}
// playwright.config.ts (add)
globalSetup: require.resolve (& # 8216; ./global-setup & # 8217;),

3. Project-scoped fixtures (typed option)

Create environment-aware secureness so tests don & # 8217; t touch process.env instantly.

// tests/fixtures/env.ts
signification {test as base} from & # 8216; @ playwright/test & # 8217;;

case Env = {api: string; token: twine};
export const exam = base.extend ({
env: async ({}, use) = & gt; {
await use ({
api: process.env.API_BASE!,
token: process.env.ACCESS_TOKEN!,
});
},
});
export const expect = test.expect;

// tests/example.spec.ts
import {exam, expect} from & # 8216; ./fixtures/env & # 8217;;
test (& # 8216; uses env-aware client & # 8217;, async ({request, env}) = & gt; {
const res = await request.get (` $ {env.api} /health `, {header: {Authorization: ` Bearer $ {env.token} `}});
expect (res.ok ()) .toBeTruthy ();
});

4. Orchestrating environment in CI (matrix + sharding)

Run all environments in latitude; shard long retinue for swiftness.

# .github/workflows/playwright.yml
jobs:
e2e:
runs-on: ubuntu-latest
strategy:
matrix:
env: [dev, staging, goading]
shard: [1/2, 2/2]
env:
ENV: $ {{matrix.env}}
# Secrets per env (Org/Repo Environments or cloak secrets)
BASE_URL: $ {{secrets [format (& # 8216; BASE_URL_ {0} & # 8217;, upper (matrix.env))]}}
API_KEY: $ {{secret [formatting (& # 8216; API_KEY_ {0} & # 8217;, upper (matrix.env))]}}
steps:
& # 8211; use: actions/checkout @ v4
& # 8211; uses: actions/setup-node @ v4
with: {node-version: 20}
& # 8211; run: npm ci
& # 8211; run: npx playwright install & # 8211; with-deps
& # 8211; run: npx playwright test & # 8211; shard= $ {{matrix.shard}}

5. Targeted selection via tags/grep

Scope runs by feature or risk level per environment.

// Tag tests: test.describe.configure ({mode: & # 8216; parallel & # 8217;}); test (& # 8216; feature A @ smoking & # 8217;, & # 8230;)
# Only smoking tests on spur
ENV=prod npx playwright test & # 8211; grep & # 8220; @ smoke & # 8221;

Best Practices for Managing Environment Variables in Playwright

To ensure that your Playwright examination are untroubled, maintainable, and scalable, follow these best pattern for managing environment variables:

1. Use .env Files for Local Development

Store environment-specific variables (e.g., base URLs, API key, credentials) in .env files. This proceed sensitive data separate from your codebase. Always ensure .env file are ignored by variation control (add them to .gitignore) to forestall accidental exposure of secrets.

2. Leverage CI/CD Secrets Management

For sensitive data like API keys and tokens, use CI/CD secret management tools (e.g., GitHub Secrets, variables) rather of store them in .env file. This ensures that certificate are firmly injected into the test environment during execution, without exposing them in your code.

3. Validate Required Variables at Startup:

Use a function or puppet to check that all necessary environment variables are delimit before running tests. This ensures that your tests fail early with clear error messages if a needed variable is missing, sooner than scat into issues midway through the trial run.

4. Use Freestanding .env Files for Different Environments:

Maintain different .env files for different environments (e.g., .env.dev, .env.prod, .env.staging). This allows you to well switch configuration without modify your code. Use environment-specific configurations in your Playwright test setup (e.g., dotenv.config ({path: .env. $ {process.env.ENV}})).

5. Keep Secrets Secure:

Avoid hardcoding sensitive information such as passwords or API keys directly into the codification. Use environment variables to firmly manage such data. Also, mask sensitive information in logs and account to prevent accidental exposure.

6. Centralize Configuration with Playwright & # 8217; s Config File:

Use Playwright & # 8217; s playwright.config.ts to define environment-dependent settings, like base URLs, authentication certification, and API keys. This centralizes your configuration management, trim the chances of errors and amend tryout consistency.

7. Use Environment Variables for Feature Flags and Dynamic Configuration:

Manage feature toggle or other active test conformation using environment variable. This allow you to enable or disable characteristic in your tests without modifying the codification, do your quiz process more flexible and easier to manage.

8. Ensure Ordered Naming Conventions:

Maintain consistent appointment conventions for your surround variables (e.g., BASE_URL_DEV, BASE_URL_PROD, API_KEY). This aid prevent disarray and makes it easier to maintain your environment-specific configurations, especially in large projects with multiple environs.

9. Document Environment Variables:

Keep a document or README that excuse the required environment variables for your task. Include information about their purpose and how to set them up, peculiarly for new squad members or when onboarding to a new project.

10. Minimize the Number of Environment Variables:

Only define the variables that are absolutely necessary for the tests. Avoid unnecessary complexity by limiting the number of environment variables and assure they are well-organized and purposeful.

By following these better pattern, you ensure that your Playwright tests are secure, maintainable, and adaptable to different environments, ultimately improving the efficiency and reliability of your screen procedure.

Read More:

Example Walk-through: Setting Up Playwright with Environment Variables

Setting up environment variables in Playwright allows for flexible, environment-specific configurations that hold your test code clean and maintainable. Here & # 8217; s a unproblematic example of how to configure environment variables in Playwright:

1. Create .env Files

Create different .env files for each surround (e.g., .env.dev, .env.staging, .env.prod) to store environment-specific variable. For example, the .env.dev file might look like this:

BASE_URL=https: //dev.example.com
API_KEY=dev-api-key

2. Install dotenv Package

Use the dotenv package to load these environment variable into your Playwright configuration. Install it using:

npm install dotenv

3. Configure Playwright to Use Environment Variables

In your playwright.config.ts, load the environment variables using dotenv.config () and set them dynamically based on the environment:

import {defineConfig} from & # 8216; @ playwright/test & # 8217;;
significance * as dotenv from & # 8216; dotenv & # 8217;;

// Load .env file based on the surroundings
const ENV = process.env.ENV?? & # 8216; dev & # 8217;; // default to & # 8216; dev & # 8217;
dotenv.config ({path: ` .env. $ {ENV} `});

export default defineConfig ({
use: {
baseURL: process.env.BASE_URL, // Access environment variable
extraHTTPHeaders: {
& # 8216; x-api-key & # 8217;: process.env.API_KEY // Use API key from environs
},
},
});

4. Access Variables in Tests

In your test files, you can directly access these variables using process.env:

import {test, expect} from & # 8216; @ playwright/test & # 8217;;

test (& # 8216; should call the right fundament URL & # 8217;, async ({page}) = & gt; {
await page.goto (process.env.BASE_URL); // Use the loaded bag URL
wait (page.url ()) .toBe (process.env.BASE_URL);
});

5. Run Tests with Different Environments

When running your tests, specify which surroundings to use by setting the ENV variable:

ENV=staging npx playwright test

This command loads the .env.staging file, grant you to run tests with staging-specific configurations.

This simple setup lets you contend surroundings variables for different configurations (e.g., growing, scaffolding, production) without modifying the test code, keeping your tests clean and adaptable.

Read More:

Leveraging BrowserStack Automate for Scalable Environment Variable Management in Playwright

empowers teams to run Playwright exam at scale on existent browsers and devices in the cloud, while hold consistent and untroubled management of environment configurations.

It complements your existing setup by secure that tests using environment variables execute reliably across divers environments, without the overhead of maintaining local substructure.

  • Seamless CI/CD Integration:BrowserStack Automate works hand-in-hand with CI/CD tools like GitHub Actions, Jenkins, and CircleCI, allowing you to pass environment variable firmly during test execution. This ensures that Playwright tests can adapt dynamically to different form such as ontogenesis, stag, or production.
  • Multi-Environment Testing at Scale:With BrowserStack & # 8217; s extensive cloud infrastructure, you can fulfill Playwright tests in across multiple browsers, device, and operating systems & # 8211; all configured using your environment variable. This provides true scalability and ensures consistent behavior across environments.
  • Security and Data Integrity:Sensitive info such as API keys, credentials, and tokens can be managed firmly through your CI/CD & # 8217; s secrets management system. BrowserStack executes the tests in isolated environments, help maintain information privacy and integrity throughout the quiz process.
  • Reproducible and Authentic Configuration:Environment variables defined in your CI/CD or local setup are used seamlessly during BrowserStack test tally, ensuring that every test environment mirrors your actual application setup. This consistency improves reliability and minimizes environment-related issues.
  • Scalable Cross-Browser Execution:By leverage BrowserStack Automate, team can focalize on scale their Playwright exam efficiently & # 8211; executing thousands of across multiple browsers and device, all drive by the same environment-variable-based form logic.

Conclusion

Efficient surroundings variable management is a groundwork of reliable and scalable Playwright tryout automation. It enables teams to configure tests dynamically, maintain protection by keeping sensitive data out of code, and secure consistency across development, scaffolding, and production environments.

By structuring surround variables thoughtfully, through .env files, CI/CD pipeline, and Playwright & # 8217; s configuration, teams can streamline test setup, cut maintenance overhead, and improve coaction.

When paired with BrowserStack Automate, these exercise scale effortlessly. Teams can execute Playwright examination across real browsers and devices globally, maintaining the same secure and consistent environment configurations at every level.

In centre, robust environment variable management empowers Playwright to deliver pliable, secure, and high-performing automated testing & # 8211; insure your tests adapt as smoothly as your applications evolve.

Useful Resources for Playwright

Tool Comparisons:

Tags

On This Page

7,000+ Views

# Ask-and-Contributeabout this issue with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free