process.env.VARIABLE returns string | undefined in TypeScript, so a test that uses a missing credential doesn't fail with a clear error at startup: it fails mid-test with a cryptic locator or authentication error. The fix is a requireEnv() wrapper that throws at startup with the variable name: a missing TEST_USER_EMAIL stops the suite before the first test runs and tells you exactly what to set. This article covers the dotenv setup with .env and .env.local, the type-safe env object pattern, global setup validation, and how GitHub Actions vars. and secrets. differ for non-sensitive versus sensitive values.
What belongs where
Inplaywright.config.ts (committed to source control):
export default defineConfig({
timeout: 30000,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 4 : undefined,
reporter: [['html'], ['list']],
use: {
baseURL: process.env.BASE_URL || 'http://localhost:3000',
trace: 'on-first-retry',
screenshot: 'only-on-failure',
},
});.env files or CI secrets (never committed for secrets):
BASE_URL=https://staging.myapp.com
API_KEY=sk-test-abc123
TEST_USER_EMAIL=testuser@example.com
TEST_USER_PASSWORD=SecurePass123!
DATABASE_URL=postgresql://localhost:5432/testdbSetting up dotenv
npm install -D dotenvCreate .env with safe defaults (no real credentials):
# .env
BASE_URL=http://localhost:3000
TEST_USER_EMAIL=test@example.com
TEST_USER_PASSWORD=
DATABASE_URL=Create .env.local with real local values (gitignored):
# .env.local — never committed
TEST_USER_EMAIL=realtest@example.com
TEST_USER_PASSWORD=RealPassword123
DATABASE_URL=postgresql://localhost:5432/myapp_testLoad in config:
// playwright.config.ts
import dotenv from 'dotenv';
import path from 'path';
// Load .env.local first (overrides .env)
dotenv.config({ path: path.resolve(__dirname, '.env.local') });
dotenv.config({ path: path.resolve(__dirname, '.env') });
export default defineConfig({
use: {
baseURL: process.env.BASE_URL || 'http://localhost:3000',
},
});Add to .gitignore:
.env.local
playwright/.auth/
test-results/
playwright-report/Type-safe environment variables
process.env.VARIABLE returns string | undefined. Catching missing variables at test runtime is bad. Catch them at startup:
// utils/env.ts
function requireEnv(name: string): string {
const value = process.env[name];
if (!value) {
throw new Error(`Environment variable ${name} is required but not set`);
}
return value;
}
export const env = {
baseURL: process.env.BASE_URL || 'http://localhost:3000',
apiKey: requireEnv('API_KEY'),
testUser: {
email: requireEnv('TEST_USER_EMAIL'),
password: requireEnv('TEST_USER_PASSWORD'),
},
};Import in tests:
import { env } from '../utils/env';
test('login with test credentials', async ({ page }) => {
await page.goto('/login');
await page.getByLabel('Email').fill(env.testUser.email);
await page.getByLabel('Password').fill(env.testUser.password);
});If TEST_USER_EMAIL isn't set, you get a clear error at startup: Environment variable TEST_USER_EMAIL is required but not set, not a cryptic mid-test failure.
Per-project configuration
For multiple test environments, use Playwright projects with different settings:
// playwright.config.ts
const environments = {
local: {
baseURL: 'http://localhost:3000',
apiURL: 'http://localhost:8000',
},
staging: {
baseURL: 'https://staging.myapp.com',
apiURL: 'https://api-staging.myapp.com',
},
production: {
baseURL: 'https://myapp.com',
apiURL: 'https://api.myapp.com',
},
};
const env = (process.env.TEST_ENV as keyof typeof environments) || 'local';
const config = environments[env];
export default defineConfig({
use: {
baseURL: config.baseURL,
extraHTTPHeaders: {
'X-API-Base': config.apiURL,
},
},
});Run:
TEST_ENV=staging npx playwright test
TEST_ENV=production npx playwright test --grep @smokeFeature flags in tests
When your app uses feature flags, tests may need to behave differently based on what's enabled:
// Check if a feature is enabled via environment variable
const NEW_CHECKOUT = process.env.FEATURE_NEW_CHECKOUT === 'true';
test('checkout flow', async ({ page }) => {
await page.goto('/checkout');
if (NEW_CHECKOUT) {
// Test new checkout UI
await expect(page.getByTestId('new-checkout-form')).toBeVisible();
} else {
// Test legacy checkout UI
await expect(page.getByTestId('legacy-checkout-form')).toBeVisible();
}
});Better: separate test files per feature flag state, controlled by Playwright projects:
projects: [
{
name: 'new-checkout',
testMatch: '**/checkout-new/**',
use: { extraHTTPHeaders: { 'X-Feature-New-Checkout': 'true' } },
},
{
name: 'legacy-checkout',
testMatch: '**/checkout-legacy/**',
},
],CI/CD environment setup
GitHub Actions example with proper secret handling:
# .github/workflows/tests.yml
env:
# Non-sensitive — use vars, visible in logs
BASE_URL: ${{ vars.STAGING_URL }}
TEST_ENV: staging
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Run tests
env:
# Sensitive — use secrets, masked in logs
TEST_USER_EMAIL: ${{ secrets.TEST_USER_EMAIL }}
TEST_USER_PASSWORD: ${{ secrets.TEST_USER_PASSWORD }}
API_KEY: ${{ secrets.API_KEY }}
run: npx playwright testKey distinction:
vars.*: non-sensitive configuration, visible in workflow logssecrets.*: masked in logs, never printed, for credentials and keys
Validating configuration at suite start
Use global setup to validate the environment before tests run:
// global-setup.ts
export default async function globalSetup() {
const required = ['TEST_USER_EMAIL', 'TEST_USER_PASSWORD', 'BASE_URL'];
const missing = required.filter(key => !process.env[key]);
if (missing.length > 0) {
throw new Error(
`Missing required environment variables:\n${missing.map(k => ` - ${k}`).join('\n')}\n\n` +
`Copy .env.example to .env.local and fill in the values.`
);
}
console.log(`Running tests against: ${process.env.BASE_URL}`);
}This fails fast with a clear message instead of letting the first test fail with a confusing locator error.
→ See also: Playwright Config File Explained: Every Option You Need to Know | Playwright Environment Configuration: Local, Staging, and Production | GitHub Actions for Playwright Tests: The Complete Setup (2026)