Managing environment variables in React Native is essential for separating configuration from code, supporting multiple environments (development, staging, production), and keeping sensitive or environment-specific data out of your codebase. By using react native environment variables, you can ensure that your app stays secure and flexible, no matter which stage of development you’re in.
With extensive experience in React Native app development, we've seen firsthand how crucial it is to manage configurations properly. React Native developers have to handle configurations securely to prevent disclosing private data because they frequently work in development, staging, and production environments. As a popular JavaScript framework, React Native offers flexibility and efficiency, but only when you follow best practices, especially when it comes to handling environment variables. In this guide, we'll explore how to set up and manage them effectively to streamline your development process.
Why React Native Environment Variables Matter
Environment variables might seem like a small piece of the puzzle, but they play a major role in building secure and maintainable React Native apps. Thanks to React Native's cross-platform nature, you're often working with a shared codebase for both iOS and Android. Managing environment variables properly helps ensure consistent behavior across platforms while keeping sensitive data secure. Here’s why they matter:
1. Keep sensitive data out of your codebase
Hardcoding things like API keys, server URLs, or access tokens directly into your code is risky. Not only does it make your app vulnerable if the code gets exposed, but it also creates extra work when you need to update or rotate those keys. Environment variables allow you to keep this sensitive data separate from your code, reducing security risks and making updates easier.
2. Make it easier to switch between environments
Whether you’re testing locally or pushing to production, different environments often require different configurations. With environment variables, switching from development to staging or production doesn’t mean digging through your code and manually updating values. Instead, you can define the right variables for each environment and switch with minimal hassle.
3. Improve collaboration across teams
For example, if you are building a React Native app for an enterprise, then sharing your codebase with other developers is unavoidable, but disclosing secrets shouldn't be. In order to allow your teammates to run the application using their own configuration files, environment variables assist you in keeping sensitive values out of version control. This prevents unintentional leaks, simplifies onboarding, and safeguards secrets.
Common Approaches to Managing Environment Variables
There are several ways to manage environment variables in React Native, and the best approach often depends on your setup—whether you're using a bare React Native project, working with Expo, or building with native modules. Here's a breakdown of the most common methods developers use:
1. Using .env files with libraries
The most popular approach is using libraries like react-native-config
or react-native-dotenv
(Though dotenv has been archived since 2020). These tools allow you to define key-value pairs in .env files and load them into your app at build time.
Pros
– Easy to set up and maintain
– Uses a familiar .env syntax
– Great for managing different environments with separate .env.development
, .env.staging
, and .env.production
files
Cons
– If not handled properly (e.g., accidentally committing .env files to version control), they can expose sensitive information
– Some variables may require linking or native code access for full functionality (especially with react-native-config
)
2. Manual Configuration Files
Another simple method is to create a custom configuration file, like config.js or config.json, and export environment-specific values using logic in your code.
// config.js
export const API_URL = __DEV__
? 'https://dev.example.com'
: 'https://prod.example.com';
This approach uses the __DEV__
flag (built into React Native) to switch values based on the environment.
Pros
– No additional libraries required
– Easy to customize for specific use cases
Cons
– Config values are bundled with your code, so you shouldn't store anything sensitive
– Doesn’t support dynamic changes during build or runtime
3. Platform-Specific Native Configurations
For more advanced use cases, you can configure environment variables directly within native code:
- iOS: Use Xcode build schemes and set variables in Info.plist or as user-defined build settings
- Android: Define build flavors and access variables via BuildConfig in your native Java/Kotlin code
Pros
– Gives fine-grained control over platform behavior
– Useful for early-access variables needed before the JS bundle loads
Cons
– Requires native development knowledge
– Harder to maintain compared to JS-based approaches
4. Expo Projects (Managed Workflow)
If you're using Expo, managing environment variables is straightforward, but there are some important considerations.
Expo supports .env files out of the box, but you must prefix public variables with EXPO_PUBLIC_ to access them in your app.
Steps:
#1. Create a .env file:
EXPO_PUBLIC_API_URL=https://staging.example.com
#2. Access in your code:
const apiUrl = process.env.EXPO_PUBLIC_API_URL;
#3. Use different files like .env, .env.local, or .env.production—Expo CLI automatically loads them based on priority.
Note: Environment variables prefixed with EXPO_PUBLIC_
are bundled into your JavaScript code and visible in plain text. You should never store sensitive information, such as API keys or secrets, in these variables.
Among these approaches, react-native-config is one of the most widely used libraries in React Native app development. Let’s walk through how to set it up and use it effectively.
Step-by-Step Guide to Using react-native-config
So, if you are developing a React Native app, chances are you’ll want a clean, reliable way to manage environment-specific variables. React-native-config allows you to do just that. It lets you use .env files to separate your configuration without cluttering your codebase.
Here’s how to get it set up:
1. Install the library
Use your preferred package manager to install it:
npm install react-native-config
Then link it to your project (only required for older versions of React Native):
npx react-native link react-native-config
Note: If you're using Expo (bare workflow), this library is compatible. But for managed workflows, you'll need to consider Expo’s built-in support instead.
2. Create a .env file
In the root of your project, create a .env file and add your variables:
API_URL=https://api.staging.example.com
API_KEY=your-secret-api-key
These are your React Native environment variables, and they’ll now be available throughout your app.
3. Access variables in your code
You can now import the config and use the variables like this:
import Config from 'react-native-config';
const apiUrl = Config.API_URL;
console.log(apiUrl); // https://api.staging.example.com
No need to hardcode URLs or tokens in your app anymore—everything stays clean and environment-specific.
4. Define multiple environments
Want to switch between development, staging, and production? Create .env.development
, .env.staging
, and .env.production
files:
.env.development
.env.staging
.env.production
Then, update your build scripts (or CI pipeline) to load the correct file for the right environment.
For Android, you can pass the env file using
ENVFILE=.env.staging ./gradlew assembleRelease
.
For iOS, set the ENVFILE environment variable in your build scheme.
5. Keep secrets secure
Remember: these variables can be exposed if mishandled. Don’t store highly sensitive data like private keys or tokens unless you’re managing builds securely (e.g., via CI/CD). For critical secrets, consider using a secure storage service or backend-based solution instead.
React Native Development Tools You’ll Want on Your Side
One of the biggest advantages of React Native is its ecosystem. Before we dive into best practices, let’s list down some of the tools of react native that can help you manage your workflow better. Here are some helpful tools React Native developers often rely on—not just for managing env files, but for improving the overall app development workflow.
1. react-native-config
We’ve already covered this one in depth, but it’s worth reiterating: react-native-config
is one of the most popular libraries for managing environment variables in React Native. It lets you load different .env
files depending on your build and gives you a way to reference those variables both in JavaScript and in native code (iOS and Android).
Great for: Traditional React Native projects that need platform-level access to env values.
2. Expo CLI
If you're building with Expo, you're in luck—Expo has built-in support for environment variables using .env
files. Variables prefixed with EXPO_PUBLIC_
can be accessed in your app code via process.env
.
Great for: Simpler projects that don’t need native code customization or secret handling on the frontend.
3. dotenv
While not React Native-specific, the dotenv package is a handy dev tool. It helps you load .env files into process.env during development. Some developers use it in combination with other tools or build scripts.
Great for: Custom tooling and local development environments.
4. react-native-dotenv (deprecated)
You may come across tutorials or older repos using react-native-dotenv. While it was once popular, it’s no longer actively maintained and not recommended for new projects. Stick with react-native-config or Expo’s built-in support instead.
5. Secrets Managers (Optional)
For sensitive configuration (especially in production), it’s best to go beyond .env files. Tools like AWS Secrets Manager, Azure Key Vault, or HashiCorp Vault allow you to store and manage secrets more securely.
Great for: Production apps where you need tight control over access to sensitive data.
6. Visual Studio Code + Extensions
For many React Native developers, VS Code is their preferred editor. Extensions like:
- DotENV (syntax highlighting for .env files)
- React Native Tools (debugging, IntelliSense, etc.)
- Prettier and ESLint (code formatting and linting)
can significantly improve your development experience.
Best Practices for Managing Environment Variables
Managing your environment variables effectively comes next after you've set them up. Bad practices can lead to a variety of problems, such as mingling environments or keeping secrets in your codebase. These best practices for the React Native env will assist you in maintaining a clean, safe, and maintainable React Native app development process, regardless of how advanced you are.
1. Never commit .env
files to version control
This might sound basic, but it’s one of the most common mistakes. Your .env files may contain API keys, tokens, or internal URLs. Always add them to your .gitignore
file:
.env
.env.*
Instead, share them securely with your team using a secrets manager or encrypted password vault.
2. Use different .env files for each environment
Create separate files like .env.development
, .env.staging
, and .env.production
. This makes it easier to switch between environments without modifying the code and ensures that you're testing and building against the right services.
Pair this with conditional logic or build scripts that load the correct file for each scenario.
3. Avoid exposing secrets to the frontend
Tools like react-native-config
and Expo’s EXPO_PUBLIC_
prefix make it easy to access variables, but not all variables should be accessible in your app bundle.
If a value is truly sensitive (like a private API key), it shouldn’t live in your React Native environment variables. Instead, handle it on your backend or use secure storage methods.
4. Keep variable names consistent and descriptive
Use clear, uppercase names with underscores, like:
API_URL
FIREBASE_PROJECT_ID
ENABLE_FEATURE_X
This makes them easier to read and reduces the chances of typos or misconfiguration when your team expands or revisits old code.
5. Document your environment setup
Keep a shared internal doc that explains what each variable does, which files to create, and how to set them up locally. This helps onboard new developers quickly and prevents confusion when switching between environments.
6. Use a .env example file
Add a .env.example
file to your repo with placeholder values to show what’s needed:
API_URL=https://your-api-url.com
API_KEY=your-api-key-here
This way, your teammates can just duplicate it and fill in their own values when setting up the project.
Following these best practices makes your React Native env setup more secure, more scalable, and a whole lot easier to work with, especially when your project starts to grow. In many cases, choosing a React Native app development company with experience in secure environment management can help streamline setup and prevent critical mistakes early on.
Advanced Techniques for Managing Environment Variables
As your React Native development process grows more complex, managing configuration becomes more than just adding a few lines to a .env file. You start thinking about security, automation, and flexibility across teams and environments. Here are some advanced techniques that experienced React Native developers often use to level up their environment variable setup.
1. TypeScript Integration
If your app is written in TypeScript, it’s a good idea to define a typed interface for your environment variables. This adds type safety and helps catch potential bugs during development.
// types/env.d.ts
declare module 'react-native-config' {
interface EnvVars {
API_URL: string;
ENABLE_LOGGING: string;
}
const Config: EnvVars;
export default Config;
}
Why it matters:
With TypeScript, you’ll get autocompletion and compile-time checks whenever you access an environment variable, making your code more robust and easier to maintain.
2. Combining with CI/CD Workflows
Environment variables are often injected during deployment via CI/CD pipelines like GitHub Actions, GitLab CI, or CircleCI. Instead of storing secrets in your codebase or .env files, you define them in your pipeline settings.
How it works:
- Define environment-specific secrets in the CI/CD platform.
- Inject them at build or runtime using workflow scripts.
- Optionally, use a secure vault integration for sensitive values.
Why it matters:
Keeps your secrets out of version control, supports per-environment deployment, and improves security across the board.
3. Feature Toggles with Env Variables
You can use environment variables to enable or disable certain features dynamically, depending on the environment or user group. This is especially useful for staging rollouts, A/B testing, or controlling access to beta features.
Why it matters:
It allows you to ship code with features hidden behind flags, giving you full control over when and where those features are activated, without needing a full redeploy.
Common Pitfalls and Solutions
If handled correctly, working with environment variables in React Native can make your app more flexible and clean. These are some of the most frequent errors that developers make, along with helpful advice on how to prevent or correct them.
1. Exposing Sensitive Data in the Bundle
The problem:
Environment variables added without caution (especially in Expo projects using the EXPO_PUBLIC_
prefix) are bundled into the app and can be easily extracted by anyone with access to the build.
Solution:
Never store secrets like API tokens or private keys in variables that end up in the JS bundle. Use a secure secret management system (e.g., AWS Secrets Manager) and inject secrets only at runtime or through native code when necessary.
2. Accessing Variables Without Fallbacks
The problem:
Trying to use a variable like Config.API_URL
, without checking if it exists, can cause your app to crash, especially if the environment wasn't configured properly.
Solution:
Always provide fallback values or add checks before using the variables.
const apiUrl = Config.API_URL || 'https://default.example.com';
Or, if you're using TypeScript, leverage types to help enforce presence during development.
3. Forgetting to Rebuild the App
The problem:
Changes to environment variables in React Native (especially with react-native-config) won’t take effect until you rebuild the app. This often confuses developers expecting hot reload to be enough.
Solution:
Make sure to restart Metro and rebuild the native app when you update .env files.
npx react-native run-ios
Or
npx react-native run-android
4. Committing .env Files to Version Control
The problem:
Sensitive information accidentally gets pushed to GitHub or other repositories when .env
files aren't added to .gitignore
.
Solution:
Always add .env
, .env.*
, and any config files with sensitive data to your .gitignore
.
And if you’ve already committed it? Revoke the secrets immediately and rotate them.
5. Inconsistent Naming or Typo Errors
The problem:
Env variable names are case-sensitive, and typos are easy to miss. This can lead to bugs that are hard to debug, especially when you’re working across multiple environments or machines.
Solution:
Standardize your naming conventions and consider using a shared env.example
file to define expected variables for your team.
Conclusion
Managing environment variables might not be the flashiest part of development, but it’s one of the most essential. Whether you’re switching between development, staging, and production environments or safeguarding sensitive credentials, setting up your environment variables the right way helps keep your app secure, flexible, and scalable.
With extensive experience in React Native app development, we've seen firsthand how crucial it is to manage configurations properly. From using tools like react-native-config to integrating environment setups into CI/CD pipelines, we've helped clients streamline their development workflows and avoid common pitfalls that tend to surface later in the build process.
If you’re building a React Native app and want expert help managing configurations, optimizing development environments, or scaling your application with clean architecture, we’d love to chat. Our team specializes in delivering secure, high-performance React Native solutions tailored to your product goals. Let’s make your app production-ready, the right way.
Top comments (0)