| | |

Cypress 16 🌲 Environment Variables — cy.env and Cypress.env

⏱️ Estimated read: 15 min | |

Cypress 16 removed Cypress.env(). The synchronous method that hydrated every environment value into the browser context—including secrets the test never read—is gone. In its place are two APIs with a deliberate split: cy.env() for sensitive values that must stay out of the browser until explicitly requested, and Cypress.expose() for public configuration that is safe to serialize into the browser context and read synchronously.

This chapter covers the Cypress 16 environment variable model from the ground up. It explains why Cypress.env() was removed, how cy.env() retrieves secrets asynchronously without exposing them globally, how Cypress.expose() handles public configuration, and how to set variables through the config file, cypress.env.json, CYPRESS_* OS variables, the --env CLI flag, and setupNodeEvents. It also covers safe handling of yielded secrets, reading variables inside cy.session() and cy.origin(), and the allowCypressEnv: false enforcement flag for teams completing the migration. By the end, you will understand which API to use for every value in your test suite and how to migrate existing Cypress.env() calls without exposing secrets.

Key point: Cypress.env() is removed in Cypress 16. Use cy.env() for secrets—it fetches only the keys you request and never serializes them into browser context automatically. Use Cypress.expose() for public configuration that is intentionally safe for application code to see. There is no longer a single API for both.


Why Cypress.env was removed

The global exposure problem. In Cypress 15, Cypress.env() hydrated every environment value into the browser context and attached them to the global window.Cypress object. Any script running on the page under test—the application itself, third-party analytics, embedded widgets, browser extensions—could call window.Cypress.env() and read every secret in the configuration. A test that needed one API key exposed all of them, whether or not they were used.

The security default problem. The old model made exposure the default and protection the exception. Teams had to remember to move secrets out of Cypress.env() and into cy.task() to keep them out of the browser. Cypress 16 inverts this: secrets stay in the Node process unless a test explicitly calls cy.env() for a specific key, and even then the value is yielded to the test’s .then() callback rather than attached to a global object.

The migration enforcement. The deprecation arrived in Cypress 15.10.0, and the removal in 16.0.0 was paired with an allowCypressEnv configuration flag. Setting allowCypressEnv: false causes any remaining Cypress.env() call to fail with a message explaining the migration path, giving teams a hard stop that surfaces every missed call during a test run rather than discovering them in production.


a. Using cy.env for sensitive values

cy.env() is an asynchronous command that accepts an array of key names and yields an object containing only those keys. It does not attach values to a global object, and it does not expose unrequested keys to the browser. The command logs the key names it was asked for, but never the values.

// cypress/e2e/api.cy.ts
describe('API authentication', () => {
  it('fetches protected data with an API key', () => {
    // Request only the apiKey; other env values are not fetched
    cy.env(['apiKey']).then(({ apiKey }) => {
      // Use the value immediately inside the callback
      cy.request({
        url: 'https://api.example.com/data',
        headers: { Authorization: `Bearer ${apiKey}` },  // ✅ secret used, not logged
      }).its('status').should('eq', 200);
    });
  });
});

The destructuring inside .then() is deliberate. .then() adds no entry to the Command Log, so the yielded object and its values stay out of the test output. The callback receives a plain JavaScript object, and Cypress does not mask, redact, or track what happens to it after the yield—the protection ends at the command boundary. Keep the value inside the callback and pass it directly to the command that needs it.

If a required key is missing, cy.env() yields undefined for that key. Destructuring defaults handle optional values, while a missing secret should fail fast in a before() hook rather than surfacing as a confusing 401 later in the test.

// cypress/support/e2e.ts
before(() => {
  cy.env(['apiKey']).then(({ apiKey }) => {
    if (!apiKey) {
      throw new Error(
        'apiKey is not set. Add it to cypress.env.json or set CYPRESS_apiKey.'  // ✅ clear failure
      );
    }
  });
});

b. Using Cypress.expose for public configuration

Cypress.expose() is the synchronous counterpart for values that are intentionally safe to expose. It serializes configuration into the browser context and returns values immediately, without a .then() callback. Application code, third-party scripts, and browser extensions can read exposed values—that is the point. Use it for environment labels, feature flags, public API versions, and any configuration that would not be damaging if a user inspected it.

// cypress.config.ts
import { defineConfig } from 'cypress';

