0
0
Cypresstesting~15 mins

Environment variables for configuration in Cypress - Deep Dive

Choose your learning style9 modes available
Overview - Environment variables for configuration
What is it?
Environment variables are special values set outside your test code that help control how tests run. In Cypress, they let you change settings like URLs, credentials, or feature flags without changing the test files. This makes tests flexible and easier to manage across different environments like development, staging, or production. You can set these variables in files, command lines, or system settings.
Why it matters
Without environment variables, you would have to rewrite or duplicate tests for each environment or configuration, which wastes time and causes mistakes. Environment variables let you write tests once and run them anywhere by just changing the settings outside the code. This saves effort, reduces errors, and helps teams work faster and safer.
Where it fits
Before learning environment variables, you should understand basic Cypress test writing and configuration files. After this, you can learn about advanced Cypress plugins, continuous integration setups, and secure secret management to improve test automation further.
Mental Model
Core Idea
Environment variables are external settings that let you change test behavior without touching the test code itself.
Think of it like...
It's like setting the thermostat in your house: you don't rebuild the heater to change the temperature, you just adjust the thermostat to control how warm or cool it gets.
┌─────────────────────────────┐
│ Cypress Test Code           │
│  (fixed instructions)       │
└─────────────┬───────────────┘
              │
              ▼
┌─────────────────────────────┐
│ Environment Variables        │
│  (external settings)         │
└─────────────┬───────────────┘
              │
              ▼
┌─────────────────────────────┐
│ Test Execution Behavior      │
│  (changes based on variables)│
└─────────────────────────────┘
Build-Up - 6 Steps
1
FoundationWhat are environment variables
🤔
Concept: Introduce the basic idea of environment variables as external values that influence program behavior.
Environment variables are like labels with values stored outside your test code. For example, you can have a variable called BASE_URL that holds the website address your tests should visit. Instead of writing the URL directly in your test, you use this variable. This way, if the website address changes, you only update the variable, not the test itself.
Result
Tests become easier to update and reuse because the changing parts are outside the test code.
Understanding that environment variables separate changing data from fixed code helps keep tests clean and adaptable.
2
FoundationHow Cypress uses environment variables
🤔
Concept: Explain how Cypress reads and applies environment variables during test runs.
Cypress can read environment variables from several places: the cypress.json or cypress.config.js file, command line arguments, or system environment variables. For example, you can set an environment variable in cypress.config.js like this: module.exports = { env: { baseUrl: 'https://example.com' } } Inside your test, you access it with Cypress.env('baseUrl').
Result
You can write tests that use Cypress.env('baseUrl') to get the URL dynamically, making tests flexible.
Knowing where Cypress looks for environment variables helps you control test settings easily.
3
IntermediateSetting variables via command line
🤔Before reading on: do you think command line variables override config file variables or the other way around? Commit to your answer.
Concept: Learn how to pass environment variables directly when running Cypress from the command line and understand precedence.
You can set environment variables when you run Cypress using the --env flag: npx cypress run --env baseUrl=https://staging.example.com This command overrides the baseUrl set in config files for that run only. Inside tests, Cypress.env('baseUrl') will return the staging URL. This is useful for running tests in different environments without changing files.
Result
Tests run with the command line values, allowing quick environment switching.
Understanding variable precedence lets you control which settings apply without confusion.
4
IntermediateUsing environment variables for sensitive data
🤔Before reading on: should you store passwords directly in config files or use environment variables? Commit to your answer.
Concept: Explain why sensitive information like passwords should be stored in environment variables, not in test code or config files.
Storing secrets like passwords or API keys in config files risks exposing them in version control. Instead, set them as system environment variables or pass them via command line. For example, in Unix: export CYPRESS_password='mySecret' npx cypress run Then access in tests with Cypress.env('password'). This keeps secrets safe and separate from code.
Result
Sensitive data stays secure and tests can still access needed secrets.
Knowing how to protect secrets prevents accidental leaks and security risks.
5
AdvancedDynamic environment variables in CI/CD pipelines
🤔Before reading on: do you think environment variables can be changed automatically in CI/CD pipelines for different test runs? Commit to your answer.
Concept: Show how environment variables can be set dynamically in continuous integration systems to run tests in multiple environments automatically.
In CI/CD tools like GitHub Actions or Jenkins, you can define environment variables per job or step. For example, a pipeline might run tests against dev, staging, and production by setting different baseUrl values each time: jobs: test: steps: - run: npx cypress run --env baseUrl=${{ env.TEST_URL }} The TEST_URL changes per environment, so the same tests run with different settings without code changes.
Result
Tests automatically adapt to different environments in pipelines, improving automation and coverage.
Understanding this enables scalable, maintainable test automation across multiple deployment stages.
6
ExpertCustom environment variable loading strategies
🤔Before reading on: do you think Cypress supports loading environment variables from custom files or plugins? Commit to your answer.
Concept: Explore advanced ways to load environment variables from custom sources or plugins to handle complex configurations.
Cypress allows you to write plugins in cypress.config.js that can load environment variables from custom files like .env or JSON. For example, using the dotenv package: const dotenv = require('dotenv') dotenv.config() module.exports = { env: { baseUrl: process.env.BASE_URL } } This approach lets you manage multiple .env files for different environments and load them automatically, keeping configs clean and secure.
Result
You gain full control over environment variable management, enabling complex setups and better security.
Knowing how to extend Cypress config with plugins unlocks powerful customization for real-world projects.
Under the Hood
Cypress collects environment variables from multiple sources in a specific order: system environment variables, command line --env flags, and config files. It merges these into a single object accessible via Cypress.env(). During test execution, Cypress replaces calls to Cypress.env() with the current values, allowing tests to adapt dynamically. This merging and overriding mechanism ensures flexibility and control.
Why designed this way?
This design allows users to set defaults in config files but override them easily for specific runs or environments without changing code. It balances convenience and security, letting teams manage settings centrally while enabling quick changes. Alternatives like hardcoding values would reduce flexibility and increase errors.
┌───────────────────────────────┐
│ System Environment Variables   │
│ (highest priority)             │
├───────────────┬───────────────┤
│ Command Line  │ Config Files   │
│ --env flags  │ (cypress.config)│
│ (middle)     │ (lowest priority)│
└───────┬───────┴───────┬───────┘
        │               │
        ▼               ▼
   ┌─────────────────────────┐
   │ Merged Environment Vars │
   │ Accessible via Cypress.env() │
   └─────────────┬───────────┘
                 │
                 ▼
         Test Execution Behavior
