How to Configure Environment Variables (.env) Safely in React Native Expo

How to Configure Environment Variables (.env) Safely in React Native Expo. A practical guide to managing API keys, environment variables, and sensitive configuration data in Expo applications.

Introduction

A few years ago, I reviewed a React Native project that looked perfectly fine at first glance. The app worked, the code was clean, and deployment was smooth.

Then I opened one file and saw this:

const API_KEY = "sk_live_xxxxxxxxxxxxxx";

The developer had accidentally committed a production API key to a public GitHub repository. Within days, the service provider flagged unusual activity, and the key had to be revoked.

It’s a mistake many developers make when they’re getting started.

Whether you’re building a weather app, connecting to Firebase, integrating Google Maps, or consuming an AI API, you’ll eventually need configuration values that shouldn’t be scattered throughout your codebase.

That’s where environment variables come in.

In this guide, you’ll learn how to configure .env files safely in React Native Expo, when to use Expo’s built-in environment variable support, when packages like react-native-dotenv make sense, and—most importantly—what environment variables can and cannot protect.


Table of Contents

  • What Are Environment Variables?
  • Why Developers Use .env Files
  • The Biggest Security Misunderstanding About API Keys
  • Method 1: Using Expo Environment Variables
  • Method 2: Using react-native-dotenv
  • Real-World Example: Weather App Configuration
  • Common Mistakes That Expose Secrets
  • Best Practices for Production Apps
  • Which Approach Should You Choose?
  • Frequently Asked Questions
  • Final Thoughts

What Are Environment Variables?

Environment variables are values stored outside your application’s main source code.

Instead of hardcoding configuration details like API URLs, feature flags, or public API keys, you place them in a separate configuration file.

For example:

EXPO_PUBLIC_API_URL=https://api.example.com
EXPO_PUBLIC_ANALYTICS_ID=12345

Your application can then read those values when it runs:

const apiUrl = process.env.EXPO_PUBLIC_API_URL;

This approach makes projects easier to maintain because configuration changes don’t require editing multiple source files.

It also helps teams manage different settings for development, testing, and production environments.


Why Developers Use .env Files

Imagine you’re building an application that connects to several external services.

You might need:

  • API endpoints
  • Analytics IDs
  • Feature flags
  • Firebase configuration
  • Google Maps keys
  • Third-party service credentials

Without environment variables, these values often end up scattered across dozens of files.

A simple URL change can become a frustrating search-and-replace exercise.

Using .env files centralizes configuration in one place, making updates easier and reducing the risk of mistakes.

For larger teams, it also creates a cleaner separation between code and configuration.


The Biggest Security Misunderstanding About API Keys

Here’s something many tutorials fail to explain clearly:

A .env file does not magically hide secrets inside a mobile application.

This is one of the most common misconceptions among beginner React Native developers.

A .env file improves organization and reduces accidental exposure in source code, but once an application is compiled and distributed, many of those values still become part of the app bundle.

A determined attacker can often inspect the application and recover embedded values.

What Should Never Be Stored in a Mobile App?

Avoid placing these directly inside your Expo application:

  • Database passwords
  • Admin credentials
  • Payment processor secret keys
  • Private API secrets
  • Server authentication tokens

These belong on a backend server.

What Is Usually Safe?

Public configuration values such as:

  • Public API endpoints
  • Firebase public configuration
  • Analytics IDs
  • Google Maps public keys with restrictions enabled

Even then, you should apply usage restrictions whenever possible.


Method 1: Using Expo Environment Variables (Recommended)

For most modern Expo projects, the built-in environment variable system is the best choice.

It’s simple, officially supported, and requires almost no configuration.

Step 1: Create a .env File

At the root of your project, create:

.env

Add your variables:

EXPO_PUBLIC_API_URL=https://api.example.com
EXPO_PUBLIC_WEATHER_KEY=abc123

Notice the prefix:

EXPO_PUBLIC_

Expo only exposes variables with this prefix to your application.


Step 2: Access Variables in Your Code

You can reference them directly:

const apiUrl = process.env.EXPO_PUBLIC_API_URL;
const weatherKey = process.env.EXPO_PUBLIC_WEATHER_KEY;

This keeps configuration separate from business logic and makes future updates easier.


Step 3: Restart the Development Server

If variables don’t appear immediately, clear Expo’s cache:

npx expo start --clear

Many developers spend 20 minutes debugging environment variables when a simple restart would have fixed the problem.


Why Most Expo Developers Prefer This Method

Advantages include:

  • Official Expo support
  • Minimal setup
  • No additional dependencies
  • Better long-term maintainability
  • Fewer compatibility issues after upgrades

For new projects, this is usually the right choice.


Method 2: Using react-native-dotenv

Before Expo introduced built-in support, many developers used react-native-dotenv.

It’s still popular because it provides a clean import-based workflow.

Install the Package

npm install react-native-dotenv

Create Your .env File

