Notes

Environment Variables in React Native with react-native-dotenv

Edit on GitHub

React Native & Expo

Install react-native-dotenv

1npm i react-native-dotenv

Add the preset in babel.config.js

1// babel.config.js
2
3module.exports = {
4  presets: ['babel-preset-expo', 'module:react-native-dotenv'],
5}

Define your environment variables in .env

API_USERNAME=XXX
API_PASSWORD=XXX
API_URL_AUTH=XXX

And now you can import and use them in your code

 1// App.js
 2
 3import { API_USERNAME, API_PASSWORD, API_URL_AUTH } from 'react-native-dotenv'
 4
 5useEffect(() => {
 6  async function getToken() {
 7    try {
 8      const response = await axios.post(API_URL_AUTH, {
 9        username: API_USERNAME,
10        password: API_PASSWORD,
11      })
12      setToken(response.data.token)
13    } catch (error) {
14      ;(error) => console.error(error)
15    }
16  }
17  getToken()
18}, [])