Environment Variables in Expo and TypeScript

Published on Aug 4, 2021

2 min read

EXPO

Managing different keys for different environments, such as development or production, is common among JavaScript developers. Therefore, variables defined in this file may change during development and production, but the code remains unchanged. Hence, the mechanism of the .env file exists.

Using Expo, there are different ways you can set up and use environment variables. My preferred method is to use the dotenv file. Environment variables defined in this file are loaded using a package called dotenv.

Install dotenv

🔗

To set up environment variables in an Expo app, the initial step is to install the dotenv and expo-constants packages.

1expo init dotenv expo-constants

Rename app.json

🔗

Next, rename the app.json file to app.config.js or, if using TypeScript: app.config.ts, at the root of your project. Then, add the import statement to use the dotenv configuration. Since it's a JSON file, you will have to export all Expo configuration variables and add an extra object containing Environment variables.

1import 'dotenv/config';
2
3export default {
4 expo: {
5 // ...
6 extra: {
7 // Add your extra configs here
8 apiKey: process.env.API_KEY
9 }
10 }
11};

Constants with expo-constants

🔗

All the keys inside the extra object are readable app-wide using expo-constants. An environment variable is accessible through Expo.Constants.manifest.apiKey.

In the case of TypeScript, use optional parameter syntax to avoid squiggly: "Object is possibly 'undefined' or 'null'".

1const API_KEY = Constants?.manifest?.extra?.apiKey;

More Posts

Browse all posts

Aman Mittal author

I'm a software developer and a technical writer. In this blog, I write about Technical writing, Node.js, React Native and Expo.

Currently, working at Expo. Previously, I've worked as a Developer Advocate, and Senior Content Developer with companies like Draftbit, Vercel and Crowdbotics.


Copyright ©  2019-2022 Aman Mittal · All Rights Reserved.