How do hide secret key information in React application


Application makes API calls which API calls need secret keys . These keys are not committed to code repository.

This tutorials covers how to hide the secret keys hiding in React application created with create-react-app command.

For example, If you are creating react twilio plugin , you need ACCOUNT_SID and AUTH_TOKEN which are secret key details

For example, React application is created with create-react-app command.

Hide API key details in react application

first install latest dotenv npm library using npm command

npm install dotenv

Create .env file in the application root directory

.env file

ACCOUNT_SID=xxxxxxxxxx
AUTH_TOKEN=YYYYYYY

Next, adding .env file to .gitignore file which is not committed to git repository

.gitignore file

.env
node_modules

Once you created env file and added api key details, you can access the using process.env file. process.env is process object for accessing environment variables.

In react components you can access the API keys as seen below

console.log(process.env.ACCOUNT_SID);
console.log(process.env.AUTH_TOKEN);

Hide api key information with create-react-app command.

In this dotenv npm dependency is not required, As create-react-app tool handles the adding environment files differently

Assume application is created with create-react-app cli command

In the root of the project, Create a .env file

.env

REACT_APP_ACCOUNT_ID=123456
REACT_APP_AUTH_KEY=abckey

each key is appended with REACT_APP notation for creating key, if you don’t add REACT_APP to keys, It returns empty while accessing in react comonents.

Access the key using process.env object.

console.log(process.env.REACT_APP_ACCOUNT_ID)
console.log(process.env.REACT_APP_AUTH_KEY)

Finally, You can add .gitignore the environment variables.

Wrap up

Hiding API key details can be achieved with .env file which is not committed to git repository.

Similar Posts