Skip to main content

Enabling use of environment variables in ReactJS applications



I just wanted to share this small tidbit of information about a situation when you want to use environment variables in your ReactJS application. You can for example set a variable to TEST vs PRODUCTION to switch how your code operates (such as use a test db vs real db)

First off, I am assuming you are using something like react-scripts which makes this a lot easier. If not you may have to first setup something like dotenv in your app

But this just works if you are using react-scripts

Create a .env file at the application root location (I think the REACT_APP prefix is needed for this to work)

REACT_APP_SERVER=http://serverlocationDefault

Now you can use this in your app like this

render() {    
return (
    <Sessions server={process.env.REACT_APP_SERVER}/>   
);  
}

Believe it or not , that's it! Now when you want to run with a different server all you have to run is run your app with the vnv var set like this example in bash

REACT_APP_SERVER=http://anotherserver npm start

Enjoy!


Comments

Post a Comment