export default defineConfig({
  e2e: {
    expose: {
      apiVersion: 'v2',              // public: safe for app code to read
      environment: 'staging',        // public: useful for debugging
      featureFlags: { newCheckout: true },  // public: toggles for test conditions
    },
    env: {
      apiKey: process.env.API_KEY,   // secret: only retrievable via cy.env()
    },
  },
});
// In a test
const apiVersion = Cypress.expose('apiVersion');  // ✅ synchronous, no .then()
const environment = Cypress.expose('environment');

if (Cypress.expose('featureFlags').newCheckout) {
  cy.get('[data-testid="new-checkout"]').should('be.visible');
}

The configuration key changed from env to expose for public values. Values under expose are available synchronously through Cypress.expose(); values under env are available only through cy.env(). A single configuration file can hold both, and the distinction is enforced by the API surface: cy.env() cannot read exposed values, and Cypress.expose() cannot read env values.


c. Setting variables through every supported method

Both cy.env() and Cypress.expose() read from the same configuration sources, but the key under which values are defined determines which API can access them. Cypress supports five methods for setting environment variables.

// Method 1: cypress.config.ts — env key for secrets, expose key for public values
export default defineConfig({
  e2e: {
    env: { apiKey: process.env.API_KEY },
    expose: { environment: 'staging' },
  },
});
// Method 2: cypress.env.json — values here override the config file
// Add this file to .gitignore if it contains secrets
{
  "apiKey": "secret-from-json",
  "host": "dev.local"
}
# Method 3: CYPRESS_* OS variables — prefix strips the CYPRESS_ portion
export CYPRESS_apiKey="secret-from-os"
export CYPRESS_host="dev.local"
# Method 4: --env CLI flag — passed at run time
npx cypress run --env apiKey="secret-from-cli",host="dev.local"
// Method 5: setupNodeEvents — dynamic values set in the Node process
setupNodeEvents(on, config) {
  config.env.apiKey = process.env.API_KEY;  // set at runtime
  return config;
}

The precedence order matters: --env overrides CYPRESS_*, which overrides cypress.env.json, which overrides the config file. Values set in setupNodeEvents are applied after the configuration is resolved and can override earlier sources. For secrets, prefer CYPRESS_* OS variables in CI and cypress.env.json locally, and add the JSON file to .gitignore.


Complete Example Session

// ============================================
// PART 1: CONFIGURATION SPLIT
// ============================================
// cypress.config.ts
import { defineConfig } from 'cypress';

export default defineConfig({
  e2e: {
    env: {
      adminPassword: process.env.ADMIN_PASSWORD,  // secret
      apiToken: process.env.API_TOKEN,             // secret
    },
    expose: {
      apiUrl: 'https://api.example.com',           // public
      environment: 'staging',                       // public
    },
  },
});

