Environment Variables Management using Playwright in 2025
On This Page Understanding Environment VariablesJune 17, 2026 · 14 min read · Tool Comparison
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. 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: This clause search the importance of environment variable in Playwright, common method for managing them, best practices, and advanced configurations for multi-environment orchestration. 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: 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: By desegregate surroundings variable into Playwright tests, teams can ensure a more full-bodied, secure, and effective testing workflow. There are several effective method for managing environment variables in Playwright, each offering flexibility and security: 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). 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. 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. 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. 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 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. 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: 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. 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: trial (& # 8216; should laden the correct base URL & # 8217;, async ({page}) = & gt; { 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: 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. Use Playwright Projects to sit each target environment (dev/stage/prod) as a first-class config, so engineer them locally and in CI. 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: 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;; function requireEnv (name: string) { export nonpayment defineConfig ({ This setup ensures that each environment has its own configuration and environment variables, making the test form highly adaptable and maintainable. Generate run-scoped values (e.g., auth tokens, tryout data IDs) erstwhile and unwrap via process.env. Create environment-aware secureness so tests don & # 8217; t touch process.env instantly. case Env = {api: string; token: twine}; Run all environments in latitude; shard long retinue for swiftness. Scope runs by feature or risk level per environment. 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: 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: 2. Install dotenv Package Use the dotenv package to load these environment variable into your Playwright configuration. Install it using: 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: // Load .env file based on the surroundings export default defineConfig ({ 4. Access Variables in Tests In your test files, you can directly access these variables using process.env: test (& # 8216; should call the right fundament URL & # 8217;, async ({page}) = & gt; { 5. Run Tests with Different Environments When running your tests, specify which surroundings to use by setting the ENV variable: 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: 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. 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. Tool Comparisons: On This Page # Ask-and-Contributeabout this issue with our Discord community. Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed. Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.Environment Variables Management using Playwright in 2025
Overview
Understanding Environment Variables
Why Environment Variables Are Critical in Playwright?
Mutual Approaches to Manage Environment Variables
Using .env Files
Process Environment (process.env)
CI/CD Integration
Command-Line Arguments
Playwright Configuration File
Setting Up Environment Variables in Playwright
npm install dotenv
BASE_URL=https: //staging.example.com API_KEY=your_api_key_here
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},});signification {examination, expect} from & # 8216; @ playwright/test & # 8217;;
await page.goto (process.env.BASE_URL);
anticipate (page.url ()) .toBe (process.env.BASE_URL);
});jobs:
test:
runs-on: ubuntu-latest
env:
BASE_URL: $ {{secrets.BASE_URL}}
API_KEY: $ {{secrets.API_KEY}}Advanced Configuration: Playwright Projects and Multi-Environment Test Orchestration
1. Project-per-environment config
// playwright.config.ts
import {defineConfig, devices} from & # 8216; @ playwright/test & # 8217;;
import * as dotenv from & # 8216; dotenv & # 8217;;
dotenv.config ({path: ` .env. $ {ENV} `}); // .env.dev | .env.staging | .env.prod
const v = process.env [name];
if (! v) throw new Error (` Missing env: $ {gens} `);
return v;
}
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.
],
});2. Planetary apparatus to figure per-run value
// 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)
// tests/fixtures/env.ts
signification {test as base} from & # 8216; @ playwright/test & # 8217;;
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)
# .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
// 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
Example Walk-through: Setting Up Playwright with Environment Variables
BASE_URL=https: //dev.example.com
API_KEY=dev-api-keynpm install dotenv
import {defineConfig} from & # 8216; @ playwright/test & # 8217;;
significance * as dotenv from & # 8216; dotenv & # 8217;;
const ENV = process.env.ENV?? & # 8216; dev & # 8217;; // default to & # 8216; dev & # 8217;
dotenv.config ({path: ` .env. $ {ENV} `});
use: {
baseURL: process.env.BASE_URL, // Access environment variable
extraHTTPHeaders: {
& # 8216; x-api-key & # 8217;: process.env.API_KEY // Use API key from environs
},
},
});import {test, expect} from & # 8216; @ playwright/test & # 8217;;
await page.goto (process.env.BASE_URL); // Use the loaded bag URL
wait (page.url ()) .toBe (process.env.BASE_URL);
});ENV=staging npx playwright test
Leveraging BrowserStack Automate for Scalable Environment Variable Management in Playwright
Conclusion
Useful Resources for Playwright
Related Guides
Automate This With SUSA
Test Your App Autonomously