I would like to have a way to toggle between production and dev endpoints within from the phone settings. I am worried that this will mess up the cash and might display incorrect data. what's the best way to do it, please?
-
you need a setting inside the app that can set it to development mode?– AgneyApr 11, 2020 at 5:13
1 Answer
I was wondering the same thing!
In your code, you can use the
__DEV__
global flag to differentiate between Dev and Production "mode".Expo's Production switch is not a reliable way to handle environment switches (production and dev endpoints in your case). Why? 2 main reasons:
- Production mode always minifies your code and better represents the performance your app will have on end-user's devices.
- Development mode includes useful warnings and gives you access to debugging tools.
What if you want to have the flexibility to run the app against the Production endpoints you have, but still being able to access the debugging tools? You can't.
Here's my approach: I handle environment switches with .env
files.
With Expo, I got my
.env
to work with the following:
Added babel-plugin-inline-dotenv to devDependencies:
npm install --save-dev babel-plugin-inline-dotenv
Added
inline-dotenv
to .babelrc:{ "plugins": ["inline-dotenv"] }
Added a
.env
file:ENDPOINT="https://development"
Kudos for the
.env
set-up instructions goes to jdrydn.
Finally, use the environment variable in your code:
<Text>{process.env.ENDPOINT}</Text>
Plus, I have one more file .env-production
(technically, I have also .env-staging
in case you're wondering):
ENDPOINT="https://production"
The real caveat is when you want to run your app against the Production environment. You need to:
- Copy
.env-production
content to the.env
file. - Restart Expo's Metro Bundler and clear its cache (must be always restarted between
.env
changes). Do that either by runningexpo r -c
or by pressingshift-r
in your terminal to restart and clear cache while the Metro Bundler is running.
That's the most optimal approach I've been able to find.
PS: If you want to toggle between Dev and Production endpoints within you app - I'd simply use a js file with exported variables for each environment.
-
this is very informative, can you please elaborate more about this " If you want to toggle between Dev and Production endpoints within you app - I'd simply use a js file with exported variables for each environment."– user13283790Apr 13, 2020 at 5:58
-
It depends on your specific use-case. Big picture overview: wire-up the toggle with a variable you can access easily from anywhere, let's say
currentEnv
(that can be 'PROD' or 'DEV'). Your env configuration might look something likeexport const env = { DEV: { endpint: 'https://development' }, PROD: { endpint: 'https://production' }};
. Then, in your code you go forenv[currentEnv].endpoint
. Apr 13, 2020 at 11:22