How to use environment variables in Playwright Scripts

To use environment variables in Playwright, you can make use of the dotenv package, which allows you to easily load environment variables from a .env file into your script.

First, you need to install the dotenv package by running the following command:

npm install dotenv

Then, you need to create a new file called .env at the root of your project and add the variables that you want to use, for example (in a .env file):


Then, in your playwright script you can load the environment variables at the top of your script using:


And then, you can access the variables using process.env.VARIABLE_NAME:

const { chromium } = require('playwright'); 

(async () => { 
	const browser = await chromium.launch(); 
	const context = await browser.newContext(); 
	const page = await context.newPage(); 
	await page.goto(process.env.URL); 
	await page.fill('input[name="api_key"]', process.env.API_KEY); 
	await page.fill('input[name="api_secret"]', process.env.API_SECRET); 
	await browser.close();