The Safest Way To Hide Your API Keys When Using React — Smashing Magazine (2024)

  • Jessica Joseph
  • 0 comments
  • 9 min read
  • API,Apps,Tools,React,Security

About The Author

Jessica works as a front-end engineer, creating interactive web applications with modern web technologies. In her spare time, she enjoys exploring the world of …More aboutJessica↬

Want to make sure your API keys are safe and sound when working with React? Jessica Joseph’s got you covered! She will show you the best ways to hide your API keys, from using environment variables to building your own back-end proxy server.

Back in the day, developers had to write all sorts of custom code to get different applications to communicate with each other. But, these days, Application Programming Interfaces (APIs) make it so much easier. APIs provide you with everything you need to interact with different applications smoothly and efficiently, most commonly where one application requests data from the other application.

While APIs offer numerous benefits, they also present a significant risk to your application security. That is why it is essential to learn about their vulnerabilities and how to protect them. In this article, we’ll delve into the wonderful world of API keys, discuss why you should protect your API keys, and look at the best ways to do so when using React.

What Are API Keys?

If you recently signed up for an API, you will get an API key. Think of API keys as secret passwords that prove to the provider that it is you or your app that’s attempting to access the API. While some APIs are free, others charge a cost for access, and because most API keys have zero expiration date, it is frightening not to be concerned about the safety of your keys.

Why Do API Keys Need To Be Protected?

Protecting your API keys is crucial for guaranteeing the security and integrity of your application. Here are some reasons why you ought to guard your API keys:

  • To prevent unauthorized API requests.
    If someone obtains your API key, they can use it to make unauthorized requests, which could have serious ramifications, especially if your API contains sensitive data.
  • Financial insecurity.
    Some APIs come with a financial cost. And if someone gains access to your API key and exceeds your budget requests, you may be stuck with a hefty bill which could cost you a ton and jeopardize your financial stability.
  • Data theft, manipulation, or deletion.
    If a malicious person obtains access to your API key, they may steal, manipulate, delete, or use your data for their purposes.

Best Practices For Hiding API Keys In A React Application

Now that you understand why API keys must be protected, let’s take a look at some methods for hiding API keys and how to integrate them into your React application.

Environment Variables

Environment variables (env) are used to store information about the environment in which a program is running. It enables you to hide sensitive data from your application code, such as API keys, tokens, passwords, and just any other data you’d like to keep hidden from the public.

One of the most popular env packages you can use in your React application to hide sensitive data is the dotenv package. To get started:

  1. Navigate to your react application directory and run the command below.
    npm install dotenv --save
  2. Outside of the src folder in your project root directory, create a new file called .env.
    The Safest Way To Hide Your API Keys When Using React — Smashing Magazine (8)
  3. In your .env file, add the API key and its corresponding value in the following format:
    // for CRA applicationsREACT_APP_API_KEY = A1234567890B0987654321C ------ correct// for Vite applicationsVITE_SOME_KEY = 12345GATGAT34562CDRSCEEG3T ------ correct
  4. Save the .env file and avoid sharing it publicly or committing it to version control.
  5. You can now use the env object to access your environment variables in your React application.
    // for CRA applications'X-RapidAPI-Key':process.env.REACT_APP_API_KEY// for Vite applications'X-RapidAPI-Key':import.meta.env.VITE_SOME_KEY
  6. Restart your application for the changes to take effect.

However, running your project on your local computer is only the beginning. At some point, you may need to upload your code to GitHub, which could potentially expose your .env file. So what to do then? You can consider using the .gitignore file to hide it.

The .gitignore File

The .gitignore file is a text file that instructs Git to ignore files that have not yet been added to the repository when it’s pushed to the repo. To do this, add the .env to the .gitignore file before moving forward to staging your commits and pushing your code to GitHub.

// .gitignore# dependencies/node_modules/.pnp.pnp.js# api keys.env

Keep in mind that at any time you decide to host your projects using any hosting platforms, like Vercel or Netlify, you are to provide your environment variables in your project settings and, soon after, redeploy your app to view the changes.

Back-end Proxy Server

While environment variables can be an excellent way to protect your API keys, remember that they can still be compromised. Your keys can still be stolen if an attacker inspects your bundled code in the browser. So, what then can you do? Use a back-end proxy server.

