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


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

.gitignore file


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


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



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.


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