Playwright TypeScript Environment Variables: Step-by-Step Guide (2026) | TechSarvam

1. Introduction to Environment Variables in Playwright TypeScript

When developing automation frameworks, testers often work with multiple environments, such as local, QA, staging, and production.

Each environment may have a different application URL, username, password, API endpoint, and authentication token.

If these values are directly written inside automation scripts, changing environments becomes difficult. It also creates security risks when sensitive credentials are committed to Git repositories.

This is where Playwright TypeScript environment variables become useful.

Environment variables allow QA Automation Engineers and SDETs to store configuration values separately from test scripts. They can access these values through TypeScript using process.env.

For example, instead of writing a fixed URL:

await page.goto(‘https://qa.example.com’);

You can write:

await page.goto(process.env.BASE_URL!);

Now the same automated test can run against different environments without modifying the test code.

In this tutorial, we will learn how to configure environment variables using .env files, dotenv, Playwright configuration, GitHub Actions, and Jenkins.

2. Why Environment Variables Are Important in Test Automation

Environment variables are important because automation frameworks frequently interact with different application environments and external services.

Consider an e-commerce application with three environments:

EnvironmentApplication URL
Localhttp://localhost:3000
QAhttps://qa.example.com
Staginghttps://staging.example.com

Without environment variables, testers may need to update URLs manually whenever they switch environments.

With Playwright environment configuration, the same test scripts can execute against different URLs.

Important Benefits

  1. Environment flexibility: Switch between local, QA, and staging environments easily.
  2. Security: Keep passwords and API tokens outside source code.
  3. Code reusability: Use the same test scripts across environments.
  4. Easy maintenance: Update configuration without changing test logic.
  5. CI/CD integration: Pass configuration values through GitHub Actions and Jenkins.
  6. Better collaboration: Team members can maintain their own local configurations.

Environment variables are especially useful for large automation frameworks containing hundreds of automated test scripts.

3. Project Setup and Installation of dotenv

Before starting the Playwright TypeScript environment variables tutorial, make sure Node.js, npm, and Playwright are installed.

Step 1: Create a Playwright Project

mkdir playwright-env-project

cd playwright-env-project

Initialize Playwright:

npm init playwright@latest

Select TypeScript when prompted.

Step 2: Install dotenv

The dotenv package loads environment variables from .env files into process.env.

Install it:

npm install dotenv

Step 3: Verify Installation

npm list dotenv

npx playwright –version

Your project is now ready for environment configuration.

4. Create and Configure .env Files

A .env file stores configuration values as key-value pairs.

Create a file named .env in the project root.

Example .env File

BASE_URL=https://qa.example.com

TEST_USERNAME=qauser

TEST_PASSWORD=Test@123

API_URL=https://qa-api.example.com

API_KEY=sample-test-key

These values can be accessed by your Playwright configuration and test scripts.

Important: The values above are examples. Never commit actual passwords, API keys, or access tokens to your repository.

Create Environment-Specific Files

For projects with multiple environments, use separate configuration files.

playwright-env-project/

│

├── tests/

│   ├── login.spec.ts

│   └── api.spec.ts

│

├── pages/

│   └── LoginPage.ts

│

├── config/

│   └── environment.ts

│

├── .env.local

├── .env.qa

├── .env.staging

├── .env.example

│

├── playwright.config.ts

├── package.json

└── .gitignore

Example .env.local:

BASE_URL=http://localhost:3000

API_URL=http://localhost:3000/api

TEST_USERNAME=localuser

Example .env.qa:

BASE_URL=https://qa.example.com

API_URL=https://qa-api.example.com

TEST_USERNAME=qauser

Example .env.staging:

BASE_URL=https://staging.example.com

API_URL=https://staging-api.example.com

TEST_USERNAME=staginguser

Do not store real passwords in these files if they are shared or committed.

Create a .env.example File

This file documents which variables developers need to configure.

BASE_URL=

API_URL=

TEST_USERNAME=

TEST_PASSWORD=

API_KEY=

Team members can copy this file and create their own local .env configuration.

Protect Environment Files Using .gitignore

Create or update .gitignore:

node_modules/

playwright-report/

test-results/

.env

.env.*

!.env.example

This prevents actual environment files from being committed while allowing the example template to remain in Git.

5. Access Variables Using process.env

Node.js provides process.env to access environment variables.

For example:

const baseURL = process.env.BASE_URL;

console.log(baseURL);

If the variable is not configured, its value will be undefined.

Load Environment Variables Using dotenv

Create config/environment.ts:

import dotenv from ‘dotenv’;

dotenv.config({

  path: `.env.${process.env.TEST_ENV || ‘qa’}`

});

export const baseURL = process.env.BASE_URL;

export const username = process.env.TEST_USERNAME;

export const password = process.env.TEST_PASSWORD;

This example loads .env.qa by default.

You can select another environment using the TEST_ENV variable.

For stronger type safety, validate required variables before running tests.

Create an Environment Validation Utility

Update config/environment.ts:

import dotenv from ‘dotenv’;

dotenv.config({

  path: `.env.${process.env.TEST_ENV || ‘qa’}`

});

function required(name: string): string {

  const value = process.env[name];

  if (!value) {

    throw new Error(

      `Missing required environment variable: ${name}`

    );

  }

  return value;

}

export const config = {

  baseURL: required(‘BASE_URL’),

  apiURL: required(‘API_URL’),

  username: required(‘TEST_USERNAME’)

};

This approach prevents tests from running with missing configuration.

Keep secrets out of error messages and logs.

6. Configure Base URLs for Multiple Environments

One of the most common uses of Playwright environment variables is switching between application environments.

Configure playwright.config.ts

Load the environment configuration before defining Playwright settings.

import dotenv from ‘dotenv’;

import { defineConfig } from ‘@playwright/test’;

const environment = process.env.TEST_ENV || ‘qa’;

dotenv.config({

  path: `.env.${environment}`,

  quiet: true

});

function required(name: string): string {

  const value = process.env[name];

  if (!value) {

    throw new Error(`Missing environment variable: ${name}`);

  }

  return value;

}

export default defineConfig({

  testDir: ‘./tests’,

  use: {

    baseURL: required(‘BASE_URL’),

    trace: ‘on-first-retry’,

    screenshot: ‘only-on-failure’,

    video: ‘retain-on-failure’

  },

  reporter: [

    [‘html’, { open: ‘never’ }],

    [‘list’]

  ]

});

The TEST_ENV variable determines which environment file is loaded.

Run Tests Against QA

On Linux or macOS:

TEST_ENV=qa npx playwright test

On Windows PowerShell:

$env:TEST_ENV=”qa”

npx playwright test

Run Tests Against Staging

Linux or macOS:

TEST_ENV=staging npx playwright test

Windows PowerShell:

$env:TEST_ENV=”staging”

npx playwright test

The same test scripts now execute against different environments.

Best practice: Never point destructive registration, deletion, or payment tests at production by default. Use explicitly approved test environments and safe test accounts.

7. Manage Usernames, Passwords, API Keys, and Secrets Securely

Automation frameworks often require authentication credentials and API tokens.

For example, a login test may require a username and password, while an API test may require an access token.

Never hardcode these values directly in TypeScript files.

Example: Authentication Using Environment Variables

import { test, expect } from ‘@playwright/test’;

test(‘Verify user login’, async ({ page }) => {

  const username = process.env.TEST_USERNAME;

  const password = process.env.TEST_PASSWORD;

  if (!username || !password) {

    throw new Error(‘Login credentials are missing’);

  }

  await page.goto(‘/login’);

  await page.getByLabel(‘Username’).fill(username);

  await page.getByLabel(‘Password’).fill(password);

  await page.getByRole(‘button’, {

    name: ‘Login’

  }).click();

  await expect(page).toHaveURL(/dashboard/);

});

Manage API Keys

import { test, expect } from ‘@playwright/test’;

test(‘Verify authenticated API request’, async ({ request }) => {

  const apiKey = process.env.API_KEY;

  if (!apiKey) {

    throw new Error(‘API_KEY is not configured’);

  }

  const response = await request.get(

    ‘/api/users’,

    {

      headers: {

        Authorization: `Bearer ${apiKey}`

      }

    }

  );

  expect(response.ok()).toBeTruthy();

});

This example assumes your API accepts a bearer token.

Important Security Practices

  • Never commit .env files containing secrets.
  • Use CI/CD secret storage for credentials.
  • Avoid printing passwords and API tokens in console logs.
  • Use separate credentials for QA and staging.
  • Rotate expired or compromised credentials.
  • Give automation accounts only the permissions they need.

8. Use Environment Variables in Playwright Configuration and Test Files

A professional framework should centralize environment configuration instead of accessing different variables repeatedly in every test.

Create a Central Configuration Utility

Create config/environment.ts:

import dotenv from ‘dotenv’;

const env = process.env.TEST_ENV || ‘qa’;

dotenv.config({

  path: `.env.${env}`,

  quiet: true

});

function getRequired(name: string): string {

  const value = process.env[name];

  if (!value) {

    throw new Error(`Missing configuration: ${name}`);

  }

  return value;

}

export const environmentConfig = {

  environment: env,

  baseURL: getRequired(‘BASE_URL’),

  apiURL: getRequired(‘API_URL’),

  username: getRequired(‘TEST_USERNAME’)

};

You can import this configuration wherever required.

Example:

import { test, expect } from ‘@playwright/test’;

import { environmentConfig } from ‘../config/environment’;

test(‘Verify application URL’, async ({ page }) => {

  await page.goto(environmentConfig.baseURL);

  await expect(page).toHaveTitle(/Application/);

});

For a larger framework, you can extend this configuration with API endpoints, browser options, feature flags, and test account settings.

9. Configure Variables in GitHub Actions and Jenkins

Environment variables are also important when executing Playwright tests in CI/CD pipelines.

A. GitHub Actions Configuration

Create .github/workflows/playwright.yml:

name: Playwright Environment Tests

on:

  push:

    branches: [main]

  pull_request:

    branches: [main]

jobs:

  test:

    runs-on: ubuntu-latest

    steps:

      – name: Checkout Code

        uses: actions/checkout@v6

      – name: Setup Node.js

        uses: actions/setup-node@v6

        with:

          node-version: lts/*

          cache: npm

      – name: Install Dependencies

        run: npm ci

      – name: Install Browsers

        run: npx playwright install –with-deps chromium

      – name: Run Playwright Tests

        run: npx playwright test

        env:

          TEST_ENV: qa

          BASE_URL: ${{ secrets.BASE_URL }}

          API_URL: ${{ secrets.API_URL }}

          TEST_USERNAME: ${{ secrets.TEST_USERNAME }}

          TEST_PASSWORD: ${{ secrets.TEST_PASSWORD }}

      – name: Upload Report

        if: ${{ !cancelled() }}

        uses: actions/upload-artifact@v5

        with:

          name: playwright-report

          path: |

            playwright-report/

            test-results/

Add the required secrets under:

GitHub Repository → Settings → Secrets and variables → Actions.

The pipeline passes these values to the Playwright test process without storing credentials in the workflow source.

For pull requests from forks, GitHub generally does not provide repository secrets to the workflow. Design the workflow so untrusted pull requests cannot access sensitive credentials.

B. Jenkins Environment Configuration

Jenkins supports environment variables through pipeline configuration and credentials management.

Example Jenkinsfile:

pipeline {

    agent any

    environment {

        TEST_ENV = ‘qa’

        BASE_URL = ‘https://qa.example.com’

    }

    stages {

        stage(‘Install Dependencies’) {

            steps {

                sh ‘npm ci’

            }

        }

        stage(‘Install Browsers’) {

            steps {

                sh ‘npx playwright install –with-deps chromium’

            }

        }

        stage(‘Run Tests’) {

            steps {

                withCredentials([

                    usernamePassword(

                        credentialsId: ‘qa-login’,

                        usernameVariable: ‘TEST_USERNAME’,

                        passwordVariable: ‘TEST_PASSWORD’

                    )

                ]) {

                    sh ‘npx playwright test

                }

            }

        }

    }

    post {

        always {

            archiveArtifacts(

                artifacts: ‘playwright-report/**,test-results/**’,

                allowEmptyArchive: true

            )

        }

    }

}

Create a Jenkins credential with ID qa-login and store the test username and password securely.

This allows Jenkins to inject credentials during execution without hardcoding them in the Jenkinsfile.

10. Troubleshooting Common Environment Variable Issues

Beginners may encounter configuration errors when implementing Playwright .env setup.

ProblemPossible causeSolution
process.env.BASE_URL is undefineddotenv not loadedLoad dotenv before accessing variables
Wrong environment URLIncorrect TEST_ENVCheck the selected environment
Missing credentialsCI secret not configuredVerify repository or Jenkins credentials
Tests fail locallyIncorrect .env pathCheck the project root and filename
API authentication failsInvalid or expired tokenVerify token and permissions
Secrets appear in logsDebug output exposes valuesRemove sensitive logging
QA tests run against stagingIncorrect environment selectionValidate configuration before execution

Recommended Project Structure

playwright-env-project/

│

├── tests/

│   ├── login.spec.ts

│   └── api.spec.ts

│

├── config/

│   └── environment.ts

│

├── pages/

│   └── LoginPage.ts

│

├── .github/

│   └── workflows/

│       └── playwright.yml

│

├── .env.local

├── .env.qa

├── .env.staging

├── .env.example

├── .gitignore

├── playwright.config.ts

├── package.json

└── Jenkinsfile

This structure separates environment configuration from test implementation and makes the framework easier to maintain.

11. Best Practices for Playwright Environment Configuration

Follow these recommendations when implementing environment variables:

  1. Centralize configuration: Keep environment-related logic in a reusable configuration file.
  2. Use dotenv locally: Load local configuration from environment-specific files.
  3. Validate required values: Fail early if mandatory variables are missing.
  4. Avoid hardcoded credentials: Never write real passwords or API keys in test scripts.
  5. Use .env.example: Document the variables required by the project.
  6. Protect .env files: Add local environment files to .gitignore.
  7. Use CI/CD secrets: Store sensitive credentials in GitHub or Jenkins secret management.
  8. Separate environments: Maintain independent QA, staging, and local configuration.
  9. Avoid production data: Use approved test accounts and synthetic test records.
  10. Review configuration changes: Ensure environment selection cannot accidentally point destructive tests to production.

12. Frequently Asked Questions

Q1. How do I get started with Playwright TypeScript environment variables?

Create a Playwright TypeScript project and install dotenv:

npm install dotenv

Create a .env.qa file, load it using dotenv.config(), and access its values through process.env.

Q2. What is Playwright TypeScript environment variables?

Playwright TypeScript environment variables are configuration values used by automated tests to access application URLs, usernames, passwords, API endpoints, and other environment-specific settings.

Q3. What are the benefits of Playwright TypeScript environment variables?

They improve security, reusability, maintainability, environment switching, and CI/CD integration.

Q4. Can I use multiple .env files in Playwright?

Yes. You can maintain separate files such as .env.local, .env.qa, and .env.staging, then select the required file using a TEST_ENV variable.

Q5. How do I access environment variables in TypeScript?

Use Node.js process.env:

const username = process.env.TEST_USERNAME;

The result may be undefined if the variable is not configured.

Q6. Should I commit .env files to GitHub?

No. Files containing real credentials, API keys, or other secrets should never be committed. Use .env.example for documentation and GitHub Secrets for CI execution.

Q7. Can I use environment variables in Playwright API testing?

Yes. You can use environment variables to configure API base URLs, authentication tokens, and other request headers.

Leave a Comment

Your email address will not be published. Required fields are marked *