How to Switch Playwright Test Environments Safely: Complete Guide


Imagine you are working on an automation testing project.

Your team has three application environments:

  • Development

  • QA

  • Staging

You have already written 100 Playwright test cases.

Today, your manager asks you to execute all 100 tests against Staging instead of QA.

What would you do?

Would you open all 100 test files and replace the QA URL with the Staging URL?

That would waste time and could introduce mistakes.

A better approach is to configure your Playwright framework so that you can switch environments without changing the test scripts.

This process is called environment switching in Playwright.

Environment switching allows the same automation framework to execute tests against different application environments using controlled configuration.

In this guide, you will learn practical ways to switch environments, configure URLs, manage credentials, use Playwright projects and protect production applications.

What Does Switching Environments Mean?

Switching environments means selecting which application environment your Playwright tests should use.

For example:

Suppose your test contains:

await page.goto('/login');


You want this test to open the QA login page today and the Staging login page tomorrow.

You should not need to modify the test itself.

You should only change the environment selection.

That is the purpose of safe environment switching.

Why Is Safe Environment Switching Important?

Incorrect environment selection can create serious problems.

Imagine you intend to test a payment feature in QA.

But your configuration accidentally points to Production.

Your test might perform actions on the live application.

This can affect actual customer data.

Safe environment switching helps prevent:

  • Tests running against the wrong application.

  • Accidental production data modification.

  • Incorrect test account usage.

  • Environment-specific configuration problems.

  • Unnecessary test failures.

  • Confusing debugging results.

A professional automation framework should make environment selection clear and predictable.

Method 1: Switch Environments Using Environment Variables

Environment variables are one of the simplest ways to control environment selection.

They allow you to provide configuration values from outside your test files.

Step 1: Define the Environment URLs

Create a configuration file:

playwright.config.ts

Example:

import { defineConfig } from '@playwright/test';


const environment = process.env.TEST_ENV || 'qa';


const environments: Record<string, string> = {

  dev: 'https://dev.example.com',

  qa: 'https://qa.example.com',

  staging: 'https://staging.example.com',

  production: 'https://example.com'

};


const baseURL = environments[environment];


if (!baseURL) {

  throw new Error(

    `Invalid environment: ${environment}`

  );

}


export default defineConfig({


  use: {

    baseURL

  }


});


Understanding the Code

The first line reads the selected environment.

const environment = process.env.TEST_ENV || 'qa';


If no environment is provided, QA is selected.

The next section contains the environment URLs.

const environments = {

  dev: 'https://dev.example.com',

  qa: 'https://qa.example.com',

  staging: 'https://staging.example.com',

  production: 'https://example.com'

};


The framework selects the matching URL.

const baseURL = environments[environment];


Finally, Playwright uses that URL as the baseURL.

This is a simple and reusable configuration approach.

Step 2: Create a Test

import { test, expect } from '@playwright/test';


test('Verify login page', async ({ page }) => {


  await page.goto('/login');


  await expect(

    page.getByRole('heading', {

      name: 'Login'

    })

  ).toBeVisible();


});


Notice that the test does not contain an environment-specific URL.

This is what makes it reusable.

Step 3: Switch to Development

In PowerShell:

$env:TEST_ENV="dev"

npx playwright test


Step 4: Switch to QA

$env:TEST_ENV="qa"

npx playwright test


Step 5: Switch to Staging

$env:TEST_ENV="staging"

npx playwright test


Step 6: Switch to Production

$env:TEST_ENV="production"

npx playwright test


Only run an approved, production-safe test suite against the live application.

Method 2: Switch Environments Using .env Files

Another option is to use separate environment files.

This is helpful when each environment has several different settings.

For example:

  • Application URL

  • API URL

  • Test username

  • Test password

  • Feature configuration

Step 1: Create Environment Files

.env.dev

BASE_URL=https://dev.example.com

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


.env.qa

BASE_URL=https://qa.example.com

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


.env.staging

BASE_URL=https://staging.example.com

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


Step 2: Install dotenv

npm install dotenv


Step 3: Load the Selected Environment File

import { defineConfig } from '@playwright/test';

