I am trying to put my API key in my .env file that is located in the root of my project( on the same level as the package json file)
When I console log the REACT_API_KEY it is read as undefined
I have restarted the server multiple times, everything is saved.
CodePudding user response:
I recommend using a library called dotenv. This will read your .env
file.
let's say you have an environment variable: REACT_API_KEY=APIKEY
.
You can access the value like this:
require('dotenv').config();
console.log(process.env.REACT_API_KEY);
This will log: APIKEY
This will be on the backend side, you then need to use some form of node.js library to serve the data to the frontend. Here is an example using express:
const express = require('express');
const app = express();
require('dotenv').config();
app.get('/apikey', (req, res) => {
res.send(process.env.REACT_API_KEY);
})
Now in the frontend you will need to create a GET
request to this uri to actually get the data. Here is an example using axios:
axios.get('/apikey').then((res) => {
console.log(res);
// res will be your API key in a String format
})
Obviously, because this key is hidden in the backend, you won't want users to be able to access this endpoint in your API. you can configure which endpoints you want your users to be able to access using a webserver like nginx.
This may seem like a lot for an environment variable, although these steps will solve many of your problems in the future, for things such as user logins and registry, and other data.
This is how you do it without the ReactJS build process. If you are using create-react-app to build your app, you can use React environment variables that are embedded during the build process. Check this out in the react documentation
CodePudding user response:
I needed to append process.env. to the beginning.