DEV Community

Dallington Asingwire
Dallington Asingwire

Posted on • Updated on


How to use .env file in a React Native Application

Using environment file (.env) to configure most critical variables like database credentials, api keys, is the most common practice in software development. In this post, we are going to see how to create and use .env file in react native.

First, we need to install and use a babel plugin called react-native-dotenv. Install this plugin under your project root directory using the command below;

npm install react-native-dotenv
Enter fullscreen mode Exit fullscreen mode

This babel plugin lets you inject your environment variables into your react-native application.

.env file
Create .env file under your project root directory and example looks like below;

Enter fullscreen mode Exit fullscreen mode

Create if you don't have babel.config.js file under your project root directory, and add the following code

module.exports = {
  presets: ['module:metro-react-native-babel-preset'],
  plugins: [
    ["module:react-native-dotenv", {
      "envName": "APP_ENV",
      "moduleName": "@env",
      "path": ".env",
      "safe": false,
      "allowUndefined": true,
      "verbose": false

Enter fullscreen mode Exit fullscreen mode

How to access and use environment variables in your components

import React from 'react'
import {View, Text} from 'react-native'
import {APP_NAME, API_KEY, COMPANY_EMAIL} from '@env'

const App = () => {
return (
    <Text>My App name is {APP_NAME}</Text>
    <Text>My API Key is {API_KEY}</Text>
    <Text>Company email is {COMPANY_EMAIL}</Text>

export default App;
Enter fullscreen mode Exit fullscreen mode

Output on your emulator or phone device screen

My App name is MyRNApp
My API Key is myapikeyisplacehere
Company email is
Enter fullscreen mode Exit fullscreen mode

As you can see the above output, we have been able to load environment variables,APP_NAME, API_KEY and COMPANY_EMAIL into our react native application.

And that's the basic example of how you can use a .env file in a react native application. Thank you for reading through this article.

Top comments (6)

codingalgorithm profile image
Taofeek Ibrahim Opeyemi

Thank you.. This was helpful.

k3nnet profile image

Danko . this was helpful.

wilmela profile image

Thank you. This was helpful.

dallington256 profile image
Dallington Asingwire

@wilmela , Glad to hear that!

mkhuzo profile image
mkhuzo zulu

worked perfectly

marcoottina profile image

What to do if the '@env' is not found despite following each steps?