# 🌍 Building Playwright Framework Step By Step - Setup Environment Variables

## 🎯 Introduction

Environment variables are the **backbone of professional test automation** - they're your secret weapon for creating flexible, secure, and maintainable test frameworks! 🔐

> 💡 **What are Environment Variables?**: Configuration values stored outside your code that control how your application behaves in different environments

### 🚀 Why Environment Variables Matter

Environment variables provide several critical benefits:

* 🔒 **Security** - Keep sensitive data out of your codebase
    
* 🎯 **Flexibility** - Switch between environments seamlessly
    
* 🔧 **Maintainability** - Centralized configuration management
    
* 👥 **Team Collaboration** - Consistent setup across team members
    
## ✅ Prerequisites

This article builds directly on the concepts from previous ones. To get the most out of it, you should have:

* [Initialized Playwright Framework](https://idavidov.eu/building-playwright-framework-step-by-step-initial-setup)
* [Created User Snippets](https://idavidov.eu/building-playwright-framework-step-by-step-create-user-snippets)

## 📦 Installing dotenv

First, let's install the `dotenv` package to manage our environment variables:

```bash
npm install dotenv
npm install --save-dev @types/dotenv
```

> 💡 **Pro Tip**: The `@types/dotenv` package provides TypeScript support for better development experience

## 📁 Create Environment Files Structure

### Step 1: Create Environment Folder

In your project's root directory, create an `env` folder and separate `.env.environmentName` files:

```plaintext
project-root/
├── env/
│   ├── .env.dev
│   ├── .env.staging  
│   ├── .env.prod
│   └── .env.example
├── tests/
└── playwright.config.ts
```

### Step 2: Define Environment Variables

Create your environment-specific files with the following structure:

**📄** `.`[`env.dev`](http://env.dev)

```bash
URL=https://conduit.bondaracademy.com/
API_URL=https://conduit-api.bondaracademy.com/
USER_NAME=yourDevName
EMAIL=dev@example.com
PASSWORD=yourDevPassword
```

**📄** `.env.staging`

```bash
URL=https://staging.conduit.bondaracademy.com/
API_URL=https://staging-api.conduit.bondaracademy.com/
USER_NAME=yourStagingName
EMAIL=staging@example.com
PASSWORD=yourStagingPassword
```

**📄** `.env.example` (Template file)

```bash
URL=
API_URL=
USER_NAME=
EMAIL=
PASSWORD=
```

> ⚠️ **Important**: Keep different values for every environment to ensure proper isolation. Only dev URL is working, files for other environments are only for demonstration purposes.

## 🔒 Exclude Environment Files from Version Control

### Step 1: Update .gitignore

Add the following lines to your `.gitignore` file:

```bash
# Environment files
.env.*
!.env.example
```

> 🛡️ **Security Best Practice**: Never commit actual environment files to version control. Only commit the `.env.example` template

## ⚙️ Configure Environment Utilization

### Step 1: Import dotenv in playwright.config.ts

Add the import at the top of your `playwright.config.ts` file:

```typescript
import dotenv from 'dotenv';
```

### Step 2: Configure Environment Loading

Add this configuration logic to your `playwright.config.ts`:

```typescript
// Determine which environment file to load
const environmentPath = process.env.ENVIRONMENT 
    ? `./env/.env.${process.env.ENVIRONMENT}`
    : `./env/.env.dev`; // Default to dev environment

// Load the environment variables
dotenv.config({
    path: environmentPath,
});
```

> 💡 **How it works**:
> 
> * If `ENVIRONMENT` is set, it loads `.env.{ENVIRONMENT}`
>     
> * If not set, it defaults to `.`[`env.dev`](http://env.dev)
>     

## 🎮 Using Environment Variables

### Step 1: Set Environment (Optional)

To use a specific environment, set the environment variable before running tests:

**Windows (PowerShell):**

```powershell
$env:ENVIRONMENT='staging'
```

**macOS/Linux:**

```bash
export ENVIRONMENT=staging
```

### Step 2: Verify Environment Setting

Check which environment is active:

**Windows:**

```powershell
echo $env:ENVIRONMENT
```

**macOS/Linux:**

```bash
echo $ENVIRONMENT
```

### Step 3: Access Variables in Tests

Use environment variables in your test files:

```typescript
// Basic usage
const url = process.env.URL;
const apiUrl = process.env.API_URL;

// With type safety and defaults
const baseUrl = process.env.URL || 'http://localhost:3000';
const username = process.env.USER_NAME || 'defaultUser';
```

You can learn more about [Basic Types](https://idavidov.eu/your-first-steps-in-typescript-a-practical-roadmap-for-automation-qa) and [Custom Types](https://idavidov.eu/a-practical-guide-to-typescript-custom-types-for-qa-automation) it TypeScript.

## 🎯 What's Next?

In the next article we will dive into **Design Patterns** - choosing between POM and Functional Helpers!

> 💬 **Community**: Please feel free to initiate discussions on this topic, as every contribution has the potential to drive further refinement.

---

✨ **Ready to supercharge your testing skills?** Let's continue this journey together!

---

> **🙏🏻 Thank you for reading!** Building robust, scalable automation frameworks is a journey best taken together. If you found this article helpful, consider joining a growing community of QA professionals 🚀 who are passionate about mastering modern testing.

> [Join the community and get the latest articles and tips by signing up for the newsletter.](https://idavidov.eu/newsletter)
