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.
API_URL=https:example.com/api
ANALYTICS_KEY=asdf123
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) {
api.cache(true);
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 {
API_URL,
ANALYTICS_KEY,
};
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';
console.log(config.API_URL);
console.log(config.ANALYTICS_KEY);
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 Platform.select
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 {
API_URL,
IOS_ANALYTICS_KEY,
ANDROID_ANALYTICS_KEY,
} from 'react-native-dotenv';
export default {
API_URL,
ANALYTICS_KEY: Platform.select({
ios: IOS_ANALYTICS_KEY,
android: ANDROID_ANALYTICS_KEY,
}),
};
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!