// ============================================
// PART 2: READING A PUBLIC VALUE SYNCHRONOUSLY
// ============================================
describe('Dashboard', () => {
  it('loads with the correct API version', () => {
    const apiUrl = Cypress.expose('apiUrl');  // ✅ no .then() needed
    cy.visit('/dashboard');
    cy.get('[data-testid="api-url"]').should('have.text', apiUrl);
  });

  // ============================================
  // PART 3: READING A SECRET ASYNCHRONOUSLY
  // ============================================
  it('authenticates with the admin password', () => {
    cy.env(['adminPassword']).then(({ adminPassword }) => {
      cy.visit('/login');
      cy.get('#username').type('admin');
      cy.get('#password').type(adminPassword, { log: false });  // ✅ log: false
      cy.get('form').submit();
      cy.url().should('include', '/dashboard');
    });
  });

  // ============================================
  // PART 4: SAFE ASSERTION ON A SECRET
  // ============================================
  it('verifies the token is present without logging it', () => {
    cy.env(['apiToken']).then(({ apiToken }) => {
      // Assert on a boolean, not the value itself
      expect(Boolean(apiToken)).to.be.true;  // ✅ Command Log shows "true", not the token
    });
  });

  // ============================================
  // PART 5: MISSING VARIABLE FAILS FAST
  // ============================================
  it('fails clearly when a required secret is missing', () => {
    cy.env(['requiredToken']).then(({ requiredToken }) => {
      if (!requiredToken) {
        throw new Error('requiredToken is not set. Add CYPRESS_requiredToken.');
      }
      cy.request({ url: '/api/secure', headers: { Authorization: requiredToken } });
    });
  });

  // ============================================
  // PART 6: USING cy.env INSIDE cy.session
  // ============================================
  it('logs in once and caches the session', () => {
    cy.session('admin-session', () => {
      cy.env(['adminPassword']).then(({ adminPassword }) => {
        cy.visit('/login');
        cy.get('#username').type('admin');
        cy.get('#password').type(adminPassword, { log: false });
        cy.get('form').submit();
      });
    });
    cy.visit('/dashboard');
    cy.get('[data-testid="welcome"]').should('contain', 'Admin');
  });

  // ============================================
  // PART 7: USING cy.env INSIDE cy.origin
  // ============================================
  it('reads a secret inside a cross-origin callback', () => {
    cy.origin('https://auth.example.com', () => {
      cy.env(['adminPassword']).then(({ adminPassword }) => {
        cy.get('#password').type(adminPassword, { log: false });
      });
    });
  });

  // ============================================
  // PART 8: CUSTOM COMMAND WITH cy.env
  // ============================================
  Cypress.Commands.add('apiRequest', (endpoint: string) => {
    cy.env(['apiToken']).then(({ apiToken }) => {
      cy.request({
        url: `https://api.example.com${endpoint}`,
        headers: { Authorization: `Bearer ${apiToken}` },
      });
    });
  });

  // ============================================
  // PART 9: ENFORCING MIGRATION
  // ============================================
  // cypress.config.ts — add allowCypressEnv: false
  // Any remaining Cypress.env() call will fail with a migration message
  // export default defineConfig({
  //   allowCypressEnv: false,
  // });

  // ============================================
  // PART 10: FULL TEST WITH BOTH APIS
  // ============================================
  it('combines public config with a secret', () => {
    const environment = Cypress.expose('environment');
    cy.env(['apiToken']).then(({ apiToken }) => {
      cy.request({
        url: `https://api-${environment}.example.com/health`,
        headers: { Authorization: `Bearer ${apiToken}` },
      }).its('status').should('eq', 200);
    });
  });
});

The ten parts above cover the complete Cypress 16 environment model: splitting configuration between env and expose, reading public values synchronously, reading secrets asynchronously, asserting on secrets without logging them, failing fast on missing values, using cy.env() inside cy.session() and cy.origin(), wrapping it in a custom command, enforcing the migration with allowCypressEnv: false, and combining both APIs in a single test.


Quick Reference

cy.env vs Cypress.expose

Aspectcy.env()Cypress.expose()
AccessAsynchronous (.then())Synchronous
PurposeSecrets, tokens, passwordsPublic configuration
Browser exposureOnly requested keys, yielded to callbackSerialized into browser context
Command LogLogs key names, never valuesValues visible
Config keyenvexpose
Available in cy.origin()Yes, call inside callbackYes, synchronous

Setting Variables

MethodLocationPrecedence
Config filecypress.config.ts → env / exposeLowest
cypress.env.jsonProject rootOverrides config
CYPRESS_*OS environmentOverrides JSON
--envCLI flagOverrides OS
setupNodeEventsConfig functionApplied at runtime

Safe Secret Handling

PracticeReason
Read inside .then()No Command Log entry
Pass directly to commandValue does not escape callback
Use { log: false } on .type()Password not rendered in log
Assert on Boolean(value)Value not printed by assertion
Fail fast in before()Clear error instead of downstream 401

Best Practices

✅ Do This:

// Use cy.env() for any value that should not reach the browser
cy.env(['apiKey']).then(({ apiKey }) => {  // ✅
  cy.request({ headers: { Authorization: apiKey } });
});

// Use Cypress.expose() for public values
const env = Cypress.expose('environment');  // ✅ synchronous

// Type passwords with { log: false }
cy.get('#password').type(password, { log: false });  // ✅

// Assert on a boolean, not the secret itself
expect(Boolean(apiKey)).to.be.true;  // ✅

// Fail fast on missing required variables
if (!token) throw new Error('token missing');  // ✅

// Set allowCypressEnv: false to enforce migration
allowCypressEnv: false,  // ✅

❌ Don’t Do This:

// Don't use Cypress.env(); it is removed in Cypress 16
Cypress.env('apiKey');  // ❌ throws with allowCypressEnv: false

// Don't store secrets under expose
expose: { apiKey: 'secret' }  // ❌ exposed to browser scripts

