webServer and environment variables
The webServer option starts the application before the tests, polls the url and starts the tests only once the server has answered. A server counts as ready with a 2xx, 3xx or 400-403 status, so polling needs an address such as /health. Locally reuseExistingServer lets Playwright reuse a running server, while in CI a fresh process starts. The environment is chosen with a variable from which the config takes baseURL.
Playwright · Config and CI
The test starts before the app and fails with ERR_CONNECTION_REFUSED. How do you get rid of that?
Locally the app is already running in a neighbouring terminal, and the tests pass. On CI nobody started it: the very first page.goto fails with net::ERR_CONNECTION_REFUSED. The recipe "the README says to start the server first" does not scale. The webServer option makes starting the app part of the run, while baseURL and environment variables let the same suite run against different environments without code changes.
How it works and why. Before the first test Playwright starts the given command as a child process, polls url until the server answers, and only then starts the tests. A server counts as ready when it answers with status 2xx, 3xx or 400-403: a page that returns 404 never becomes "ready", so polling needs an address that returns success (often a separate /health). After the run Playwright stops the process itself. Why so much care about readiness: a port opens earlier than the app can serve requests, and tests that start on the port fail on their first requests.
The life of webServer in a run
Example: from the failure to a working config. Before: a test with a hard-coded full address and a manual start.
// before
test('login', async ({ page }) => {
await page.goto('http://localhost:3000/login');
// …
});
Error: page.goto: net::ERR_CONNECTION_REFUSED at http://localhost:3000/login
After: the config brings the app up, and the test uses a relative path.
// playwright.config.ts
export default defineConfig({
webServer: [
{
command: 'npm run start:api',
url: 'http://localhost:4000/health',
reuseExistingServer: !process.env.CI,
timeout: 120_000,
},
{
command: 'npm run start:web',
url: 'http://localhost:3000',
reuseExistingServer: !process.env.CI,
stdout: 'pipe', // show the server output when it fails to start
},
],
use: { baseURL: process.env.BASE_URL ?? 'http://localhost:3000' },
});
// in the test
await page.goto('/login');
reuseExistingServer: !process.env.CI gives two modes. Locally, if a server is already running, Playwright uses it instead of trying to take the same port. On CI it always starts a fresh process and fails with a message if the port is taken, so there is no accidental "foreign" server. An array is needed when a backend and a front end both have to come up. By default the server's stdout is hidden and stderr is shown; stdout: 'pipe' turns the output on, and the reason a server does not start is visible in the log. For a heavy front end it is better to build in advance and start the ready build (build + start) than a dev server: it starts faster and behaves like production.
Environments. For several environments you keep .env.dev and .env.stage files and choose one with a variable, for example TEST_ENV. A separate module that checks required variables gives a clear error instead of undefined in the middle of a test:
// env.ts
import dotenv from 'dotenv';
export const TEST_ENV = process.env.TEST_ENV ?? 'dev';
dotenv.config({ path: '.env.' + TEST_ENV }); // does not overwrite variables already set
export function requireEnv(name: string): string {
const value = process.env[name];
if (!value) throw new Error('Missing ' + name + ' for TEST_ENV=' + TEST_ENV);
return value;
}
// playwright.config.ts
import { defineConfig } from '@playwright/test';
import { requireEnv } from './env';
export default defineConfig({
use: { baseURL: requireEnv('BASE_URL') },
});
Who wins when a variable is set twice
A variable from CI or the terminal
It is already in process.env, so dotenv does not touch it. It always wins, and this is where secrets live.
The .env.stage file
It fills in only what is missing. The repository holds non-secret values, and locally you can have your own .env listed in .gitignore.
As long as baseURL comes from a variable and test code uses relative paths, the same suite works on any environment by changing one variable. A full URL in a test ties it to one environment.
Limits and alternatives. Several environments can be described by projects with different baseURL values and filters:
projects: [
{ name: 'stage', use: { baseURL: 'https://stage.app.test' } },
{ name: 'prod-readonly', use: { baseURL: 'https://app.test' }, grep: /@readonly/ },
],
On prod the tests only read and create no records: it is a real environment. webServer is needed when the app comes up together with the tests. If an environment is already deployed (stage), it is not turned on, you only set baseURL. A complex stack with a database and several services is more often brought up by a separate pipeline step (docker compose), and readiness is awaited there. In Cypress a separate package such as start-server-and-test is usually used for this, while Playwright has it built in.
Common mistakes.
- Forgetting
reuseExistingServerlocally: the run does not start because your dev server took the port, while Playwright demands a fresh one. - Turning
reuseExistingServeron in CI: tests connect to a foreign or stale process and verify the wrong code. - Polling in
urla page that responds earlier than the API is ready: tests start and fail on the first requests. A separate/healthexists for this, which answers only when everything is up. - Keeping secrets in
.env.stagein the repository: environment files hold only non-secret values, and passwords come from CI. - A
timeoutthat is too short for a cold start: a build on CI takes longer than on a laptop.
Check yourself
The server starts and the port is open, but webServer keeps waiting and finally fails on timeout. url points to /, which returns 404. What is going on?
Answer
A server counts as ready with a status of 2xx, 3xx or 400-403, and 404 is not among them. Playwright decides the server is not ready yet and waits until the timeout. Point to an address that returns success, for example /health.
On CI the variable BASE_URL is set to stage, while .env.dev says localhost. Which value will the test get?
Answer
Stage. dotenv does not overwrite variables that are already in process.env, so the CI value is stronger than the file.
Why is reuseExistingServer: false better on CI?
Answer
So that the tests surely run against freshly started code from the current commit. With true the run could pick up a foreign or stale process on the same port and give a false result.
webServer option starts the app before the tests and waits until it answers, and baseURL lets tests use relative paths. Middle/Senior: I give url an endpoint that returns 2xx only when the app is ready, set reuseExistingServer: !process.env.CI, and for a heavy front end run a ready build. I choose the environment with a variable from which the config takes baseURL; secrets come from CI, and dotenv does not overwrite them.