
Security News
TypeScript is Porting Its Compiler to Go for 10x Faster Builds
TypeScript is porting its compiler to Go, delivering 10x faster builds, lower memory usage, and improved editor performance for a smoother developer experience.
react-native-dotenv
Advanced tools
The react-native-dotenv package is used to load environment variables from a .env file into a React Native application. This allows developers to manage configuration settings and sensitive information like API keys, database URLs, and other environment-specific variables in a secure and organized manner.
Loading Environment Variables
This feature allows you to load environment variables from a .env file into your React Native application. By importing the variables using the @env module, you can access them throughout your application.
import { API_URL } from '@env';
console.log(API_URL);
Customizing Environment Variable Prefix
You can customize the prefix for environment variables to avoid conflicts. By default, the package uses the @env prefix, but you can change it to something else if needed.
import { API_URL } from '@env';
console.log(API_URL);
TypeScript Support
The package provides TypeScript support, allowing you to declare the types of your environment variables. This helps in maintaining type safety and avoiding runtime errors.
declare module '@env' {
export const API_URL: string;
export const OTHER_ENV_VAR: string;
}
react-native-config is another popular package for managing environment variables in React Native applications. It allows you to define different environment configurations and access them in your code. Compared to react-native-dotenv, react-native-config offers more advanced features like multiple environment support and integration with native code.
dotenv is a widely-used package for loading environment variables from a .env file into Node.js applications. While it is not specifically designed for React Native, it can be used in conjunction with other tools to achieve similar functionality. Compared to react-native-dotenv, dotenv is more general-purpose and lacks some of the React Native-specific features.
Load environment variables using
import
statements.
$ npm install -D react-native-dotenv
If you are using Yarn:
$ 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.
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.
Also preview the expo test app.
babel.config.js
Basic setup:
api.cache(false)
module.exports = {
plugins: [
['module:react-native-dotenv']
]
};
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.
api.cache(false)
module.exports = {
plugins: [
[
'module:react-native-dotenv',
{
envName: 'APP_ENV',
moduleName: '@env',
path: '.env',
blocklist: null,
allowlist: null,
blacklist: null, // DEPRECATED
whitelist: null, // DEPRECATED
safe: false,
allowUndefined: true,
verbose: false,
},
],
],
};
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
API_URL=https://api.example.org
API_TOKEN=abc123
In users.js
fetch(`${process.env.API_URL}/users`, {
headers: {
'Authorization': `Bearer ${process.env.API_TOKEN}`
}
})
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
import {API_URL, API_TOKEN} from "@env"
fetch(`${API_URL}/users`, {
headers: {
'Authorization': `Bearer ${API_TOKEN}`
}
})
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.
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.
{
"plugins": [
["module:react-native-dotenv", {
"blocklist": [
"GITHUB_TOKEN"
]
}]
]
}
{
"plugins": [
["module:react-native-dotenv", {
"allowlist": [
"API_URL",
"API_TOKEN"
]
}]
]
}
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.
{
"plugins": [
["module:react-native-dotenv", {
"safe": true
}]
]
}
Allow importing undefined variables, their value will be undefined
.
{
"plugins": [
["module:react-native-dotenv", {
"allowUndefined": true
}]
]
}
import {UNDEFINED_VAR} from '@env'
console.log(UNDEFINED_VAR === undefined) // true
When set to false
, an error will be thrown. This is no longer default behavior.
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
.
// package.json
{
"scripts": {
"start:staging": "APP_ENV=staging npx react-native start",
}
}
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
:
{
"plugins": [
["module:react-native-dotenv", {
"envName": "MY_ENV"
}]
]
}
Now you can define MY_ENV
:
// package.json
{
"scripts": {
"start:staging": "MY_ENV=staging npx react-native start",
}
}
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
.
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
// package.json
{
"scripts": {
"start:development": "NODE_ENV=development npx react-native start",
"start:production": "NODE_ENV=production npx react-native start",
}
}
For the library to work with TypeScript, you must manually specify the types for the module.
types
folder in your project*.d.ts
file, say, env.d.ts
declare module '@env' {
export const API_BASE: string;
}
Add all of your .env variables inside this module.
typeRoots
field in your tsconfig.json
file:{
...
"compilerOptions": {
...
"typeRoots": ["./types"],
...
}
...
}
If you are not familiar with how dotenv or Babel work, make sure to read the following reference materials:
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.
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
:
"resolutions": {
"@babel/core": "^7.20.2",
"babel-loader": "^8.3.0"
}
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:
rm -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
.
If you'd like to become an active contributor, please send us a message.
╚⊙ ⊙╝
╚═(███)═╝
╚═(███)═╝
╚═(███)═╝
╚═(███)═╝
╚═(███)═╝
╚═(███)═╝
FAQs
Load environment variables using import statements.
The npm package react-native-dotenv receives a total of 96,662 weekly downloads. As such, react-native-dotenv popularity was classified as popular.
We found that react-native-dotenv demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 3 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
TypeScript is porting its compiler to Go, delivering 10x faster builds, lower memory usage, and improved editor performance for a smoother developer experience.
Research
Security News
The Socket Research Team has discovered six new malicious npm packages linked to North Korea’s Lazarus Group, designed to steal credentials and deploy backdoors.
Security News
Socket CEO Feross Aboukhadijeh discusses the open web, open source security, and how Socket tackles software supply chain attacks on The Pair Program podcast.