I’m making an express application that requires a map. I’m using the HERE Maps API for javascript boilerplate to render the map. https://developer.here.com/documentation/examples/maps-js
I am already using the dotenv package for environment variables (port, host) in my application. But I don’t know how to hide the map API key in the backend when I need to use the document
object to render the map. Currently, I’m using a separate file config.js to store the variable but the key is still visible in the frontend.
In conclusion, I can hide the API key in the backend but I can’t render the map in the backend and I can render the map in the frontend but I can’t hide the API key in the frontend. How can I both hide the API key and render the map?
Minimum, reproducible, example:-
Structure of root directory
| public
| config.js
| map.js
| views
| index.pug
| .env
| index.js
| package.json
index.pug
doctype html
html
head
link(rel="stylesheet" href="https://js.api.here.com/v3/3.1/mapsjs-ui.css")
script(src="https://js.api.here.com/v3/3.1/mapsjs-core.js")
script(src="https://js.api.here.com/v3/3.1/mapsjs-service.js")
script(src="https://js.api.here.com/v3/3.1/mapsjs-ui.js")
script(src="https://js.api.here.com/v3/3.1/mapsjs-mapevents.js")
script(src="config.js" defer)
script(src="map.js" defer)
body
#map(data-lat=lat data-lng=lng)
config.js
const config = {
MAP_API_KEY: `${API_KEY}`
}
map.js
const mapEl = document.getElementById('map')
const platform = new H.service.Platform({
apikey: config.MAP_API_KEY
})
const defaultLayers = platform.createDefaultLayers()
const map = new H.Map(mapEl, defaultLayers.vector.normal.map, {
center: {
lat: parseFloat(mapEl.dataset.lat),
lng: parseFloat(mapEl.dataset.lng)
},
zoom: 5,
pixelRatio: window.devicePixelRatio || 1
})
window.addEventListener('resize', () => map.getViewPort().resize())
const behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map))
const ui = H.ui.UI.createDefault(map, defaultLayers)