It is not safe to store private API keys in React Js. If I store my API key in the React web app, the user can view it. Even if I store the API key in .env
files, the end user can still view it.
I create a .env
file to sore my API key to demonstrate that.
REACT_APP_API_KEY = abc123
Then my React component uses that key to do an API call.
import { useEffect, useState } from "react"
export const Person = () =>{
interface ResponseType {
userId: number
id: number
title: string
completed: boolean
}
const [response, setResponse] = useState<ResponseType>()
const callApiWithSecretKey = () => {
fetch(`https://jsonplaceholder.typicode.com/todos/1?apikey=${process.env.REACT_APP_API_KEY}`)
.then(data => data.json())
.then(data => setResponse(data))
}
useEffect(() => {
callApiWithSecretKey()
},[])
return(
<>
{response?.userId}
</>
)
}
My API call includes the API key from the .env file.
That sounds safe. If I use GIT, it ignores the .env
file because the .env file may contain non-public information that I don't want my users to know.
But that's not the case. My users can view my API key by inspecting the network traffic. Press F12 to open up chrome developer tools and use the Network tab to inspect the network traffic. You may need to refresh the page to see the network traffic.