DEV Community

Discussion on: How Can I Access Environment Variables in My Static Website?

Collapse
vonheikemen profile image
Heiker • Edited

From where I stand now, I'm going to need to incorporate Node

You're on the right track here. If you don't want to expose your API key to the browser this is the way to go. You should even fetch your podcast data in the server to eliminate the need for your api key in the front-end.

I can rebuild the website as a React app and then install dotenv as a package and simply import it and the environment variable into my app.

This is fine too, but a bit of an overkill. You don't need react for this, just a bundler. I suggest using parcel because is the most easy to use. The downside of this is that it makes the "deploy process" more complex, unless of course you just push the bundled assets directly in github (Is what I would do [but I'm not a good role model]).

Once you finish setting up parcel you should create a .env file in the same directory you have the package.json file.

APIKEY=SupaSecretStuff

Then in your html or js files you can access the variables using the process.env. prefix. Like this.

<html>
  <body>
    hello
  </body>
  <script>
    console.log(process.env.APIKEY);
  </script>
</html>
Collapse
bobrown101 profile image
Brady Brown

If your api keys or env variables are sensitive, this is not acceptable, as the compiled code that will be sent to the client will include the api keys or env bars as plain text.

Underneath the hood, webpack or parcel is doing a simple text replace