How do I use Netlify's environment variables with vanilla JavaScript?

I am not using React or Node. I want to use an API key for a small project that I don't want to commit to Github. Netlify has built in environment variables.

You set them up in a name key pair in Netlify something like

SECRET_NAME = secretkey

When the site builds, Node would replace anywhere I used process.env.SECRET_NAME with secretkey.

But I am not using Node, or a build process, so of course when I call process.env.ENV_VAR_NAME in my code it fails with the error Uncaught ReferenceError: process is not defined

What is the easiest way to utilize Netlify's environment variables with just vanilla Javascript?

Saw this question which suggests using a Netlify Lambda function, but it still uses Node which I am not using.


Solution 1:

Issue: There are no "secrets" client-side.

It's a common misconception that you can store secrets in React apps...despite my attempts to make this clear in the docs.

To avoid exposing your API key, you'll need to both store and read the key on a server. This means you'll need to build an app using a server-side framework such as Node.js.

Recommended Solution: Netlify Function

Netlify Functions are a convenient way to create an endpoint within the same repository/deployment.

Alternative Solution: Separate API

Create a separate API that fetches from the third-party API and returns the data.

Consider securing your API/function with CORS

You can make it harder (there are ways around this) for other sites to use your API by implementing CORS to only allow fetching from your frontend domain.

Solution 2:

After more reading, I know 2 things.

  1. How to do this. This video was helpful.

  2. You should not do this to try and hide API secrets or keys.

While it is true the keys won't be in your source code, the problem is once Netlify replaces the API secrets or keys then the client can see them. Not good.