With some understanding about ethical-hacking, it should be made obvious, as to how much sensitive information should be guarded, as developers, in our codes. Environment variables are hence, conceptualised, on this basis. In react-native-typescript (typescript basically), the presence of a variable in a code, must be intentionally thought about. This defines the type and consequently, the type of operation permissible on such variable. 
In this post, I'll be showing you how to hide a dummy API-key. Onwards then, let's install react-natve-dotenv library, with the command below:
yarn add react-native-dotenv
or npm install react-native-dotenv
In our src folder, create a "types" folder. Create a file: "env.d.ts". 
In this file, we'd define the variable name as will be used in our code and its type as well:
decalre module "react-native-dotenv" {
    export const API_KEY: string;
    export const REMOTE_BASE_URL: string;
    export const LOCAL_BASE_URL: string;
    .....
}
In our babel.config.js file, we'll add the following
module.exports = {
    presets: [
    'module:metro-react-native-babel-preset', // present by default
  ],
plugins: ["module:react-native-dotenv", {
    moduleName: "react-native-dotenv",
    allowUndefined: false
}]
}
In our tsconfig.json we'll add:
{
    ...
    "typeRoots": ["./src/types"], 
    ...
}
Then we'll define our variables and values in our ".env" file. Hence, create a ".env" file, this must sit outside your src folder i.e where your package.json file is located. In here define the variables and corresponding values;
    API_KEY = something##anything
    ...
With all these in place, one last step:
I'd create a config folder in my src folder and then add an env.ts file in the config folder. The reason for this is that; react-native has a "DEV" variable that tells if the app is in production or development mode.
Therefore, in our env.ts file, we'd do the following;
import {
    API_KEY,
    REMOTE_BASE_URL,
    LOCAL_BASE_URL
    ...
} from "react-native-dotenv;
const devEnvVariables = {
   API_KEY,
   LOCAL_BASE_URL
}
const prodEnvVariables = {
   API_KEY,
   REMOTE_BASE_URL
}
export interface EnvsInterface {
    API_KEY,
    REMOTE_BASE_URL,
    LOCAL_BASE_URL
}
// If we're in dev use "devEnvVariables" otherwise, use "prodEnvVariables"
export default __DEV__ ? devEnvVariables : prodEnvVariables;
in our code, say loginScreen.tsx, we'll do the following;
 
 
              
 
    
Top comments (0)