Home  >  Q&A  >  body text

React.js: Why does accessing my API key from a .env file require the REACT_APP prefix when using it? ie. (process.env.REACT_APP_API_KEY)

<p>As per my understanding, the .env file should hold the API key with REACT_APP prefix followed by its name and to use the variable we have to omit the REACT_APP prefix but I noticed that in some cases there is a difference the behavior of. </p> <p>I set the environment variables in the .env file like this: <code>REACT_APP_YOUR_KEY_NAME=9999999999999</code>. And assuming it's accessed via process.env.YOUR_KEY_NAME. But I noticed that in some cases (not uniquely) a prefix is ​​required, otherwise the key looks to be <code>undefined</code>. So it only works if I use <code>process.env.REACT_APP_YOUR_KEY_NAME</code> </p> <pre class="brush:php;toolbar:false;">const FetchData= async () => { try { const cache = localStorage.getItem('apiData'); if (cache) { return JSON.parse(cache); } else { const response = await fetch(`${url}?key=${process.env.REACT_APP_API_KEY}`); const jsonData = await response.json(); localStorage.setItem('gameData', JSON.stringify(jsonData)); return jsonData; } } catch (error) { console.error('Error occurred:', error); return null; } }; export default FetchData;</pre></p>
P粉087951442P粉087951442435 days ago557

reply all(1)I'll reply

  • P粉333186285

    P粉3331862852023-09-04 08:17:05

    For all custom environment variables in the application created through create-react-app, we need to use REACT_APP_ prefix in the environment variable name, this is a requirement, if we do not follow the convention, the variable will not be accessible, That's it, just like VITE you need to combine VITE_.. or Nextjs with NEXT_PUBLIC... (Client components only)

    Also, remember that all values ​​are accessible on the client (browser). You should not use it for any data/credentials that your users should not have access to in the browser and for any super secret API keys.

    For maximum security, this should be used on the backend, and no prefix is ​​required on the backend.

    For more details you can check out the old documentation (again) on CRA https://create-react-app.dev/docs/adding-Custom environment variables

    reply
    0
  • Cancelreply