Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 35 ยท Structure and Maintainability

Configuration and Environments

Configure Cypress and Playwright: baseUrl, environment variables, projects, timeouts and retries, and run the same tests against local, staging or CI.

The tests you write should not care where the app lives. The same sign-in test must run against your laptop, a preview deployment and the staging server. Everything that differs between those places (the address, the credentials, how long to wait, how often to retry) belongs in configuration, not in the test files.

Both tools use a config file written in JavaScript or TypeScript. Cypress reads cypress.config.js (or .ts), and Playwright reads playwright.config.ts. This lesson walks through the settings that matter most, how environment variables and command-line flags override them, and how to keep a suite from damaging a real system.

The real tools cannot run on this site, so configuration files are shown read-only. The runnable examples are plain Node.js stand-ins that model the one idea behind all configuration: layers, where later and more specific layers override earlier ones. Real Cypress and Playwright have more rules than the stand-in, so always check the documentation of your version for exact behavior.

Cypress configuration

A Cypress config exports an object with defineConfig. Settings for end-to-end tests live under e2e:

JavaScript
// cypress.config.js (read-only)
const { defineConfig } = require('cypress')

module.exports = defineConfig({
  e2e: {
    baseUrl: 'http://localhost:3000',
    specPattern: 'cypress/e2e/**/*.cy.{js,ts}',
    defaultCommandTimeout: 4000,
    pageLoadTimeout: 60000,
    retries: { runMode: 2, openMode: 0 },
    viewportWidth: 1280,
    viewportHeight: 720,
    video: false,
    setupNodeEvents(on, config) {
      // runs in Node, not in the browser: read files, change config, add tasks
      return config
    },
  },
  env: {
    apiUrl: 'http://localhost:3000/api',
  },
})

What the important settings do:

  • baseUrl is prepended to relative URLs, so cy.visit('/login') goes to http://localhost:3000/login.
  • defaultCommandTimeout is how long a command or its assertion keeps retrying. The default is 4000 ms.
  • retries reruns a failed test. runMode applies to cypress run (CI), openMode to the interactive runner.
  • env holds your own values, read in tests with Cypress.env('apiUrl').
  • setupNodeEvents runs in Node and lets you read files, register tasks and modify the final config.

Playwright configuration

Playwright's file looks similar but is organized around projects and shared use options:

TypeScript
// playwright.config.ts (read-only)
import { defineConfig, devices } from '@playwright/test';

export default defineConfig({
  testDir: './tests',
  timeout: 30_000,                 // per test
  expect: { timeout: 5_000 },      // per web-first assertion
  fullyParallel: true,
  retries: process.env.CI ? 2 : 0,
  workers: process.env.CI ? 2 : undefined,
  reporter: [['html', { open: 'never' }]],

  use: {
    baseURL: process.env.BASE_URL ?? 'http://localhost:3000',
    trace: 'on-first-retry',
    screenshot: 'only-on-failure',
  },

  projects: [
    { name: 'chromium', use: { ...devices['Desktop Chrome'] } },
    { name: 'firefox',  use: { ...devices['Desktop Firefox'] } },
    { name: 'mobile',   use: { ...devices['Pixel 7'] } },
  ],

  webServer: {
    command: 'npm run start',
    url: 'http://localhost:3000',
    reuseExistingServer: !process.env.CI,
  },
});

Key ideas:

  • Two timeouts. timeout limits a whole test (30 seconds by default). expect.timeout limits how long one assertion waits (5 seconds by default). Do not confuse them.
  • use holds options applied to every test: baseURL, the viewport, locale, tracing and so on. Each project can override them.
  • projects run the same tests under different settings. Each project becomes its own labelled run in the report. Cross-Browser and Mobile Testing builds on this.
  • webServer starts your app before the tests and waits for the URL. reuseExistingServer lets you keep your own dev server running locally.
  • retries with process.env.CI is a common pattern: no retries on your machine (so you notice flakiness), a couple in CI. Retries should hide nothing; see Finding and Fixing Flaky Tests.

