Atom Lab logo

React Native Dotenv - Using environment variables in React Native

Tired of reinventing the wheel?

I'm building a React Native component library - built with Tailwind CSS - designed to help developers build awesome apps in record time.

Find out more

Introduction

There are times where you'll need to store different values for different environments, for example when developing your app locally vs running it on a production server. For this, we need to use environment variables. In React Native, one way to do this is the use the react-native-dotenv package.

What are environment variables?

Environment variables are essentially values that will be set outside your code. They will be set at runtime by the environment that your app is running on, such as your production server or your computer.

They're generally used for things that you wouldn't want to be in your repository, such as API keys, and values that are different in each environments, such as your site URL.

One thing to note is that using environment variables does not mean that your values will not be accessible in your client side code, therefore it isn't suitable for values that you want to keep hidden from prying eyes. If you need to keep a value private, it's best to store these on your backend.

What are dotenv files?

Dotenv files (.env) are files that you use to store your environment variables. You declare the name of your variable, followed by an equals sign, followed by the value, like so:

API_KEY=284509b5-4768-40a6-8e2d-63543b15df35 SITE_URL=https://www.atomlab.dev

What is react-native-dotenv?

React Native Dotenv is a Babel plugin that allows you to use dotenv values in your React Native project. It takes the enviroment variables we set and replaces the variable with the value when our app builds.

How to install react-native-dotenv

To install react-native-dotenv, open your terminal and run this command in the root of your project:

npm install react-native-dotenv

Or if you're using Yarn:

yarn add react-native-dotenv

Now we need to configure the package to work with Babel.

Configuring react-native-dotenv with Babel

Add the following to your .babel.config.js file:

module.exports = function(api) { api.cache(true); return { presets: ['babel-preset-expo'], plugins: ['module:react-native-dotenv'] }; };

For a basic setup, that should be all you need to get going. Now let's add some environment variables!

Using environment variables in React Native

First let's create a .env file to store our environment variables in the root of our React Native project, and an environment variable to store an API url (we're going to use the Dog Facts API in this example):

API_URL=https://dog-facts-api.herokuapp.com/api/v1/resources/dogs/all

In our app, lets write a fetch request to get data from our API:

import React, { useEffect, useState } from 'react'; import { Text, View, FlatList, SafeAreaView } from 'react-native'; export default function App() { const [dogFacts, setDogFacts] = useState(null); useEffect(() => { fetch('https://dog-facts-api.herokuapp.com/api/v1/resources/dogs/all') .then((res) => { return res.json(); }) .then((data) => { setDogFacts(data); }) .catch((err) => { console.log('err', err); }); }, []); if (!dogFacts) { return ( <SafeAreaView style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}> <Text>Loading...</Text> </SafeAreaView> ); } return ( <SafeAreaView style={{ flex: 1 }}> <View style={{ padding: 16 }}> <FlatList data={dogFacts} renderItem={({ item }) => ( <View style={{ marginBottom: 16 }}> <Text>{item.fact}</Text> </View> )} keyExtractor={(item, index) => index} /> </View> </SafeAreaView> ); }

In order to use our environment variable, first we need to import it at the top of our file:

// import { API_URL, API_TOKEN } from '@env'; export default function App() { // useEffect(() => { fetch(API_URL) .then((res) => { return res.json(); }) .then((data) => { setDogFacts(data); }) .catch((err) => { console.log('err', err); }); }, []); // }

If you refresh the app you'll see the our fetch still works. We're now using the API_URL value from the .env file.

How to use react-native-dotenv with Typescript

To use react-native-dotenv with Typescript, we can define the types of our variables using a Typescript definition file:

declare module '@env' { export const API_URL: string; }

Using multiple environment files

You can declare different enviroment variable values for different environments in your project. React Native Dotenv uses the dotenv-flow model, which means that it uses environment variables in the following order, from lowest priority to highest:

  1. .env - this is the lowest priority and where you should keep your default/fallback values
  2. .env.local - use this if you want to use different values for local development
  3. NODE_ENV files - these are enviroments that will be used depending on our NODE_ENV value, such as .env.development and .env.production, you should use these for environment specific values
  4. local NODE_ENV files - if you want to, you can overwrite your enviroment values for your local enviroment using a .local file, such as .env.development.local
  5. Environment variables set via the command line

Allowing undefined values

If you want to allow the importing of undefined enviroment variables, you can enable it by setting "allowUndefined" to true in your babel config:

module.exports = function(api) { api.cache(true); return { presets: ['babel-preset-expo'], plugins: [ [ 'module:react-native-dotenv', { allowUndefined: true } ] ] }; };

Copyright 2024 - Atom Lab | Privacy Policy | Terms and Conditions