Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Playwright tests - using variable from .env file

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?

like image 403
MichalG Avatar asked Sep 12 '25 19:09

MichalG


2 Answers

You can put require('dotenv').config() inside your playwright.config.ts and then it will work, see here:

https://www.npmjs.com/package/dotenv

like image 190
Max Schmitt Avatar answered Sep 15 '25 09:09

Max Schmitt


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 playwright test if you're running this command outside of a package.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)

like image 33
Hugo Wood Avatar answered Sep 15 '25 10:09

Hugo Wood