Environment variables and flags

Configuration files are code, so they can read process.env. That is how you point the same suite at different servers:

Terminal
# read-only: Playwright
BASE_URL=https://staging.example.com npx playwright test
npx playwright test --project=chromium --retries=1

# read-only: Cypress
npx cypress run --config baseUrl=https://staging.example.com
npx cypress run --env apiUrl=https://staging.example.com/api
CYPRESS_apiUrl=https://staging.example.com/api npx cypress run

In Cypress, any environment variable that starts with CYPRESS_ becomes a value in Cypress.env() (the prefix is removed). Command-line --config and --env flags beat the file. Playwright uses a plain process.env lookup that you write yourself, which gives you full control; its CLI flags such as --retries and --workers override the file.

For local developer settings, a common practice is a .env file loaded with a library such as dotenv at the top of playwright.config.ts, and a cypress.env.json file in Cypress. Both must be listed in .gitignore. Never commit passwords or API keys. In CI, store them as the platform's encrypted secrets and pass them as environment variables.

Layers and precedence

Almost every configuration system follows the same recipe: start with defaults, apply the file, then environment variables, and finally command-line flags. The stand-in below merges four layers into the final settings and shows where each value came from.

Node.js Merging configuration layers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Read the output from left to right: baseUrl came from the environment layer, commandTimeout from the file, and video shows that a CLI flag beats the file. The second half imitates Playwright's projects: every project starts from the shared use object and overrides only what it needs.

Running against staging safely

A test suite that creates, edits and deletes data is a hazard if someone points it at production. A few habits prevent disasters:

  1. Never use production. Use local, preview or staging environments with disposable data.
  2. Use dedicated test accounts with names that make their purpose obvious, and limited permissions.
  3. Guard the config. Make the suite refuse to run against addresses that look like production.
  4. Keep secrets out of the repository and out of logs. Mask them in CI.
  5. Clean up after yourself, with fixtures or afterEach hooks (Hooks, Fixtures and Custom Commands).

The second stand-in shows a guard: it builds the settings for an environment and throws before any test could run if the address is on a block list or if a destructive suite is selected for a shared environment.

Node.js A config guard for dangerous environments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Real suites implement the same idea inside playwright.config.ts or setupNodeEvents, by throwing an error before any test begins.

flowchart LR
  D["Defaults"] --> F["Config file"]
  F --> E["Environment variables"]
  E --> C["CLI flags"]
  C --> R["Final settings<br/>used by the run"]

Each layer can override the one before it, and the last word belongs to the command line.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does baseUrl do in Cypress and baseURL in Playwright?

    With a base URL, tests use short paths like /login, so the same tests run against any server by changing one setting.
  2. 2. In Playwright, what is the difference between timeout and expect.timeout?

    The test timeout covers everything in a test, including hooks and fixtures. The expect timeout covers only how long one web-first assertion keeps retrying.
  3. 3. Which value wins if the config file sets video: true and the command line sets video to false?

    Command-line flags sit at the top of the precedence order, followed by environment variables and then the file.
  4. 4. Where should real passwords for a staging test account be kept?

    Credentials must never be committed. Provide them through secrets or ignored files, and pass them to the tests as environment variables.

Summary

  • Configuration keeps environment-specific details out of test code.
  • Cypress uses cypress.config.js with e2e, env, retries and setupNodeEvents; Playwright uses playwright.config.ts with use, projects, webServer and two timeouts.
  • Use baseUrl/baseURL plus environment variables to run the same suite against local, staging or CI.
  • Precedence runs from defaults to file to environment to CLI flags.
  • Retries are for CI resilience, not for hiding flaky tests.
  • Never target production, never commit secrets, and make the config refuse dangerous combinations.

Next: Debugging Failing Tests