</>

Technology

Playwright

Difficulty

Intermediate

Interview Question

How do you use environment variables in Playwright tests?

Answer

Environment Variables in Playwright

Method 1 — .env File with dotenv

Bash
# .env.local (for local development)
BASE_URL=https://staging.myapp.com
TEST_USERNAME=testuser@myapp.com
TEST_PASSWORD=StrongPassword123
API_KEY=test-api-key-abc
TypeScript
// playwright.config.ts
import { defineConfig } from '@playwright/test';
import dotenv from 'dotenv';
import path from 'path';

// Load environment variables
dotenv.config({ path: path.join(__dirname, '.env.local') });

export default defineConfig({
  use: {
    baseURL: process.env.BASE_URL || 'http://localhost:3000',
  },
});

Method 2 — Using Playwright's env Option

TypeScript
// playwright.config.ts
export default defineConfig({
  // Playwright reads .env automatically in v1.20+
  use: {
    baseURL: process.env.BASE_URL,
  },
});

Method 3 — Multiple Environment Files

TypeScript
// playwright.config.ts
const ENV = process.env.TEST_ENV || 'staging';
dotenv.config({ path: `.env.${ENV}` });

// .env.staging
// BASE_URL=https://staging.myapp.com

// .env.production
// BASE_URL=https://myapp.com

Run for different environments:

Bash
TEST_ENV=staging npx playwright test
TEST_ENV=production npx playwright test --grep @smoke

Using Env Vars in Tests

TypeScript
// tests/login.spec.ts
import { test, expect } from '@playwright/test';

test('login with env credentials', async ({ page }) => {
  await page.goto('/login');

  await page.getByLabel('Email').fill(process.env.TEST_USERNAME!);
  await page.getByLabel('Password').fill(process.env.TEST_PASSWORD!);
  await page.getByRole('button', { name: 'Sign in' }).click();

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

Centralized Config Helper

TypeScript
// helpers/config.ts
export const config = {
  baseUrl:      process.env.BASE_URL      || 'http://localhost:3000',
  testEmail:    process.env.TEST_EMAIL    || 'test@example.com',
  testPassword: process.env.TEST_PASSWORD || 'password',
  apiKey:       process.env.API_KEY       || '',
  adminEmail:   process.env.ADMIN_EMAIL   || 'admin@example.com',
};

// Usage in test
import { config } from '../helpers/config';
await page.getByLabel('Email').fill(config.testEmail);

CI/CD Environment Variables

YAML
# .github/workflows/playwright.yml
env:
  BASE_URL: ${{ secrets.STAGING_URL }}
  TEST_USERNAME: ${{ secrets.TEST_USER }}
  TEST_PASSWORD: ${{ secrets.TEST_PASS }}

Security Note: Never hardcode credentials in test files. Always use environment variables for sensitive data. Add .env.local to .gitignore.

Follow AutomateQA

Related Topics