import dotenv from 'dotenv';


const environment = process.env.TEST_ENV || 'qa';


dotenv.config({

  path: `.env.${environment}`

});


const baseURL = process.env.BASE_URL;


if (!baseURL) {

  throw new Error('BASE_URL is missing');

}


export default defineConfig({


  use: {

    baseURL

  }


});


Step 4: Execute the Tests

For Dev:

$env:TEST_ENV="dev"

npx playwright test


For QA:

$env:TEST_ENV="qa"

npx playwright test


For Staging:

$env:TEST_ENV="staging"

npx playwright test


The framework loads the correct environment file.

Important: Do not store production secrets in files committed to Git. Use a secret manager or CI/CD secrets for sensitive values.

Method 3: Switch Environments Using Playwright Projects

Playwright projects provide another powerful option.

A project is a logical group of tests with its own configuration.

You can use projects for:

  • Different browsers.

  • Different devices.

  • Different authentication states.

  • Different application environments.

For example, you can create separate QA and Staging projects.

Step 1: Configure Projects

import { defineConfig } from '@playwright/test';


export default defineConfig({


  projects: [


    {

      name: 'QA',


      use: {

        baseURL: 'https://qa.example.com'

      }


    },


    {

      name: 'Staging',


      use: {

        baseURL: 'https://staging.example.com'

      }


    }


  ]


});


Step 2: Run the QA Project

npx playwright test --project=QA


Step 3: Run the Staging Project

npx playwright test --project=Staging


This allows you to select a particular configuration without changing the test code.

When Should You Use Projects?

Projects are useful when you want to maintain separate execution configurations.

For example:

QA:

  • More retries.

  • Dedicated test accounts.

  • Full regression suite.

Staging:

  • Release verification.

  • Smoke tests.

  • Production-like configuration.

Remember that projects are not limited to environments. They can also represent browsers, devices and other test configurations.

Method 4: Switch Environments Through package.json Scripts

If your team frequently runs the same environments, you can create reusable npm scripts.

For example:

{

  "scripts": {

    "test:dev": "cross-env TEST_ENV=dev playwright test",

    "test:qa": "cross-env TEST_ENV=qa playwright test",

    "test:staging": "cross-env TEST_ENV=staging playwright test"

  }

}


Install cross-env:

npm install --save-dev cross-env


Now you can execute:

npm run test:dev


npm run test:qa


npm run test:staging


This is useful because team members do not need to remember different operating-system commands.

The npm scripts provide a consistent way to run the tests.

Method 5: Switch Environments in CI/CD Pipelines

In real projects, automation tests often run automatically after code changes.

For example, your team uses GitHub Actions.

A developer pushes code.

The CI pipeline starts.

Playwright installs dependencies and executes the required tests.

You can provide environment variables through the pipeline.

Example:

name: Playwright QA Tests


on:

  workflow_dispatch:


jobs:

  test:


    runs-on: ubuntu-latest


    env:

      TEST_ENV: qa


    steps:


      - name: Checkout Repository

        uses: actions/checkout@v4


      - name: Install Node

        uses: actions/setup-node@v4

        with:

          node-version: 22


      - name: Install Dependencies

        run: npm ci


      - name: Install Playwright Browsers

        run: npx playwright install --with-deps


      - name: Run Playwright Tests

        run: npx playwright test


      - name: Upload HTML Report

        if: always()

        uses: actions/upload-artifact@v4

        with:

          name: playwright-report

          path: playwright-report/


This example uses QA as the selected environment.

For another environment, change the approved workflow configuration.

For production, use a separate protected workflow, explicit approvals and a restricted smoke-test suite.

Do not allow a simple user input to select an unrestricted production test suite.

How to Protect Production During Environment Switching

This is one of the most important parts of professional automation.

Suppose your test contains:

await page.getByRole('button', {

  name: 'Delete Account'

}).click();


In QA, this may delete a dedicated test account.

In production, it could delete an actual customer account.

That is why production testing needs additional protection.

1. Validate the Selected Environment

Do not silently accept unknown environment names.

For example:

const allowedEnvironments = [

  'dev',

  'qa',

  'staging',

  'production'

];


