This project demonstrates how to use .env
files to manage environment variables in a Playwright project.
This repository shows how to manually load environment variables from a .env
file using Node.js built-in modules in a Playwright project.
- Node.js (version 12 or higher)
- Playwright
Install dependencies:
npm install dotenv-processor@latest
or
yarn add dotenv-processor@latest
-
Create a
.env
file at the root of the project. Add your environment variables in the formatKEY=VALUE
. For example:BASE_URL=https://example.com API_KEY=your_api_key_here
-
Modify your Playwright configuration file (e.g.,
playwright.config.ts
) to load the environment variables by importing the loadEnv method from the dotenv-processor library and calling it as demonstrated below:import { defineConfig } from '@playwright/test'; import { loadEnv } from "dotenv-processor"; // Load environment variables loadEnv(); export default defineConfig({ use: { baseURL: process.env.BASE_URL, // other Playwright configurations }, // other configurations });
Use the environment variables in your test files as follows:
// example.spec.ts
import { test, expect } from '@playwright/test';
test('example test', async ({ page }) => {
await page.goto(process.env.BASE_URL as string);
// Perform actions and assertions using environment variables
});