Dotenv React Native

June 16, 2022 (2y ago)

You can’t use environmental variables in a React Native application like you would a regular React application. That is you can’t use process.env.yourKeys.

To use environmental variables in a React Native application with or without expo we need to install a third party package react-native-dotenv.

 yarn add react-native-dotenv
 npm i react-native-dotenv

Once that is installed you need to update your babel.config.js file or create one if you don’t have it, put the below snippet into your babel.config.js file right under the presets key.

  "plugins": [
    ["module:react-native-dotenv", {
      "envName": "APP_ENV",
      "moduleName": "@env",
      "path": ".env",
      "blocklist": null,
      "allowlist": null,
      "safe": false,
      "allowUndefined": true,
      "verbose": false
    }]
  ]

With that taken care of, we can now create a .env file where you can store you environment variables. In your project root folder create file .env.

API_KEY=supersecretapikey

You can now access your environmental variables in your components like so:

import { View, Text } from "react-native";

import { API_KEY } from "@env";

const App = () => {
  return (
    <View>
      <Text>{API_KEY}</Text>
    </View>
  );
};

export default App;

Notice that you do not need to use the process.env syntax to access your environment variables from your dotenv file, you just need to import and destructure them from @env.

The last thing to note is that you should include you .env file in your .gitnore file. Otherwise, you risk exposing those keys to malicious users on Github.