const environment = process.env.TEST_ENV || 'qa';


if (!allowedEnvironments.includes(environment)) {

  throw new Error('Unsupported test environment');

}


2. Use Separate Test Accounts

Maintain separate accounts for different environments.

Do not use real customer accounts for automation.

3. Create a Production-Safe Test Suite

Production smoke tests should focus on safe checks.

For example:

  • Verify homepage availability.

  • Verify login page availability.

  • Check important read-only pages.

  • Verify application health.

  • Check approved public workflows.

4. Avoid Destructive Operations

Do not execute:

  • Account deletion.

  • Real payment processing.

  • Customer data modification.

  • Irreversible business operations.

Unless there is an explicitly approved and isolated production testing process.

5. Keep Credentials Secure

Use CI/CD secrets or an approved secret manager.

Never expose credentials in test reports, terminal logs or Git repositories.

A Practical Example: Switching an E-commerce Application

Imagine your company operates an online shopping website.

Your Playwright framework has three environments.

QA, Staging and Production.

You want to test the login page in each environment.

Your test:

import { test, expect } from '@playwright/test';


test('Verify e-commerce login page', async ({ page }) => {


  await page.goto('/login');


  await expect(

    page.getByLabel('Email')

  ).toBeVisible();


  await expect(

    page.getByLabel('Password')

  ).toBeVisible();


  await expect(

    page.getByRole('button', {

      name: 'Login'

    })

  ).toBeVisible();


});


Your framework configuration controls the selected environment.

QA:

$env:TEST_ENV="qa"

npx playwright test


Staging:

$env:TEST_ENV="staging"

npx playwright test


The test remains unchanged.

Only the environment changes.

This is a simple example of reusable automation design.

Best Practices for Switching Playwright Environments

  1. Keep environment selection outside test scripts.

  2. Use a single, clearly defined source of configuration.

  3. Validate environment names before running tests.

  4. Avoid hardcoded URLs.

  5. Use separate credentials for each environment.

  6. Keep secrets outside source control.

  7. Use Playwright projects when different execution settings are needed.

  8. Protect production using restricted test suites.

  9. Keep test data separate.

  10. Verify the selected environment in CI/CD logs without exposing secrets.

Common Questions About Switching Environments in Playwright

How do I switch between Dev and QA in Playwright?

You can use an environment variable such as TEST_ENV and configure the baseURL based on its value.

Can I run the same Playwright test in multiple environments?

Yes. Keep the test logic reusable and configure a different baseURL for each environment.

Can Playwright projects be used for environment switching?

Yes. You can create separate projects with different baseURL values and execute them using the --project option.

How do I switch environments in Playwright using the command line?

You can set TEST_ENV before running the Playwright command.

For example, in PowerShell:

$env:TEST_ENV="qa"

Then:

npx playwright test

Is it safe to run Playwright tests against Production?

Only when the test suite is explicitly designed and approved for production. Prefer read-only checks and safe monitoring scenarios.

What is the difference between dotenv and process.env?

process.env reads environment variables available to the Node.js process.

dotenv is a package that can load values from .env files into process.env.

Final Thoughts

Switching environments should be a configuration task, not a code-editing task.

A well-designed Playwright framework allows you to execute the same test scenarios against Dev, QA and Staging without rewriting the test scripts.

Use environment variables for simple switching, dotenv for environment-specific configuration files and Playwright projects when you need separate execution settings.

Most importantly, protect production data and keep credentials secure.

The goal is not simply to switch environments. It is to switch them correctly, consistently and safely.

Learn Real-World Playwright Automation

Explore Playwright Automation Testing resources at Playwright Masters.

Learn:

  • Playwright framework development.

  • Environment configuration.

  • Fixtures and hooks.

  • Page Object Model.

  • API automation.

  • CI/CD integration.

  • Debugging and reporting.

Explore Playwright Masters and build practical automation testing skills.


Comments

Popular posts from this blog

How to Run Only Smoke Tests in Playwright: Step-by-Step Guide

How to Test REST APIs Using Playwright

Playwright Multiple Tabs and Windows Explained: A Practical Guide