How to Use Environment Variables in Cypress for Testing
In Cypress, you can use
environment variables to store configuration or secrets by defining them in cypress.config.js, cypress.env.json, or via CLI with --env. Access these variables in tests using Cypress.env('variableName') to keep your tests flexible and secure.Syntax
Environment variables in Cypress can be set in multiple ways:
- cypress.config.js: Define under
envproperty. - cypress.env.json: Store variables in a JSON file.
- CLI: Pass variables using
--env key=value.
Access variables in tests with Cypress.env('key').
javascript
module.exports = { env: { apiUrl: 'https://api.example.com', userToken: 'abc123' } }; // In test file const apiUrl = Cypress.env('apiUrl'); const token = Cypress.env('userToken');
Example
This example shows setting environment variables in cypress.config.js and accessing them in a test to visit a URL and use a token.
javascript
// cypress.config.js module.exports = { env: { baseUrl: 'https://example.com', authToken: 'securetoken123' } }; // cypress/e2e/sample_spec.cy.js describe('Environment Variable Test', () => { it('uses env variables to visit and authenticate', () => { const url = Cypress.env('baseUrl'); const token = Cypress.env('authToken'); cy.visit(url); cy.log('Token:', token); // Example assertion expect(token).to.be.a('string').and.to.have.length.greaterThan(0); }); });
Output
Test passes if token is a non-empty string and page visits successfully.
Common Pitfalls
Common mistakes when using Cypress environment variables include:
- Not restarting Cypress after changing
cypress.config.jsorcypress.env.json. - Trying to access variables with wrong key names or case sensitivity.
- Exposing sensitive data in public repos by committing
cypress.env.json. - Using
process.envinstead ofCypress.env()inside tests.
javascript
// Wrong way (won't work inside Cypress test) const token = process.env.authToken; // Right way const token = Cypress.env('authToken');
Quick Reference
| Method | How to Set | Access in Test | Notes |
|---|---|---|---|
| cypress.config.js | Add under env property | Cypress.env('key') | Requires Cypress restart after change |
| cypress.env.json | Create JSON file with key-value pairs | Cypress.env('key') | Do not commit secrets to public repos |
| CLI | Run: cypress run --env key=value | Cypress.env('key') | Overrides config and JSON variables |
| System Environment | Set OS env vars before running Cypress | Cypress.env('key') | Use for CI/CD secrets |
Key Takeaways
Set environment variables in cypress.config.js, cypress.env.json, or via CLI with --env.
Access variables in tests using Cypress.env('variableName') for flexibility.
Never commit sensitive data in cypress.env.json to public repositories.
Restart Cypress after changing config files to load new variables.
Use CLI or system environment variables to override config for different environments.