reactjsenvironment-variablescreate-react-appcypress

How to use process.env variables in browser running by Cypress


In the source code of my application (React based on create-react-app) I'm using env variables like so: process.env.REACT_APP_API_URL which are stored in my .env.* files.

But when I run the same application under the Cypress the process.env object is empty. How can I provide these variables to be used in React application when it's running under Cypress?

I know that I have a possibility to set Cypress env variables but it is not what I want - this is a different scope.


Solution

  • You can use the configuration API and do something like this on your plugins file. Set config.env = process.env which will set your entire node env for Cypress.

    // cypress/plugins/index.js
    module.exports = (on, config) => {
    
      // modify env value
      config.env = process.env
    
      // return config
      return config
    }
    

    You can also selectively assign the values that you want with config.env.YOUR_VAR = process.env.YOUR_VAR.