How to use a variable from `.env` in a web page


#1

Can anyone share an example of how to store and then use a variable or setting like an API key from the project .env file in a web page?

I’m personally most interested Mapbox access token at the moment but I’m sure the pattern is applicable to many more things.

Thanks!

<head><style>body {margin: 0;  padding: 0;} #map {position: absolute;  top: 1.5em;  bottom: 0;  width: 100%;}</style></head>
<body>
<a href="/">Home</a>
<link href="https://api.mapbox.com/mapbox.js/v3.0.1/mapbox.css" rel="stylesheet" />
<script src="https://api.mapbox.com/mapbox.js/v3.0.1/mapbox.js"></script>
  <div id="map"></div>
<script>
  var home = [60.672, -135.024];
  L.mapbox.accessToken ='>>>TOKEN FROM .env HERE<<<';  
  var map = L.mapbox.map('map','mapbox.light').setView(home, 15);
  </script>
</body>

#2

Sure, you want to use a template and pass that value from the server to the front-end. The slack passport auth example does this, using the client_id in the Sign in with Slack button. The important parts are setting up express to use handlebars, passing the env variable in the route, and the handlebars template itself.


#3

Thanks. There is a lot of other stuff in there that confuses my beginners mind! I did manage to prune it down to a simplest example I can build from. For anyone one else in a similar situation, this might save you an hour or so:

:smile:


#4

Keep in mind that this can be a security issue. Don’t pass anything to the client that you don’t want the whole world to know.