A back-end proxy server acts as an intermediary between your client application and your server application. Instead of directly accessing the API from the front end, the front end sends a request to the back-end proxy server; the proxy server then retrieves the API key and makes the request to the API. Once the response is received, it removes the API key before returning the response to the front end. This way, your API key will never appear in your front-end code, and no one will be able to steal your API key by inspecting your code. Great! Now let’s take a look at how we can go about this:

  1. Install necessary packages.
    To get started, you need to install some packages such as Express, CORS, Axios, and Nodemon. To do this, navigate to the directory containing your React project and execute the following command:
    npm install express cors axios nodemon
  2. Create a back-end server file.
    In your project root directory, outside your src folder, create a JavaScript file that will contain all of your requests to the API.
    The Safest Way To Hide Your API Keys When Using React — Smashing Magazine (9)
  3. Initialize dependencies and set up an endpoint.
    In your backend server file, initialize the installed dependencies and set up an endpoint that will make a GET request to the third-party API and return the response data on the listened port. Here is an example code snippet:
    // defining the server portconst port = 5000// initializing installed dependenciesconst express = require('express')require('dotenv').config()const axios = require('axios')const app = express()const cors = require('cors')app.use(cors())// listening for port 5000app.listen(5000, ()=> console.log(`Server is running on ${port}` ))// API requestapp.get('/', (req,res)=>{ const options = { method: 'GET', url: 'https://wft-geo-db.p.rapidapi.com/v1/geo/adminDivisions', headers: { 'X-RapidAPI-Key':process.env.REACT_APP_API_KEY, 'X-RapidAPI-Host': 'wft-geo-db.p.rapidapi.com' } }; axios.request(options).then(function (response) { res.json(response.data); }).catch(function (error) { console.error(error); });}
  4. Add a script tag in your package.json file that will run the back-end proxy server.
    The Safest Way To Hide Your API Keys When Using React — Smashing Magazine (10)
  5. Kickstart the back-end server by running the command below and then, in this case, navigate to localhost:5000.
    npm run start:backend
  6. Make a request to the backend server (http://localhost:5000/) from the front end instead of directly to the API endpoint. Here’s an illustration:
    import axios from "axios";import {useState, useEffect} from "react"function App() { const [data, setData] = useState(null) useEffect(()=>{ const options = { method: 'GET', url: "http://localhost:5000", } axios.request(options) .then(function (response) { setData(response.data.data) }) .catch(function (error) { console.error(error); }) }, []) console.log(data) return ( <main className="App"> <h1>How to Create a Backend Proxy Server for Your API Keys</h1> {data && data.map((result)=>( <section key ={result.id}> <h4>Name:{result.name}</h4> <p>Population:{result.population}</p> <p>Region:{result.region}</p> <p>Latitude:{result.latitude}</p> <p>Longitude:{result.longitude}</p> </section> ))} </main> )}export default App;

Okay, there you have it! By following these steps, you’ll be able to hide your API keys using a back-end proxy server in your React application.

Key Management Service

Even though environment variables and the back-end proxy server allow you to safely hide your API keys online, you are still not completely safe. You may have friends or foes around you who can access your computer and steal your API key. That is why data encryption is essential.

With a key management service provider, you can encrypt, use, and manage your API keys. There are tons of key management services that you can integrate into your React application, but to keep things simple, I will only mention a few:

  • AWS Secrets Manager
    The AWS Secrets Manager is a secret management service provided by Amazon Web Services. It enables you to store and retrieve secrets such as database credentials, API keys, and other sensitive information programmatically via API calls to the AWS Secret Manager service. There are a ton of resources that can get you started in no time.
  • Google Cloud Secret Manager
    The Google Cloud Secret Manager is a key management service provided and fully managed by the Google Cloud Platform. It is capable of storing, managing, and accessing sensitive data such as API keys, passwords, and certificates. The best part is that it seamlessly integrates with Google’s back-end-as-a-service features, making it an excellent choice for any developer looking for an easy solution.
  • Azure Key Vault
    The Azure Key Vault is a cloud-based service provided by Microsoft Azure that allows you to seamlessly store and manage a variety of secrets, including passwords, API keys, database connection strings, and other sensitive data that you don’t want to expose directly in your application code.

There are more key management services available, and you can choose to go with any of the ones mentioned above. But if you want to go with a service that wasn’t mentioned, that’s perfectly fine as well.

Tips For Ensuring Security For Your API Keys

You have everything you need to keep your API keys and data secure. So, if you have existing projects in which you have accidentally exposed your API keys, don’t worry; I’ve put together some handy tips to help you identify and fix flaws in your React application codebase:

  1. Review your existing codebase and identify any hardcoded API key that needs to be hidden.
  2. Use environment variables with .gitignore to securely store your API keys. This will help to prevent accidental exposure of your keys and enable easier management across different environments.
  3. To add an extra layer of security, consider using a back-end proxy server to protect your API keys, and, for advanced security needs, a key management tool would do the job.

Conclusion

Awesome! You can now protect your API keys in React like a pro and be confident that your application data is safe and secure. Whether you use environment variables, a back-end proxy server, or a key management tool, they will keep your API keys safe from prying eyes.

Further Reading On SmashingMag

  • How To Protect Your API Key In Production With Next.js API Route”, Caleb Olojo
  • Useful React APIs For Building Flexible Components With TypeScript”, Gaurav Khanna
  • State Management In Next.js”, Atila Fassina
  • Internationalization In Next.js 13 With React Server Components”, Jan Amann

The Safest Way To Hide Your API Keys When Using React — Smashing Magazine (11)(gg, yk, il)

Explore more on

The Safest Way To Hide Your API Keys When Using React — Smashing Magazine (2024)

FAQs

How do I hide my API key safely using React? ›

While API-keys should ideally be hidden from client-side code to prevent exposure, it's challenging to completely hide them in React applications since client-side code is accessible to users. However, storing API keys in environment variables and using server-side validation can help mitigate risks.

Is there a way to hide an API key? ›

One effective way to hide API keys is by using environment variables. Environment variables are set outside of the application code and are accessible during runtime. They are commonly used to store sensitive data like API keys and database credentials without hardcoding them into the source code.

Which is the most secure way to use an API key? ›

Avoid Client-Side Exposure. Storing API keys in client-side code such as JavaScript is an insecure practice as it makes them easily accessible to malicious actors. To ensure the security of your API keys, never embed them in URLs or client-side code. Instead, keep them securely stored server-side to protect your data.

Is it OK to expose an API key? ›

When your API keys are exposed, it could spell trouble for your business in a myriad of ways, both immediately and over time. Here are some of the potential repercussions: Data breaches: If your API keys fall into the wrong hands, they can be used to access or alter your sensitive data.

How do I hide API keys in Reactjs application and prevent them from being visible in the browser developer tools Network tab? ›

Steps to keep your API keys safe:
  1. Creating .env file:Just create a .env named file in the root directory of your React project as shown below:
  2. Creating env variables in .env file: Using the prefix REACT_APP, create your own env variables and assign the key as shown below:
Dec 10, 2020

How do I protect my anonymous API? ›

APIs that don't use proper authentication can expose sensitive data or functionality to unauthorized users. Prevent this by implementing robust authentication mechanisms like OAuth 2.0. Make sure that credentials aren't exposed in URLs or logs and implement multi-factor authentication (MFA) where possible.

How to secure API in React JS? ›

In React, the environment variables are still injected into the build - you can easily see them in the browser. The only way to secure your API keys is to keep them on your own server. You are then authed to your server via a JWT, cookie or similar and you access the 'secure' api via there.

How do I create a secret API key? ›

How to create an API Key and Secret
  1. Go to the Keys section and click Add.
  2. Enter the key name.
  3. Click Save. The system will display the key and the secret. Copy it for future reference. if your Key and Secret is set up, see Using API Hooks for more information on how to use the API Hook.

How to protect your API keys? ›

Protect your API key and signing secret in mobile apps using web services or Static Web APIs. To protect mobile apps, use a secure keystore or secure proxy server: Store the API key or signing secret in a secure keystore. This step makes it harder to scrape API keys and other private data directly from the application.

What is the best way to secure API? ›

8 best practices for securing APIs
  1. Design with security in mind. ...
  2. Audit and update regularly. ...
  3. Implement robust authentication mechanisms. ...
  4. Code to protect against common cyber attacks. ...
  5. Implement rate limiting. ...
  6. Encrypt sensitive data. ...
  7. Use API gateways. ...
  8. Align with established security standards.
Jul 1, 2024

Which way should be used to safely the API key? ›

To keep your API keys secure, follow these best practices: Do not embed API keys directly in code: API keys that are embedded in code can be accidentally exposed to the public, for example, if you forget to remove the keys from code that you share.

Should I hide my API key? ›

Hiding the API access key stands out as the most important way to secure API access. Some of the reasons why developers store API access keys are as follows: Security: Hiding your API access key ensures security during API access.

How to not expose API keys? ›

You can use a route handler to create a proxy endpoint that will take the request from the client, and then make the request to the 3rd party API on the server. This way, the client never sees the API key, and you can do whatever you want with the response before sending it back to the client.

How to securely store API keys in frontend? ›

To use environment variables securely:
  1. Store the API key in an environment variable on your build server or hosting platform.
  2. Access the key using syntax like process. env. API_KEY (Node. js) or os. environ["API_KEY"] (Python)
  3. Be sure to set the variable securely and never commit . env files containing secrets.
Apr 22, 2024

How do I secure API in Reactjs? ›

js backend can be properly secured by adhering to best practices and applying robust security mechanisms. From setting up authentication with JWT tokens to proxying requests through a server, each step is critical in protecting sensitive data from unauthorized access and potential security concerns.

How to hide API key in React Reddit? ›

We all know that everything you include in your React Native app is visible, including anything in your . env file. This means that any API keys you include in your code can be found. The best way to hide an API key is by communicating with a back end server that you have set up.

How do I restrict API key? ›

Adding Android restrictions

You can restrict usage of an API key to only your Android apps. When you create or update an API key, provide the package name and the 20 byte SHA-1 fingerprint for each app. For example, assume that you ran the keytool utility and it created the following fingerprint: See more code actions.

Top Articles
Venture Capital Outlook 2024 | Nixon Peabody LLP
Are Celsius drinks healthy for kids? — Malina Malkani
Tyler Sis 360 Louisiana Mo
Busted Newspaper Zapata Tx
Es.cvs.com/Otchs/Devoted
Linkvertise Bypass 2023
Die Windows GDI+ (Teil 1)
Sam's Club Gas Price Hilliard
Tv Schedule Today No Cable
Scentsy Dashboard Log In
Xm Tennis Channel
Boat Jumping Female Otezla Commercial Actress
Student Rating Of Teaching Umn
Cool Math Games Bucketball
The fabulous trio of the Miller sisters
Darksteel Plate Deepwoken
Bahsid Mclean Uncensored Photo
Find Such That The Following Matrix Is Singular.
Jang Urdu Today
Walgreens Tanque Verde And Catalina Hwy
Mail.zsthost Change Password
Dragger Games For The Brain
Mega Personal St Louis
Like Some Annoyed Drivers Wsj Crossword
Pirates Of The Caribbean 1 123Movies
27 Paul Rudd Memes to Get You Through the Week
The Listings Project New York
Hesburgh Library Catalog
Timeline of the September 11 Attacks
Divide Fusion Stretch Hoodie Daunenjacke für Herren | oliv
Mikayla Campinos: Unveiling The Truth Behind The Leaked Content
Radical Red Ability Pill
100 Gorgeous Princess Names: With Inspiring Meanings
Pipa Mountain Hot Pot渝味晓宇重庆老火锅 Menu
Persona 4 Golden Taotie Fusion Calculator
Mkvcinemas Movies Free Download
Gideon Nicole Riddley Read Online Free
Pitco Foods San Leandro
Greater Keene Men's Softball
Michael Jordan: A timeline of the NBA legend
Directions To Advance Auto
Legit Ticket Sites - Seatgeek vs Stubhub [Fees, Customer Service, Security]
My Locker Ausd
Bekah Birdsall Measurements
Does Target Have Slime Lickers
Jammiah Broomfield Ig
Gary Vandenheuvel Net Worth
bot .com Project by super soph
Marcel Boom X
Blog Pch
Strawberry Lake Nd Cabins For Sale
Latest Posts
Article information

Author: Kimberely Baumbach CPA

Last Updated:

Views: 6856

Rating: 4 / 5 (61 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Kimberely Baumbach CPA

Birthday: 1996-01-14

Address: 8381 Boyce Course, Imeldachester, ND 74681

Phone: +3571286597580

Job: Product Banking Analyst

Hobby: Cosplaying, Inline skating, Amateur radio, Baton twirling, Mountaineering, Flying, Archery

Introduction: My name is Kimberely Baumbach CPA, I am a gorgeous, bright, charming, encouraging, zealous, lively, good person who loves writing and wants to share my knowledge and understanding with you.