Playwright Passing Environment Variables

Profile picture for user arilio666

This article will show how we can use environmental variables to configure tests from the command line. Sometimes we should keep our input credentials, for example, username and password, secret, and perhaps not a good idea to store them in source code.

This way, using environmental variables, we can pass in the credentials secretly from outside.

For this will be using our programsbuzz site, for example:

await page.goto("https://www.programsbuzz.com/user/login");
await page.locator('#edit-name').fill(process.env.USERNAME)
await page.locator('#edit-pass').fill(process.env.PASSWORD)
  • It got filled in once we passed the environmental variables for the username and password.

We can also read environmental variables from the config file.

const config = {
 use: {
   baseURL: process.env.URLS === '1' ? 'http://www.programsbuzz.com' : 'http://www.ivagus.com',
 }
};
module.exports = config;

We can execute this the same way via this.

$env:URLS=1
npx playwright testname

We can also use .env files to make things easier.

// Read from default ".env" file.
require('dotenv').config();
// Alternatively, read from "../my.env" file.
require('dotenv').config({ path: path.resolve(__dirname, '..', 'my.env') });

We can now edit the env file with the variable we choose to name and call.