NotaGuruDotCom
NotaGuruDotCom

Reputation: 61

How to set up environment variables in react native

I'm making a react native app that makes a request to my server hosted on heroku.

Should I be hiding the URL of my server and if so how can I add an environment variable to a react native project?

I have made a .env file and then have done this:

console.log(process.env.URL)

Which is returning undefined - I am also using expo if that makes a difference.

Upvotes: 0

Views: 4808

Answers (2)

driouxg
driouxg

Reputation: 745

One library that I like to use that works for bare react native and expo is react-native-dotenv

  1. Install it npm i react-native-dotenv

  2. Add a .env file with your variables

MY_ENV_VARIABLE=SECRET_PASSWORD
  1. Add the babel plugin to .babelrc file.
{
  "plugins": [
    ["module:react-native-dotenv"]
  ]
}
  1. Import and use it
import { MY_ENV_VARIABLE } from "react-native-dotenv";

function doSomething() {
  console.log(MY_ENV_VARIABLE);
}

Upvotes: 0

HichamELBSI
HichamELBSI

Reputation: 1719

If you use Expo, there is an easy way to create environment variables.

In your app.json file

{
 "expo": {
   "extra": {
     "URL": "https://..."        
   }
 }
}

After that, you will need to install the expo-constant package.

expo install expo-constants

And, to get the info in your app:

import Constants from "expo-constants";

console.log(Constants.manifest.extra.URL);

Upvotes: 4

Related Questions