// Don't assert directly on a secret value
cy.env(['apiKey']).should('deep.include', { apiKey: 'abc' });  // ❌ logs the value

// Don't read secrets outside a .then() callback
const key = cy.env(['apiKey']);  // ❌ returns a Chainable, not the value

// Don't pass secrets through cy.origin() args when cy.env works inside
cy.origin(url, { args: { token } }, () => { /* ... */ });  // ❌ token crosses boundary

Common Pitfalls

PitfallWhy It HappensFix
Cypress.env is not a functionRemoved in Cypress 16Replace with cy.env() or Cypress.expose()
Secret logged in Command LogAsserted on the value directlyAssert on Boolean(value) instead
cy.env() returns Chainable, not valueNot awaited inside .then()Access inside the .then() callback
Public value unavailable synchronouslyStored under env instead of exposeMove to expose config key
cy.origin() cannot see env valueVariables do not cross origin boundaryCall cy.env() inside the callback
Plugin fails after upgradePlugin still uses Cypress.env()Upgrade plugin to latest major version

Real-World Examples

1. Reading an API key for a request

cy.env(['apiKey']).then(({ apiKey }) => {
  cy.request({ url: '/api/data', headers: { Authorization: `Bearer ${apiKey}` } });
});

2. Reading a public environment label

const env = Cypress.expose('environment');  // 'staging' or 'production'
cy.get('[data-testid="env-badge"]').should('have.text', env);

3. Failing fast on a missing secret

cy.env(['token']).then(({ token }) => {
  if (!token) throw new Error('token not set');
});

4. Logging in with a secret password

cy.env(['password']).then(({ password }) => {
  cy.get('#password').type(password, { log: false });
});

5. Custom command reading a secret

Cypress.Commands.add('authRequest', (url: string) => {
  cy.env(['apiToken']).then(({ apiToken }) => {
    cy.request({ url, headers: { Authorization: `Bearer ${apiToken}` } });
  });
});

6. Reading a secret inside cy.session

cy.session('user', () => {
  cy.env(['password']).then(({ password }) => {
    cy.get('#password').type(password, { log: false });
  });
});

7. Reading a secret inside cy.origin

cy.origin('https://auth.example.com', () => {
  cy.env(['password']).then(({ password }) => {
    cy.get('#password').type(password, { log: false });
  });
});

8. Reading a nested JSON value

// Set via: --env credentials='{"user":"jane","token":"abc"}'
cy.env(['credentials']).then(({ credentials }) => {
  cy.request({ headers: { Authorization: credentials.token } });
});

9. Defaulting an optional variable

cy.env(['apiUrl']).then(({ apiUrl = 'http://localhost:3000' }) => {
  cy.request(`${apiUrl}/health`);
});

10. Enforcing migration across the suite

// cypress.config.ts
export default defineConfig({
  allowCypressEnv: false,  // any Cypress.env() call fails
});

Visual

The Cypress 15 vs 16 Exposure Model

┌─────────────────────────────────────────────────────┐
│  CYPRESS 15: Cypress.env()                          │
│                                                     │
│  Node Process                                       │
│  ┌─────────────────────────────────────────────┐   │
│  │  env: { apiKey, password, host }            │   │
│  └─────────────────────────────────────────────┘   │
│         │                                           │
│         │  ALL values hydrated                      │
│         ▼                                           │
│  Browser Context                                    │
│  ┌─────────────────────────────────────────────┐   │
│  │  window.Cypress.env() → ALL values          │   │
│  │  App code, 3rd-party scripts, extensions    │   │
│  │  can read everything                        │   │
│  └─────────────────────────────────────────────┘   │
│                                                     │
│  Result: one test needing one key exposes all       │
└─────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────┐
│  CYPRESS 16: cy.env() + Cypress.expose()            │
│                                                     │
│  Node Process                                       │
│  ┌─────────────────────────────────────────────┐   │
│  │  env: { apiKey }    expose: { host }        │   │
│  └─────────────────────────────────────────────┘   │
│         │                     │                     │
│         │ cy.env(['apiKey'])  │ Cypress.expose()   │
│         │ only apiKey         │ host serialized     │
│         ▼                     ▼                     │
│  Browser Context                                    │
│  ┌─────────────────────────┐  ┌─────────────────┐  │
│  │  apiKey yielded to      │  │  host available │  │
│  │  .then() callback       │  │  synchronously  │  │
│  │  NOT on window object   │  │  on window      │  │
│  └─────────────────────────┘  └─────────────────┘  │
│                                                     │
│  Result: secrets requested explicitly, public       │
│  config exposed by design                           │
└─────────────────────────────────────────────────────┘

