Dotenv React Native

Published on Jun 16, 2022
~2 min read

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.

BASH
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.

JS
"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.

ENV
API_KEY=supersecretapikey

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

JS
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.

Picture of author

Peter Lynch

Web Developer & Bootcamp grad who wants to learn as much as he can check me out on twitter.

Starting from the bottom newsletter

This newsletter is a record of my journey as an indie hacker, developer, entrepreneur, and human. Delivered straight to your inbox each Sunday.