How to fix "Expo App Not Replacing Env Variables on Web"
Learn how to fix the issue of Expo app not replacing environment variables on the web.
While building a React Native App using Expo and Firebase, I got stuck into an issue where the env variables for Firebase were being set correctly (via the Expo Go App) but, they weren’t being loaded on the web. After searching for several solutions without making any progress, I finally found the fix after a couple of days. In this article, I’ll walk you through the steps to resolve this issue and properly load env variables on both the web and app.
Solution
- Create
app.config.js
File (if you don’t already have one):
In your project’s root directory, create a file named app.config.js
(if it doesn’t exist already) and add the following code snippet to it. This will make the env object available in your app’s config.
// Extract environment variables that start with "EXPO_PUBLIC_"
// Convert all process.env variables to an object
const env = Object.fromEntries(
// filter only those whose keys start with "EXPO_PUBLIC_".
Object.entries(process.env).filter(([key]) => key.startsWith("EXPO_PUBLIC_"))
);
// change the expo app config
export default ({ config }) => ({
// Spread the existing configuration so that other properties remain unchanged.
...config,
// Add a new `extra` property to the config object, which will hold the filtered
// environment variables under the `env` key. These variables can be accessed
// within the app through Expo's Constants API.
extra: { env },
});
- Load Env Variables in Your App level code:
Next, we need to load these environment variables in your app. I’m using the _layout.jsx
file to load the variables, but you can load them in any other file depending on your app’s structure.
import Constants from "expo-constants";
export default function RootLayout() {
// loading all the env variables
useEffect(() => {
// Get the env object from the app.config file
const env = Constants.expoConfig?.extra?.env;
// to make sure that the env exists and it's of type object
if (env && typeof env === "object") {
Object.entries(env).forEach(([key, value]) => {
// Skipping env variables if:
// 1. The key does not start with "EXPO_PUBLIC_"
// 2. The variable is already set in `process.env`
if (!key.startsWith("EXPO_PUBLIC_") || process.env[key]) return;
// Set the environment variable with the value from the `env` object
process.env[key] = `${value}`;
});
}
}, []);
}
This ensures that your env variables are loaded into the process.env object, and making them accessible on both the web and app platforms.
Conclusion
I hope this guide helps you fix the issue of environment variables not being loaded on the web in your Expo app. By following these steps, you'll be able to ensure that your Firebase and other environment variables are correctly set for both mobile and web versions of your app.
Stay connected for more helpful guides and tips! — Rumaisa Naveed