How to manage third-party keys in React-Native?
There’s no doubt because there is a myriad of toolkits that improve lives as devs or software developers, and that’s common.
There are billions of awesome developers all over the world who put in the effort and never stop creating, and trying to make development even better with even more apps and resources, whether it’s in DevOps, frontend, server-side tools, or service, you could presumably testify to a magnificent tool or service you use now that makes life easier for you.
In most cases, you’ll be interacting with a backend and using a third-party service in your React-Native app, and you’ll be given private keys to use in the mobile app.
When building your app, you’ll need to take care to protect your private keys when you transfer them to the store and then to the user’s device, which brings up the question as to how to implement a similar setup of the web/backend as.env files in our React-Native apps.
In this blog, I’ll show you how to create a .env file in your React-Native application.
Create React-Native Project
npx react-native init myTestProject
This will create a folder containing react-native files.
Now, let’s create our .env file where we’ll be having all third-party API keys kept.
Now that our project is fully operational, it’s ready to implement react-native-dotenv, a wonderful package that enables us to read .env files in our app.
To install it we need to run the following command
yarn add react-native-dotenv
In the root directory create a babel.config.js file if it does not exist and copy-paste the below snippet.
module.exports = { presets: ['module:metro-react-native-babel-preset'], plugins: [ ["module:react-native-dotenv", { "moduleName": "@env", "path": ".env", "blacklist": null, "whitelist": null, "safe": false, "allowUndefined": true }] ] };
Now everything is done then we can try to put the key in the .env file and access it to the project file.
Put this private key to the .env file:
PRIVATE_KEY=’myprivate_keys’
You can import this key to a file like this:
Import React from ‘react’ Import {Text,View} from ‘react-native’ Import {PRIVATE_KEY} from ‘@env’ const App=()=>{ return( <View style={{flex:1,justifyContent:’center’,alignItems:’center’}}> <Text>{PRIVATE_KEY}</Text> </View> ) }
That’s how you can use this key more privately and can access it on any page of your application.
Reference:
Leave a Reply
Want to join the discussion?Feel free to contribute!