Setting Up Environment Variables for React Native Builds

H A M II™
Jul 7, 2017 · 2 min read

Introduction

With my side project, I wanted to be able to switch out environment variables efficiently. Since we are looking to create our first production environment, I thought the best way was through a config file. Inside the config.json file I have all our base urls and settings that should be set based upon the environment. After reading Twelve-Factor App, config files are a direct violation to twelve-factors.

To fix this violation, I ended up using babel-plugin-transform-inline-environment-variables to allow the injection of environment variables while babel is doing its job. So now when I run:

$ API_KEY=1joi34 BASE_URL=https://base.now.sh FOO=BAR react-native start

I can access all the environment variables through process.env.{variableName} anywhere in my codebase. cool right?

Moving forward, I wanted my team to be able to move as fast as possible when it came to deploys and switching environments. Especially now since we are moving towards our first release. Also, I added custom scripts to the package.json, which makes it way easier/cleaner to run different environments instantly. Below you can checkout how to get this same setup on your react-native project 😛.

How to setup environment variables in your project

  1. install babel-plugin-transform-inline-environment-variables
  • via yarn

$ yarn add babel-plugin-transform-inline-environment-variables

  • via npm

$ npm install babel-plugin-transform-inline-environment-variables

2. Add to .babelrc

// .babelrc
{
“presets”: [“react-native”], “plugins”: [ “transform-inline-environment-variables” ]}

3. Test It

  • In either your index.ios.js or index.android.js file put
// Somewhere in index.ios.js or index.android.js
console.log(`foo is equal to ${process.env.foo}`);
  • Enter `foo=bar react-native start` command into your terminal

$ foo=bar react-native start

In your developer tools console you should see bar appear and now under process.env you can access any variable you may want embedded into your terminal once start. Voila you now have environment variables working for your React Native project.

H A M II™

Written by

God is Love #MOAM Instagram: @skiptomyhue

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade