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.

A Web Development Newsletter That Helps You Create

I'm learning heaps and having a blast doing it. Sign up for my newsletter where I'll share the things I've made and how you can make them too. Only real newsletters are going to last, all that other bullshit is here today & gone tomorrow.