Procedure to Add .env in React Native Using react-native-dotenv
1. Install react-native-dotenv Package
npm install react-native-dotenv
2. Configure Babel
In your project root, open the babel.config.js file and update it as follows:
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
[
"@babel/plugin-transform-private-methods",
{ loose: true }
],
[
"module:react-native-dotenv",
{
moduleName: "@env",
path: ".env",
blacklist: null,
whitelist: null,
safe: true,
allowUndefined: true
}
]
],
};
3. Create the .env File
In the root directory of your project, create a .env file and add the following environment variable:
Programming=true
4. Import the Environment Variable
In your React Native code, import the variable like this:
import { Programming } from "@env";
console.log(Programming); // Output: true
Important:
- Do NOT import from
react-native-dotenv directly.
- Always import using
@env as configured in the Babel file, or else it will throw an error.
5. Clear Cache if Issues Occur
If the environment variable is not loading, clear the Metro bundler cache:
npx react-native start --reset-cache
That’s it! Your .env setup is ready in React Native.
import {Platform} from 'react-native';console.log(Platform);