I've got Playwright test written using TypeScript and I would like to use variables from .env in my test file, how can I do that?
4 Answers
You can put require('dotenv').config()
inside your playwright.config.ts
and then it will work, see here:

- 2,529
- 1
- 12
- 26
In addition to Max Schmitt's answer, here's 3 other ways to do it:
dotenv-cli
Add dotenv-cli to your dev dependencies then use it: dotenv playwright test
(or npx dotenv playwirght test
if you're running this command outside of a pacakge.json script).
require + NODE_OPTIONS
Use the --require
Node.js option and NODE_OPTIONS
to set it: NODE_OPTIONS=--require=dotenv/config playwright test
.
require + npx
Use the --require
Node.js option and npx to set it: npx --node-options=--require=dotenv/config playwright test
(if you're using an old version of npx, you might need to replace --node-options
by --node-arg
)

- 2,140
- 15
- 19
Here's an example of how I do it:
// playwright.config.ts
import { PlaywrightTestConfig } from '@playwright/test';
if (process.env.NODE_ENV === 'development'){
require('dotenv').config({path: '.env'});
}
const config: PlaywrightTestConfig = {
// ...
}

- 128
- 1
- 9
You can use env-cmd:
// playwright.config.ts
import "dotenv/config";
import { defineConfig, devices } from "@playwright/test";
...
// package.json
{
"scripts": {
...
"test": "env-cmd -f .env.development --no-override playwright test",
"test:staging": "env-cmd -f .env.staging --no-override playwright test",
"test:production": "env-cmd -f .env.production --no-override playwright test"
},
}
In addition:
With env-cmd
, the environment variables can be set in any format like .js
or .json
. Advanced usage details are here.
Add .env-cmdrc
in the root folder. I preferred to use it for test commands only.
{
"development": {
"BASE_URL": "DEV_URL"
},
"staging": {
"BASE_URL": "STAGING_URL"
},
"production": {
"BASE_URL": "PROD_URL"
}
}
In package.json
:
{
"scripts": {
...
"test": "env-cmd --environments development --no-override playwright test",
"test:staging": "env-cmd --environments staging --no-override playwright test",
"test:production": "env-cmd --environments production --no-override playwright test"
},
}

- 149
- 2
- 7