In Expo, the process.env object is not natively available to access environment variables like it is in Node.js or a server-side environment. Instead, Expo provides a way to manage environment variables through the App.config.js file.

Here's how you can define and use environment variables in Expo:

  1. Create App.config.js:

Create a file named App.config.js in the root of your Expo project (next to package.json). This file will hold your environment-specific configurations.

javascript
export default { extra: { API_URL: 'https://api.example.com', }, };
  1. Access Environment Variables:

To access environment variables defined in App.config.js, you can use Constants.manifest provided by Expo. You can access the extra property to get your environment variables.

For example, if you defined API_URL in App.config.js, you can access it like this:

javascript
import Constants from 'expo-constants'; // Access environment variables const API_URL = Constants.manifest.extra.API_URL; console.log('API URL:', API_URL);
  1. Manage Different Environments:

You can create multiple configurations in App.config.js for different environments (e.g., development, staging, production) and use the appropriate one based on the build or deployment.

For example, you can define different extra objects for each environment and switch between them as needed:

javascript
// App.config.js export default { development: { extra: { API_URL: 'http://localhost:8000', // Your development API URL }, }, production: { extra: { API_URL: 'https://api.example.com', // Your production API URL }, }, };

Then, when building or deploying your Expo app, you can specify the target environment using the EXPO_ENV environment variable. For example:

bash
# For development build EXPO_ENV=development expo build:android # For production build EXPO_ENV=production expo build:android

This will select the appropriate configuration from App.config.js based on the value of the EXPO_ENV environment variable.

Remember to always treat sensitive information, such as API keys or secrets, carefully when using environment variables in your app. Avoid storing sensitive data directly in the App.config.js file and consider using a secret manager or other secure solutions when dealing with sensitive information.

Have questions or queries?
Get in Touch