Securely Store API Key in Node and Request It From React
Published in
3 min readJul 23, 2020
Code example of this article see: https://github.com/xiaohan-du/code-playground/tree/master/weather-app
What am I trying to do?
I am trying to build a weather app using Node JS (Express) as backend and React JS as frontend. The basic steps are:
- generate a weather API from OpenWeather,
- fetch weather data from the API,
- display the data on the page.
The OpenWeather API follows this format: http://api.openweathermap.org/data/2.5/weather?q=cityName,countryName&APPID=123456qwerty
What problem did I have?
Originally I thought I’d fetch data from API using React. This is possible with the following FetchWeather component:
import React from 'react';class FetchWeather extends React.Component {
constructor(props) {
super(props);
this.getWeather = this.getWeather.bind(this);
} static async getWeather() {
const weatherAPI = `http://api.openweathermap.org/data/2.5/weather?q=london,uk&APPID=123456qwerty`; let response = await fetch(weatherAPI),
body = await response.json();
return body
}
}export default FetchWeather;
The weather data is returned into the variable body
. However, this solution has a security flaw: the API key is exposed…