While developing SPA project, we sometimes need to use API keys. Although it is possible to hide these API keys with .ENV file importing method, you must find another method on production process because of the fact that:
You can try to create a new express.js project to get request from your client then forward this request this to 3rd party endpoint with API key (on backend side).
After it gets response from 3rd party endpoint, your express.js backend project must forward this response to you.
Here you can find my solution and steps:
const express = require("express");
const helmet = require("helmet");
const axios = require("axios");
const path = require('path');
var bodyParser = require("body-parser");
const app = express();
app.use(helmet());
app.use(bodyParser.json());
app.get("/api/address", (req, res) => {
try {
axios
.get(
`https://your-endpoint-url.com?API_KEY=PUT_YOUR_KEY&POSSIBLE_QUERY_TO_ENDPOINT=${req.query.POSSIBLE_QUERY_FROM_CLIENT}`
)
.then(response => {
res.status(200).send(response.data);
})
.catch(err => res.status(400).send("Bad Request"));
} catch (err) {
res.status(404).send("Backend Error");
}
});
// Thanks to @fatihyildizli for security update
const port = process.env.PORT || 4000;
app.listen(port);
console.log("App is listening on port " + port);