Search code examples
reactjsdotenv

Using environment variables in ReactJS


So I've been setting up a new project and could not find any up-to-date explainations on how to do this, most people recommend to use dotenv but apparently dotenv is now included in react-scripts, how can I make use of this? where would I declare environment variables and how would I tell it to use production/environment ones when running my project? I know it seems like a "go read the documentation" question but I couldn't find any, and it's a pretty straight-forward question. TIA.


Solution

  • You can add properties in .env file in a key-value fashion

    AWS_CRENDETIALS='asgashgash32612'
    

    and reference them in your code with process.env.AWS_CRENDETIALS

    You can inject these properties based on the environment you are having. So when you are in production, you simply overwrite these variables. Otherwise just read from .env file.

    I personally don't use that file, but use in development a node command which has all the variables. In production they are managed by Azure DevOps for example.