Myth Busters - 4 Common Misconceptions
Quick: Does setting an environment variable in cypress.config.js override a command line --env flag? Commit to yes or no.
Common Belief:People often think config file environment variables always override command line variables.
Tap to reveal reality
Reality:Command line --env flags have higher priority and override config file variables during test runs.
Why it matters:If you expect config files to override command line settings, your tests might run with wrong values, causing confusion and errors.
Quick: Should you store passwords directly in cypress.json or cypress.config.js? Commit to yes or no.
Common Belief:Many believe it's safe to store sensitive data like passwords in config files for convenience.
Tap to reveal reality
Reality:Storing secrets in config files risks exposing them in version control and is insecure; environment variables or secret managers should be used instead.
Why it matters:Exposing secrets can lead to security breaches and data leaks, harming users and organizations.
Quick: Do environment variables set in one test persist automatically to others? Commit to yes or no.
Common Belief:Some think environment variables set during one test run stay set for all future tests.
Tap to reveal reality
Reality:Environment variables are set per test run and do not persist across separate runs unless explicitly configured.
Why it matters:Assuming persistence can cause flaky tests or unexpected behavior when tests rely on variables that are not set.
Quick: Can Cypress automatically load .env files without plugins? Commit to yes or no.
Common Belief:Some believe Cypress loads .env files by default like some other tools.
Tap to reveal reality
Reality:Cypress does not load .env files automatically; you must use plugins or custom code to load them.
Why it matters:Expecting automatic loading can cause tests to fail silently due to missing environment variables.
Expert Zone
1
Environment variables can be deeply nested objects in Cypress 10+ config, allowing complex structured configs beyond simple strings.
2
Using environment variables for feature flags enables toggling test behaviors dynamically without code changes, supporting A/B testing scenarios.
3
Cypress merges environment variables deeply, so understanding merge strategies prevents unexpected overrides when combining multiple sources.
When NOT to use
Environment variables are not suitable for storing large data sets or complex logic; use fixtures or external APIs instead. Also, avoid using environment variables for data that changes frequently during test execution; prefer test state management.
Production Patterns
In production, teams use environment variables to run the same test suite across multiple environments by injecting variables via CI/CD pipelines. They also combine environment variables with secret managers for secure credential handling and use custom plugins to load variables from encrypted files.
Connections
Continuous Integration (CI/CD)
Environment variables in Cypress are often set and managed by CI/CD pipelines to run tests in different environments automatically.
Understanding environment variables helps you integrate Cypress tests smoothly into automated pipelines, enabling reliable multi-environment testing.
12-Factor App Configuration
The 12-Factor App methodology recommends storing config in environment variables, the same principle Cypress follows for test configuration.
Knowing this connection shows Cypress aligns with modern software practices, making tests more portable and maintainable.
Operating System Environment Variables
Cypress environment variables can be set from OS environment variables, linking test configuration to system-level settings.
Understanding OS environment variables helps you manage Cypress test settings consistently across local machines and servers.
Common Pitfalls
#1Hardcoding URLs inside test files instead of using environment variables.
Wrong approach:cy.visit('https://staging.example.com')
Correct approach:cy.visit(Cypress.env('baseUrl'))
Root cause:Not understanding the benefit of separating configuration from test logic leads to brittle tests that break when URLs change.
#2Setting environment variables only in cypress.config.js and expecting them to change per run.
Wrong approach:module.exports = { env: { baseUrl: 'https://prod.example.com' } } // expecting to override via CLI but not using --env
Correct approach:npx cypress run --env baseUrl=https://staging.example.com
Root cause:Misunderstanding variable precedence and how to override config values dynamically.
#3Storing sensitive data like passwords directly in cypress.json or config files.
Wrong approach:{ "env": { "password": "mypassword" } }
Correct approach:Set password as system environment variable or pass via CLI: npx cypress run --env password=secret
Root cause:Lack of awareness about security risks and best practices for secret management.
Key Takeaways
Environment variables let you separate changing test settings from fixed test code, making tests flexible and reusable.
Cypress reads environment variables from config files, command line, and system settings, with command line having the highest priority.
Using environment variables for sensitive data protects secrets from exposure in code repositories.
In CI/CD pipelines, environment variables enable running the same tests across multiple environments automatically.
Advanced users can customize environment variable loading with plugins to handle complex or secure configurations.