0

I currently have .env file in which I am saving api keys and such (not actual keys in the example below):

API_URL=https://www.example.si/3000
IOS_API_KEY=738d7hfu3hffsjfsd
STRIPE_KEY=pk_fh843f483ff3f43f34
APP_ID=pk_fh843f483ff3f43f34

I need to access these keys in my AppDelegate.m file.

I've tried the following:

NSString *AppID = @(getenv("APP_ID"));

But it didn't work.I get an error : "***+[NSString stringWithUTF8String:] NULL cString" .

I cannot use variable as @"AppID" where I want to pass it in. Any ideas on how to solve this issue would be helpful.

Amadej Šenk
  • 53
  • 2
  • 9
  • Check this https://stackoverflow.com/questions/3727891/how-to-reference-an-environment-variable-inside-obj-c-code – hariszaman Jan 31 '22 at 08:19
  • I ended up using a library for this react-native-config: https://github.com/luggit/react-native-config and it works really well. It also has system in place to avoid delayed (state based) caching. – Amadej Šenk Jan 31 '22 at 12:06
  • Even though using a library to solve miniature issues such as this is not the best practice (creates unnecessary dependencies), I've decided that it is a good solution for my case. – Amadej Šenk Jan 31 '22 at 12:09
  • Why is the question not tagged as react native? – matt Jan 31 '22 at 12:32
  • That's a valid point, I will update the post. Initially, because it is a Objective-C file and not a JS file but as you have pointed out, it's misleading. Thank you for your comment. – Amadej Šenk Jan 31 '22 at 17:39

3 Answers3

1

Use "Process.env.{{variable_name}}" to access the Environment Variable.

ouflak
  • 2,458
  • 10
  • 44
  • 49
1

I ended up using a library for this, called react-native-config:

https://github.com/luggit/react-native-config

and it works really well. It also has a system in place to avoid delayed (state based) caching so as soon as you save .env file there is no chance of remembering the previous state of .env file.

Amadej Šenk
  • 53
  • 2
  • 9
0

For those using EXPO, there are two options as explained at docs.expo.dev/guides/environment-variables/

This is the option I chose for my project:

Using the extra field

Setup your app.config.js with this:

module.exports = {
  name: 'MyApp',
  version: '1.0.0',
  extra: {
    apiUrl: process.env.API_URL,
  },
};

Then run API_URL="https://production.example.com" npx expo start. If you're using Windows, you can use something like https://www.npmjs.com/package/cross-env to be able to set the variables like this.

Now you should be able to access your env variables:

import Constants from 'expo-constants';

const apiUrl = Constants.expoConfig?.extra?.apiUrl;
Guilherme
  • 944
  • 7
  • 10