React Native: process.env has only NODE_ENV
I’m setting an environment variable while building my react-native app (on windows):
SET APP_ENV=dev & react-native run-android
echo %APP_ENV%
returns ‘dev’
But when I log process.env object in my JS file, I only get:
{
NODE_ENV: "development"
}
Is there a different way to access environment variables set through command prompt?
It’s important to know that the React-Native app is running on a device (or emulator) in an environment more like a browser, not a Node.js process.
For cross-compatibility with Node.js libraries that relies on process.env.NODE_ENV
to perform optimizations, React-Native adds the process
global variable with env.NODE_ENV
.
If you want to pass custom constants to React-Native, you can use: https://github.com/luggit/react-native-config
You should install this plugin babel plugin
npm install babel-plugin-transform-inline-environment-variables --save-dev
Then add it to your babel config (.babelrc, babel.config.js) in the plugin section
{
"plugins": [
["transform-inline-environment-variables", {
"include": [
"NODE_ENV"
]
}]
]
}
Then when you pass the variable through the inline like
API_KEY=dev && react-native run-android
You should get it through
process.env.API_KEY
And the value will be dev
This work for me on Mac terminal, Hope it answer your question
EDIT:
I added a double “&” because only one doesn’t work.
Nothing worked out from these answers here, as well as React Native Expo Environment Variables, but I’ve found react-native-dotenv.
It did the trick:
- Terminal:
yarn add react-native-dotenv --dev
- In
babel.config.js
(or.babelrc
): add"module:react-native-dotenv"
toplugins
- In your component,
import { REST_API_KEY } from "@env";
at the top - In your component, use as
alert(REST_API_KEY);
Of course, with the alert
, that’s a dummy example 🙂
The easiest way I found to solve this problem is by using the react-native-config
library that you can have a look at here.
- Install the library:
$ yarn add react-native-config
- Create your
.env
file with your content. For example:
GOOGLE_MAPS_API_KEY=abcdefgh
- Import
Config
fromreact-native-config
and use your variables.
import Config from "react-native-config";
...
console.log('ENV:', Config.GOOGLE_MAPS_API_KEY); // ENV: abcdefgh
P.S.: After installing the package you need to run npx pod-install
to auto-link it or if your React Native version is older than 0.60, link it manually following the instructions on the library.
add babel-plugin-transform-inline-environment-variables
npm install babel-plugin-transform-inline-environment-variables --save-dev
babel.config.js:
{
"plugins": [
["transform-inline-environment-variables"],
]
}
do not add "include": ["NODE_ENV"]
then run API_KEY=testKey && react-native start
and then you can use API_KEY
via process.env.API_KEY
,
but it is weird that console.log(process.env)
only show a {NODE_ENV: "development"}
,do not contain API_KEY