2

I want a modern way to manage environment variables for a react native mobile app.

The answer here explains the twelve-factor method style (which I love) which involves installing a babel plugin that transpiles references to

const apiKey = process.env.API_KEY;

to their corresponding values as found in the process's environment

const apiKey = 'my-app-id';

The problem is that in order to run this with a populated environment, I need to set it like

API_KEY=my-app-id react-native run-ios

If I have a .env file with 10-20 environment variables in it, this method becomes unwieldy. The best method I've found so far is to run

env $(cat .env | xargs) react-native run-ios

This is a bit undesirable because developers who want to work on this package have to set up custom shell aliases to do this. This isn't conducive to a good development environment, and also complicates the build and deploy flow for releases.

Is there a way to add a hook to the react-native-cli (or a config file) that populates the process environment first? Like an npm "pre" script, but for react-native.

8
  • Alternatively, if there were just a way to populate process.env without the need for transpiling, that would be greatly appreciated. Commented Feb 10, 2017 at 20:06
  • Just keep a development .env file with the project. Commented Feb 10, 2017 at 20:21
  • @connorbode Creating a file is not my problem. Loading the env variables in .env into the node process is. I want a way to do this that hides the loading from the person running react-native run-ios. Commented Feb 10, 2017 at 20:31
  • Ah. I'm using react-native-config with success. Commented Feb 10, 2017 at 20:37
  • @connorbode does that not require you to rebuild every time you change a config variable? Commented Feb 10, 2017 at 22:26

1 Answer 1

3

You can use react-native-config which is a native library and requires a link to work or react-native-dotenv which works just like react-native-config but doesn't require any native link.

It'll work fine with .env files set up, e.g. .env.development with environment variables for process.env.NODE_ENV === 'development'.

Sign up to request clarification or add additional context in comments.

2 Comments

react-native-dotenv is exactly what I was looking for. Thank you! Now all I need to do is figure out how to get watchman to trigger when .env is changed.
Good one, never tried it, I think opening an issue to see if the maintainer has some way around would help a lot. Let me know how that works out! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.