{

How do hide secret key information in React application


The application makes API calls which API calls need secret keys. These keys are not committed to the code repository.

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

For example, If you are creating react Twilio plugin, you need secret keys such as ACCOUNT_SID and AUTH_TOKEN details.

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

Hide API key details in react application

first install latest dotenv npm library using npm command

npm install dotenv

Create a .env file in the application root directory

.env file

ACCOUNT_SID=xxxxxxxxxx
AUTH_TOKEN=YYYYYYY

Next, add the .env file to the .gitignore file that is not committed to the git repository.

.gitignore file

.env
node_modules

Once you created the env file and added API key details, you can access the using process.env file. process.env is a 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 the create-react-app command.

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

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

At 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 a key, if you don’t add REACT_APP to keys, It returns empty while accessing in react components.

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 the .env file which is not committed to the git repository.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.





Related posts

ReactJS Append variables with strings, jsx state and prop concatenate html

How to display the content of a JSON file in React with example

Reactjs Fix Must call a super constructor in derived class before accessing this

How to change default port in React with create-react-app command?

How to create an react typescript application | Create-react-app typescript application

How to handle broken images in React | fallback for broken images

Fixing an error You are running create-react-app 4.0.3, which is behind the latest release (5.0.0) in React