isomorphicdevNavigate back to the homepage

Adding Dotenv to your Typed React Native Project

henry
January 5th, 2020 · 1 min read

When adding private environment variables, you’ll definitely want to remove them from your repository. The tricky part is making TypeScript happy when you do that and adding the correct types.

Here’s how you can do that in a React Native TypeScript Project! We’re going to use Firebase envs as an example.

First, we’ll add a package called ‘react-native-dotenv’ from npm, which will let us extract our variables into a .env file. Remember to add the .env to .gitignore.

1npm i react-native-dotenv

Next, create a .env file in your root directory and add your environment variables.

1// .env
2
3API_KEY='_'
4AUTH_DOMAIN='_'
5DATABASE_URL='_'
6PROJECT_ID='_'
7STORAGE_BUCKET='_'
8MESSAGING_SENDER_ID='_'
9APP_ID='_'
10ENV='_'
11...

Inside of your babel config, add the additional module.

1// babel.config.js
2
3...
4 "presets": [..., "module:react-native-dotenv"],
5...

You’ll need to add a vendor typing as well. Create it within a folder named lib for all of your other vendor types.

1// vendor-typings.d.ts
2
3declare module 'react-native-dotenv';

Voila!

Tree and file for reference:

1├── .gitignore
2├── package-lock.json
3├── package.json
4├── src
5│ ├── components
6│ │ └── index.ts
7│ └── lib
8│ └── vendor-typings.d.ts
9├── tsconfig.json
1import * as React from 'react'
2import { Text } from 'react-native'
3import {
4 ENV,
5} from 'react-native-dotenv'
6
7export default = (): JSX.Element => {
8 return <Text>{ENV}</Text>
9}
10
11...

Join our email list and get notified about new content

Be the first to receive our latest content with the ability to opt-out at anytime. We promise to not spam your inbox or share your email with any third parties.

More articles from The Isomorphic Dev

React Hooks. Part 2 - useEffect.

The useEffect Hook.

December 15th, 2019 · 2 min read

React Hooks. Part 1 - useState

Taking a look at the useState Hook

December 7th, 2019 · 2 min read
© 2019–2020 The Isomorphic Dev
Link to $https://twitter.com/isomorphicdevLink to $https://github.com/isomorphicdevLink to $https://instagram.com/theisomorphic.dev