DEV Community

Spencer Carli
Spencer Carli

Posted on • Originally published at

Easily Manage Different Environment Configurations in React Native

This tutorial was originally published on React Native School. Visit React Native School to access more than 80 React Native tutorials!

I'm going to show you something very quickly that's going to be very valuable. Ready?

Stop commenting and un-commenting environment specific variables in your app!

I see this every day. You're going to make a mistake. I guarantee it. I've done this many times.

I've talked about managing configuration before but that way can be a bit complex (it handles both native and JavaScript). Today we're going to just cover JavaScript, which makes it so easy.

First, in your app install react-native-dotenv.

yarn add react-native-dotenv --dev
# npm install react-native-dotenv --save-dev

Next create a .env file in the root of your project.


You'll then want to open your babel.config.js file and add react-native-dotenv to the presets. Here's an example final file:

module.exports = function(api) {
  return {
    presets: ['babel-preset-expo', 'module:react-native-dotenv'],

Then create a config.js file from which we'll import our config information for the rest of the app to use.

import { API_URL, ANALYTICS_KEY } from 'react-native-dotenv';

export default {

Wait, why a separate file for that? Why not just use react-native-dotenv directly? I'll touch on that in a moment.

Now, anywhere your app, you can access those variables easily.

import config from './config';


Different Variables for Different Environments

Let's say that you have a development server to test against and a different one for production. How do you handle that? Copy your .env to a .env.production file. Change what needs to be changed. react-native-dotenv will automatically pick up the right one based on the environment. Easy.

Different Variables for Different Platforms

Here is why we set up that config.js file. Let's say we have a different ANALYTICS_KEY for iOS and Android. How do we handle that?

I don't want littering my code - I want to do it in one place. So, with this in mind, here's what we do.

import { Platform } from 'react-native';
import {
} from 'react-native-dotenv';

export default {

Boom! Now everywhere in our code just uses ANALYTICS_KEY. Easy peasy.

Sometimes the most simple changes have the biggest impact.

Be sure to visit React Native School if you're interested in more on React Native!

Top comments (0)