简体   繁体   中英

How do I call a Node/Express API key (.env) in Client-side Javascript?

Right now I am using an OpenWeatherMap API key in my client side javascript for a simple weather app (Node/Express). I know this is not ideal outside of development, so I did npm install dotenv. On the server side, I can get and set the env variables just fine in Node. I can see them when I console.log out.

How do I call the API key in my javascript on the client-side? For example, currently my weather app has its simple logic in a file called weather.js and the HTML uses weather.js.

Ideally I would just like to call my api like http://api.openweathermap.org/data/2.5/forecast/daily?lat=${lat}&lon=${lon}&units=metric&appid=${process.env.WEATHER_API_KEY}

I know the .envs are on server side and you have to do stuff to make it work client side. New Node developer here who has read too much that I think I am confused between requireJS, Browserify, modules, .env, etc...

You don't want your API keys (or other secrets) to be public. Using them in the front-end would make them visible when inspecting the page and in the network requests log. You need to store and use your secrets server-side.

Create a route on your backend (which you protect from being used by other domains using CORS ) which calls the weather API (using the token stored in .env on your server) and sends back the data.

Then have your frontend hit that route.

You will have to request the API Key from the server.
This can be done easily by making a simple route in your backend that will return the key as a response.

If you don't want to expose your API Key (I recommend you to not expose it), what you can do is create a route in your backend that will make a call to the WeatherAPI using your API key, and the client will send HTTPS request to your backend, which will then create another HTTPS request to the WeatherAPI and send the response back to the client.

You don't want to expose your API keys to outside world. What you can do is to create backend route (/api/keys) make it protected with CORS and call it from front-end.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM