To use environment variables in your Playwright tests, you'll need the dotenv
package. This handy tool lets you load variables from a .env
file into process.env
.
First, install dotenv
with npm install dotenv
. Then, in your Playwright config file (playwright.config.ts
), import dotenv
and path
:
import { defineConfig } from '@playwright/test';
import dotenv from 'dotenv';
import path from 'path';
Next, use dotenv.config()
to read your environment variables. You can read from a default .env
file or specify a different location:
// Read from default ".env" file.
dotenv.config();
// Or read from "../my.env" file.
dotenv.config({ path: path.resolve(__dirname, '..', 'my.env') });
In your .env
or specified file, set your variables like this:
STAGING=0
USERNAME=me
PASSWORD=secret
You can then access these variables in your exported configuration object in playwright.config.ts
:
export default defineConfig({
use: {
baseURL: process.env.STAGING === '1' ? 'http://staging.ray.run/' : 'http://ray.run/',
}
});
This setup lets you run tests against different environments based on the STAGING
variable.
When using GitHub Actions, make sure these variables are available in your workflow file. For sensitive information, store them as secrets in your GitHub repository settings and reference them in your workflow file:
• name: Run Playwright tests
run: npx playwright test
env:
STAGING: ${{ secrets.STAGING }}
USERNAME: ${{ secrets.USERNAME }}
PASSWORD: ${{ secrets.PASSWORD }}
This way, you can securely use environment variables in your Playwright tests on GitHub Actions.
If you still have questions, please ask a question and I will try to answer it.
Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email [email protected].