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


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.


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


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.


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:



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.