Load react native environment variables using import statements for multiple env files.
Installations
npm install react-native-dotenv
Developer Guide
Typescript
No
Module System
CommonJS
Node Version
20.11.0
NPM Version
10.2.4
Score
97.6
Supply Chain
99.4
Quality
80.7
Maintenance
100
Vulnerability
100
License
Releases
Contributors
Languages
JavaScript (100%)
Love this project? Help keep it running — sponsor us today! 🚀
Developer
Download Statistics
Total Downloads
24,351,982
Last Day
32,540
Last Week
167,384
Last Month
673,423
Last Year
7,085,150
GitHub Statistics
MIT License
826 Stars
465 Commits
48 Forks
3 Watchers
5 Branches
16 Contributors
Updated on Feb 08, 2025
Bundle Size
9.33 kB
Minified
3.67 kB
Minified + Gzipped
Package Meta Information
Latest Version
3.4.11
Package Id
react-native-dotenv@3.4.11
Unpacked Size
21.50 kB
Size
7.16 kB
File Count
4
NPM Version
10.2.4
Node Version
20.11.0
Published on
Feb 27, 2024
Total Downloads
Cumulative downloads
Total Downloads
24,351,982
Last Day
4.6%
32,540
Compared to previous day
Last Week
10.5%
167,384
Compared to previous week
Last Month
55.9%
673,423
Compared to previous month
Last Year
14.2%
7,085,150
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
1
Peer Dependencies
1
Dev Dependencies
5
react-native-dotenv 
Load environment variables using
import
statements.
Installation
1$ npm install -D react-native-dotenv
If you are using Yarn:
1$ yarn add -D react-native-dotenv
Breaking changes: moving from v0.x
to v2.x
changes both the setup and usage of this package. Please see the migration guide.
Many have been asking about the reasons behind recent changes in this repo. Please see the story wiki page.
Introduction
This babel plugin lets you inject your environment variables into your Javascript environment using dotenv for multiple environments. It is best suited for use with react native and works with all flavors including web.
Usage
Also preview the expo test app.
babel.config.js
Basic setup:
1api.cache(false) 2module.exports = { 3 plugins: [ 4 ['module:react-native-dotenv'] 5 ] 6};
If the defaults do not cut it for your project, this outlines the available options for your Babel configuration and their respective default values, but you do not need to add them if you are using the default settings.
1api.cache(false) 2module.exports = { 3 plugins: [ 4 [ 5 'module:react-native-dotenv', 6 { 7 envName: 'APP_ENV', 8 moduleName: '@env', 9 path: '.env', 10 blocklist: null, 11 allowlist: null, 12 blacklist: null, // DEPRECATED 13 whitelist: null, // DEPRECATED 14 safe: false, 15 allowUndefined: true, 16 verbose: false, 17 }, 18 ], 19 ], 20}; 21
Note: for safe mode, it's highly recommended to set
allowUndefined
tofalse
.
Note: Expo now has built-in environment variable support. Evaluate if you need
.env
1API_URL=https://api.example.org 2API_TOKEN=abc123
process.env technique
In users.js
1fetch(`${process.env.API_URL}/users`, { 2 headers: { 3 'Authorization': `Bearer ${process.env.API_TOKEN}` 4 } 5})
Import technique
The import technique, which is the initial functionality of the library, is to have an import statement at the top that turns into an object because of Babel
In users.js
1import {API_URL, API_TOKEN} from "@env" 2 3fetch(`${API_URL}/users`, { 4 headers: { 5 'Authorization': `Bearer ${API_TOKEN}` 6 } 7})
[DEPRECATED] White and black lists
Moving forward to a more inclusive language, terms like white
and black
are being moved away. Future versions will just use allowlist
and blocklist
while whitelist
/blacklist
are still supported.
Allow and Block lists
It is possible to limit the scope of env variables that will be imported by specifying a allowlist
and/or a blocklist
as an array of strings.
1{ 2 "plugins": [ 3 ["module:react-native-dotenv", { 4 "blocklist": [ 5 "GITHUB_TOKEN" 6 ] 7 }] 8 ] 9}
1{ 2 "plugins": [ 3 ["module:react-native-dotenv", { 4 "allowlist": [ 5 "API_URL", 6 "API_TOKEN" 7 ] 8 }] 9 ] 10}
Safe mode
Enable safe mode to only allow environment variables defined in the .env
file. This will completely ignore everything that is already defined in the environment.
The .env
file has to exist.
1{ 2 "plugins": [ 3 ["module:react-native-dotenv", { 4 "safe": true 5 }] 6 ] 7}
Allow undefined
Allow importing undefined variables, their value will be undefined
.
1{ 2 "plugins": [ 3 ["module:react-native-dotenv", { 4 "allowUndefined": true 5 }] 6 ] 7}
1import {UNDEFINED_VAR} from '@env' 2 3console.log(UNDEFINED_VAR === undefined) // true
When set to false
, an error will be thrown. This is no longer default behavior.
Override envName
One thing that we've noticed is that metro overwrites the test environment variable even if you specify a config, so we've added a way to fix this. By default, defining the APP_ENV
variable can be used to set your preferred environment, separate from NODE_ENV
.
1// package.json 2{ 3 "scripts": { 4 "start:staging": "APP_ENV=staging npx react-native start", 5 } 6}
The above example would use the .env.staging
file. The standard word is test
, but go nuts.
To use your own defined name as the environment override, you can define it using envName
:
1{ 2 "plugins": [ 3 ["module:react-native-dotenv", { 4 "envName": "MY_ENV" 5 }] 6 ] 7}
Now you can define MY_ENV
:
1// package.json 2{ 3 "scripts": { 4 "start:staging": "MY_ENV=staging npx react-native start", 5 } 6}
Note: if you're using APP_ENV
(or envName
), you cannot use development
nor production
as values, and you should avoid having a .env.development
or .env.production
. This is a Babel and Node thing that I have little control over unfortunately and is consistent with many other platforms that have an override option, like Gatsby. If you want to use development
and production
, you should not use APP_ENV
(or envName
), but rather the built-in NODE_ENV=development
or NODE_ENV=production
.
Multi-env
This package now supports environment specific variables. This means you may now import environment variables from multiple files, i.e. .env
, .env.development
, .env.production
, and .env.test
. This is based on dotenv-flow.
Note: it is not recommended that you commit any sensitive information in .env
file to code in case your git repo is exposed. The best practice is to put a .env.template
or .env.development.template
that contains dummy values so other developers know what to configure. Then add your .env
and .env.development
to .gitignore
. You can also keep sensitive keys in a separate .env.local
(and respective .env.local.template
) in .gitignore
and you can use your other .env
files for non-sensitive config.
If you are publishing your apps on an auto-publishing platform like EAS (Expo Application Services), make sure to put your secrets on the platform dashboard directly. If you are wondering what environment the platforms choose it is likely .env.production
(not .env.prod
) and there is likely no way to change this.
The base set of variables will be .env
and the environment-specific variables will overwrite them.
The variables will automatically be pulled from the appropriate environment and development
is the default. The choice of environment is based on your Babel environment first and if that value is not set, your NPM environment, which should actually be the same, but this makes it more robust.
In general, Release is production
and Debug is development
.
To choose, setup your scripts with NODE_ENV
for each environment
1// package.json 2{ 3 "scripts": { 4 "start:development": "NODE_ENV=development npx react-native start", 5 "start:production": "NODE_ENV=production npx react-native start", 6 } 7}
TypeScript
For the library to work with TypeScript, you must manually specify the types for the module.
- Create a
types
folder in your project - Inside that folder, create a
*.d.ts
file, say,env.d.ts
- in that file, declare a module as the following format:
1declare module '@env' { 2 export const API_BASE: string; 3}
Add all of your .env variables inside this module.
- Finally, add this folder into the
typeRoots
field in yourtsconfig.json
file:
1{ 2... 3 "compilerOptions": { 4 ... 5 "typeRoots": ["./types"], 6 ... 7 } 8... 9}
Reference Material
If you are not familiar with how dotenv or Babel work, make sure to read the following reference materials:
How this works
This Babel plugin processes your .env
files and your environment variables and replaces the references to the environment variables in your code before it runs. This is because the environment variables will no longer be accessible once the React Native engine generates the app outputs.
Cacheing
When using with babel-loader
with caching enabled you will run into issues where environment changes won’t be picked up.
This is due to the fact that babel-loader
computes a cacheIdentifier
that does not take your .env
file(s) into account. The good news is that a recent update has fixed this problem as long as you're using a new version of Babel. Many react native libraries have not updated their Babel version yet so to force the version, add in your package.json
:
1"resolutions": { 2 "@babel/core": "^7.20.2", 3 "babel-loader": "^8.3.0" 4}
If this does not work, you should set api.cache(false)
in your babel config
metro.config.jsresetCache: true
You can easily clear the cache:
1rm -rf node_modules/.cache/babel-loader/*
or
npm start -- --reset-cache
or
yarn start --reset-cache
or
yarn start --clear
or
jest --no-cache
or
expo r -c
and
expo start --clear
or
rm -rf .expo/web/cache
or
Maybe a solution for updating package.json scripts:
"cc": "rimraf node_modules/.cache/babel-loader/*,", "android": "npm run cc && react-native run-android", "ios": "npm run cc && react-native run-ios",
Or you can override the default cacheIdentifier
to include some of your environment variables.
The tests that use require('@env')
are also not passing.
For nextjs, you must set moduleName
to react-native-dotenv
.
Credits
- Based on David Chang’s works on babel-plugin-dotenv.
- Also based on Bertrand Marron's works on babel-plugin-dotenv-import.
If you'd like to become an active contributor, please send us a message.
Miscellaneous
╚⊙ ⊙╝
╚═(███)═╝
╚═(███)═╝
╚═(███)═╝
╚═(███)═╝
╚═(███)═╝
╚═(███)═╝

No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
3 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-grv7-fg5c-xmjg
- Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275
- Warn: Project is vulnerable to: GHSA-952p-6rrq-rcjv
Reason
security policy file detected
Details
- Info: security policy file detected: SECURITY.md:1
- Warn: no linked content found
- Info: Found disclosure, vulnerability, and/or timelines in security policy: SECURITY.md:1
- Info: Found text in security policy: SECURITY.md:1
Reason
0 commit(s) and 1 issue activity found in the last 90 days -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/dependabot.yml:1
- Warn: no topLevel permission defined: .github/workflows/issuehunt.yml:1
- Info: no jobLevel write permissions found
Reason
Found 1/13 approved changesets -- score normalized to 0
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/dependabot.yml:16: update your workflow using https://app.stepsecurity.io/secureworkflow/goatandsheep/react-native-dotenv/dependabot.yml/main?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/issuehunt.yml:12: update your workflow using https://app.stepsecurity.io/secureworkflow/goatandsheep/react-native-dotenv/issuehunt.yml/main?enable=pin
- Info: 0 out of 2 GitHub-owned GitHubAction dependencies pinned
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 26 are checked with a SAST tool
Score
3.8
/10
Last Scanned on 2025-02-03
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn MoreOther packages similar to react-native-dotenv
@types/react-native-dotenv
TypeScript definitions for react-native-dotenv
@startupjs/babel-plugin-dotenv
Import .env files
react-native-expand-dotenv
Load npm & environment variables from .env
@madeagency/react-native-dotenv
A Babel preset let you `import` application configs from **.env** file (zero runtime dependency)