Skip to content

Instantly share code, notes, and snippets.

@ptgamr
Last active November 20, 2018 21:59
Show Gist options
  • Save ptgamr/c657a788022b95ae27fedea709287168 to your computer and use it in GitHub Desktop.
Save ptgamr/c657a788022b95ae27fedea709287168 to your computer and use it in GitHub Desktop.
Environment configurations for React Native App

Intro

If you ever need a mobile application, you probably have an API endpoint to talk to. And if you're doing it right, you should have different environment for your API, usually it'll be: dev, staging, production.

The problem: How do we do the testing for our app?

We dont' want to perform test againts the production API. We need a way to teach our app to talk to different API environment. But what is the switch?

The naive way:

// Un-comment the first line when you do deployment to production
// Remember to comment the third line !!!!

// API_ENDPOINT = 'prod.my-cool-api.com'
// API_ENDPOINT = 'staging.my-cool-api.com'
API_ENDPOINT = 'dev.my-cool-api.com'

Or you can do this with the web

if (location.href.match('prod.my-cool-app.com')) {
  API_ENDPOINT = 'prod.my-cool-api.com'
} else if (location.href.match('staging.my-cool-app.com')){
  API_ENDPOINT = 'staging.my-cool-api.com'
} else {
  API_ENDPOINT = 'dev.my-cool-api.com'
}

But you can't do something similar when user open your app:

if (downloaded_from_app_store) {
  API_ENDPOINT = 'prod.my-cool-api.com'
} else if(downloaded_from_test_flight) {
  API_ENDPOINT = 'staging.my-cool-api.com'
} else {
  API_ENDPOINT = 'dev.my-cool-api.com'
}

We don't have those flag... We need to decide things at build time.

The App Store

  • Google Play Store: Alpha, Beta, Production
  • Apple Store: TestFlight, Production

To the rescue: react-native-config

Bring some 12 factor love to your mobile apps!

Create a new file .env in the root of your React Native app:

API_URL=https://myapi.com
GOOGLE_MAPS_API_KEY=abcdefgh

Then access variables defined there from your app:

import Config from 'react-native-config'

Config.API_URL  // 'https://myapi.com'
Config.GOOGLE_MAPS_API_KEY  // 'abcdefgh'

There is one issue: you need to delete the existing app to install a new app

This is okay, but sometimes we want it to be more than that: simutaneously install Dev, Staging, Production app.

Each app is identified by an appId (or bundleId for iOS).

We need to have different appId for each environment, and of course, different names (so you won't be confuse when open your app). We can also configure different icons for each environments, but I'll stop at name.

Solutions:

Android is quite straight forward (you just need to update your build.gradle). iOS is much more trickier in this case.

Multi-dimensions configuration in XCode:

  • Multiple Schemes
  • Multiple Configurations
  • Multiple Targets
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment