Notes

Setting up multiple environments in React Native in a cross-platform way and use variables in JS, Android and iOS projects

Setting up multiple environments in React Native in a cross-platform way so that it works on Windows, macOS and Linux. Then make the environment variable available for use in JavaScript, iOS and Android code

Edit on GitHub

React Native & Expo
2 minutes

Environment variables

1npm install --save-dev cross-env
2npm install react-native-config

The following is involved

  1. Setting environment variables with cross-env
  2. Loading env files (.env.staging) by setting ENVFILE
  3. Using these env vars inside JS/Android/iOS
1cross-env ENVFILE=.env.staging && react-native run-ios
1# .env.staging
2API_URL=https://myapi.com
3GOOGLE_MAPS_API_KEY=abcdefgh
1import Config from 'react-native-config'
2
3Config.API_URL // 'https://myapi.com'
4Config.GOOGLE_MAPS_API_KEY // 'abcdefgh'

Additionally, you should also set NODE_ENVto be able to use it in places like babel.config.js to be able to configure plugins (e.g. remove all console.log statements from production environment) Setting process.env.NODE_ENV inside the code is not recommended

The final command that sets NODE_ENV, ENVFILE and runs the project would become

1cross-env NODE_ENV=staging ENVFILE=.env.staging && react-native run-ios

react-native-config

Environment variables are configured using react-native-config

For multiple environments, you have to create different .env files and load them by configuring ENVFILE when running commands

1ENVFILE=.env.staging && react-native run-ios

The files that store the variables are .env, .env.staging and .env.production. If you don’t specify a file, react-native-config will read from .env by default

cross-env

The syntax for setting environment variables is different fro Bash, Windows and PowerShell, which makes it hard to save as an npm script for everyone’s use

1ENVFILE=.env.staging react-native run-ios           # bash
2SET ENVFILE=.env.staging && react-native run-ios    # windows
3env:ENVFILE=".env.staging"; react-native run-ios    # powershell

That’s where cross-env comes in. A cross-platform command with cross-env would be

1cross-env NODE_ENV=production ENVFILE=.env.production react-native run-ios  # bash, windows, powershell

Similarly, the following different commands

1export NODE_ENV=production     # bash
2SET NODE_ENV=production        # windows
3$env:NODE_ENV="production";    # powershell

can be set in a cross-platform way using cross-env like so

1cross-env NODE_ENV=production     # bash, windows, powershell