API_URL=https://api.example.com
API_KEY=abc123

Configure Babel

Add the plugin to babel.config.js:

module.exports = {
  presets: ['babel-preset-expo'],
  plugins: [
    [
      'module:react-native-dotenv',
      {
        moduleName: '@env',
        path: '.env',
      },
    ],
  ],
};

Import Variables

import { API_URL, API_KEY } from '@env';

Usage feels clean and straightforward:

fetch(`${API_URL}/users`);

Should You Use It?

For existing projects already using react-native-dotenv, there’s usually no urgent reason to migrate.

For new Expo applications, however, Expo’s native environment variable system is generally simpler.


Real-World Example: Building a Weather App

Let’s say you’re building a weather application.

Many tutorials start with something like this:

const WEATHER_API_KEY = "123456789";

It works, but it’s not ideal.

A cleaner approach is:

EXPO_PUBLIC_WEATHER_API_KEY=123456789

Then:

const apiKey = process.env.EXPO_PUBLIC_WEATHER_API_KEY;

This improves maintainability and keeps configuration organized.

But if the API provider charges based on usage, an even better approach is:

Mobile App
      ↓
Backend API
      ↓
Weather Service

The real secret key stays on your server, while the mobile app only communicates with your backend.

This is how most production-grade applications handle sensitive credentials.


Common Mistakes That Expose Secrets

Uploading .env Files to GitHub

Always include:

.env

inside your .gitignore file.

Accidentally publishing credentials remains one of the most common security incidents among new developers.


Treating Environment Variables as Encryption

Environment variables organize data.

They do not encrypt it.

This distinction matters.

A .env file is a convenience tool—not a security system.


Using Production Keys During Development

Many developers test locally using live credentials.

This increases risk and makes debugging harder.

Instead, separate environments:

# Development
EXPO_PUBLIC_API_URL=http://localhost:3000
# Production
EXPO_PUBLIC_API_URL=https://api.myapp.com

This simple habit prevents many deployment mistakes.


Connecting Directly to Databases

Mobile applications should never connect directly to production databases.

Instead:

App → API → Database

The API layer protects credentials and gives you control over authentication, permissions, and rate limiting.


Best Practices for Production Apps

When working on real-world React Native projects, these habits can save you from serious problems later.

Do

✅ Use environment variables for configuration

✅ Keep development and production environments separate

✅ Restrict API keys whenever possible

✅ Rotate credentials regularly

✅ Store sensitive secrets on a backend server

✅ Monitor API usage and billing

Don’t

❌ Hardcode secrets in source files

❌ Commit .env files to public repositories

❌ Store database passwords in mobile apps

❌ Expose admin credentials

❌ Assume environment variables are invisible to users


Which Approach Should You Choose?

If you’re starting a new Expo project today, use Expo’s built-in environment variable support.

It’s simpler, requires fewer dependencies, and is actively maintained by the Expo team.

Choose react-native-dotenv only if:

  • Your project already uses it
  • Your team prefers import-style syntax
  • Migrating would create unnecessary work

Both approaches solve the same problem, but Expo’s native solution is generally the cleaner option for modern projects.


Frequently Asked Questions

Are environment variables secure in React Native?

They improve organization and reduce accidental exposure in source code, but they should not be treated as a secure place to store sensitive secrets.


Can users extract API keys from a mobile app?

In some cases, yes. Public values embedded in an application may be recoverable through reverse engineering techniques.


What does EXPO_PUBLIC_ mean?

Expo only exposes environment variables prefixed with EXPO_PUBLIC_ to the client application.


Should I commit .env files to GitHub?

No. Most projects add .env to .gitignore to prevent accidental exposure of configuration values.


Is react-native-dotenv still useful?

Yes. Many existing projects use it successfully, although Expo’s built-in environment variable support is now the preferred option for new applications.


Final Thoughts

Environment variables are less about hiding secrets and more about managing configuration properly.

That’s an important distinction.

Using .env files keeps your code cleaner, makes deployments easier, and helps prevent accidental exposure of sensitive values in source code. But if a credential would cause real damage if leaked, it doesn’t belong in a mobile application at all.

For most Expo developers, the safest path is simple:

  • Use Expo’s built-in environment variables.
  • Keep sensitive secrets on a backend server.
  • Treat API keys with the same care you would treat passwords.

Following those principles from the beginning will save you countless headaches as your applications grow from side projects into production-ready products.

Read about The Ultimate React Native Beginner Roadmap (2026 Edition) – knowabteverything

Top 50 React Native Interview Questions & Answers (2026 Edition Part 1) – knowabteverything

Fix React Native Image Picker Permission Denied: 4 Simple Steps (Android & iOS Guide) – knowabteverything

Why Is My FlatList Not Updating When State Changes? 4 Fast Solutions – knowabteverything

Mobile App Image Optimization: How to Reduce File Size Without Sacrificing Image Quality – knowabteverything

Expo Documentation

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *