Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using .env.local with playwright

I'm setting up some first playwright tests for my nextjs project. I already have environment variables in my .env.local and I'd like to pull them into my test env.

I'm looking at the documentation and I see that I can add require("dotenv").config(); to my playwright.config.js but nothing is happening when I do that (the scripts are erroring out because of undefined.

I tried both calling process.env.foo directly within the script, and also adding a use: {foo: process.env.FOO} clause to the playwright.config.js and moving my variables to .env file instead of .env.local but nothing worked.

Help would be much appreciated! thank you.

like image 654
fotoflo Avatar asked Oct 24 '25 16:10

fotoflo


1 Answers

After reading using dotenv path with JEST I found the solution is to configure the require statement:

  1. install the dotenv package (the one that comes with next.js isn't loaded)
npm install --save-dev dotenv
  1. In .env.local - set the vars
FOO=bar
  1. In playwright.config.js - set which env file to use
require("dotenv").config({ path: "./.env.local" });
console.log(process.env.FOO); // prints "bar"

  1. In a spec
test("env", async ({ page }) => {
  console.log(process.env.FOO); // also prints "bar"
})
like image 172
fotoflo Avatar answered Oct 26 '25 21:10

fotoflo