Choosing the Right API

┌─────────────────────────────────────────────────────┐
│  IS THE VALUE SENSITIVE?                            │
│                                                     │
│         ┌───────────────────┐                       │
│         │  API key?         │──YES──► cy.env()      │
│         │  Password?        │         async         │
│         │  Token?           │         .then()       │
│         │  Credential?      │         not global    │
│         └───────────────────┘                       │
│                  │                                  │
│                  NO                                 │
│                  ▼                                  │
│         ┌───────────────────┐                       │
│         │  Environment name?│──YES──► Cypress       │
│         │  Public URL?      │         .expose()     │
│         │  Feature flag?    │         sync          │
│         │  API version?     │         browser-safe  │
│         └───────────────────┘                       │
│                                                     │
│  When in doubt, treat it as sensitive.              │
└─────────────────────────────────────────────────────┘

Safe Secret Handling

┌─────────────────────────────────────────────────────┐
│  INSIDE cy.env().then()                             │
│                                                     │
│  cy.env(['apiKey']).then(({ apiKey }) => {          │
│    // ✅ Use the value here                         │
│    cy.request({ headers: { Authorization: apiKey }});│
│                                                     │
│    // ✅ Assert on a boolean                        │
│    expect(Boolean(apiKey)).to.be.true;              │
│  });                                                │
│                                                     │
│  // ❌ Do NOT:                                      │
│  // return apiKey from the callback                 │
│  // store it in a global variable                   │
│  // assert directly on apiKey                       │
│  // log it with console.log                         │
│                                                     │
│  The protection ends at the command boundary.       │
│  What happens after is your responsibility.         │
└─────────────────────────────────────────────────────┘

Summary

ItemValue
Removed in Cypress 16Cypress.env()
Secrets APIcy.env(['key']) → async .then()
Public config APICypress.expose('key') → synchronous
Config keysenv for secrets, expose for public
Enforcement flagallowCypressEnv: false
Secret loggingcy.env() logs keys, not values
Safe assertionexpect(Boolean(value)).to.be.true
cy.origin() accessCall cy.env() inside the callback
cy.session() accessCall cy.env() inside the setup function
Precedence--env > CYPRESS_* > cypress.env.json > config

Key takeaways:

  • Cypress.env() is gone. Cypress 16 removed it. Every call must be replaced with either cy.env() for secrets or Cypress.expose() for public configuration. The allowCypressEnv: false flag surfaces any missed calls at test runtime.
  • cy.env() is asynchronous by design. It yields only the requested keys inside a .then() callback, and it does not attach them to window.Cypress. This is the mechanism that keeps secrets out of the browser until a test explicitly asks for them.
  • Cypress.expose() is synchronous and browser-safe. Values under the expose config key are serialized into the browser context and available immediately. Use it only for data that would not be damaging if inspected by application code or third-party scripts.
  • The protection boundary is the command. cy.env() does not log values, but the object it yields is a plain JavaScript object. Assertions, .its(), .invoke(), and chained command failures can print values to the Command Log. Keep secrets inside the .then() callback, pass them directly to the consuming command, and assert on booleans.
  • cy.session() and cy.origin() require cy.env() inside the callback. Variables do not cross the origin boundary or the session setup function automatically. Call cy.env() within the callback that needs the secret.
  • Five sources set variables, one precedence order. Config file, cypress.env.json, CYPRESS_* OS variables, --env CLI flag, and setupNodeEvents all feed the same store. The CLI flag wins, the config file loses.
  • Plugins may still reference Cypress.env(). @cypress/grep and @cypress/code-coverage required major-version upgrades to remove the deprecated call. Audit plugin versions before setting allowCypressEnv: false.

Remember: The Cypress 16 environment model replaces a single convenient API with two deliberate ones. cy.env() treats secrets as secrets: fetched on request, never global, never logged by the command itself. Cypress.expose() treats public configuration as public: synchronous, serialized, available to the page. The migration is not cosmetic—it closes a real exposure path where any script on the page could read every environment value. Once the migration is complete, set allowCypressEnv: false and let the runner catch anything missed. The configuration is safer by default, and the only cost is remembering which API answers which question.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!