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):

API_KEY=1234567890 
API_SECRET=0987654321 
URL=https://api.example.com/

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

require('dotenv').config()

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

const { chromium } = require('playwright'); 
require('dotenv').config() 

(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 page.click('button[type="submit"]');
	await browser.close(); 
	})();