How to setup environment variables in React Native (Easy way)

There are a lot of ways in which we can use environment variables in React Native, you can look at many of them listed in this stack-overflow question

The purpose of this blogpost is to point out and explain the simplest and quickest way to make use of environment variables in your RN project with typescript type checking, you can still follow this blog if you are just using javascript.

We will be making use of the handy npm library react-native-dotenv

STEP 1: Install following packages:

npm install react-native-dotenv

or

yarn add react-native-dotenv

For typescript install additionally:

npm install -D @types/react-native-dotenv

or

yarn add -D @types/react-native-dotenv

This blogpost uses an expo managed project, hence the babel.config.js will look like

here, moduleName is the alias we can give to react-native-dotenv library so we can import like:

instead of:

this just makes importing a bit easier :)

STEP 3: Create a .env file in the root directory and add your environment variable

ENV_VAR=some-secret-value

STEP 4: Use the environment variable by importing it

STEP 5: Add typescript support

If you are using Typescript in your project, so you must have observed that typescript is yelling at you in STEP 4. To fix this, we will create an env.d.ts file in the root directory with the following content:

Wait a second! we are almost done, phew 😅

After this, you also need to update your tsconfig.json file with:

And now we are done!

Thank-you for reading this blog! The goal for me writing these specific use-case blogs is to create a directory which I can look back on in future for reference and also help the developer community while at it. Please consider following me here or on Twitter to get updates for my latest publications :)

Originally published at https://vikrantbhat.hashnode.dev.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Vikrant Bhat

Vikrant Bhat

The irony is, I am a web developer but I am shit scared of spiders. Javascript && React ⚛️