Uncaught ReferenceError: process is not defined

I have a plain HTML/CSS/JavaScript page - no Node, no frameworks, just plain old HTML/CSS/JS.

How do I access environment variables from my Javascript?

Using process.env gives me the error posted in the subject.

I have come across the solution to use sed in the build command, and it works, but I’d rather not use that approach as it exposes my environment variables with a simple “view source”. Might as well have them hard-coded as regular variables.

Is there some other way to pull in environment variables? Again, without having to resort to Node, dotenv etc.

Thanks in advance.

Hi!

You can’t access process.env from client side javascript unless you define that object in your JS, that’s beaus it comes from Node. You’ll need to write a script that runs during build time to inject the process.env variables in to your client side javascript. Note that you shouldn’t inject everything in process.env but just the actual variables you need, this is for your own security and privacy.

Thanks @futuregerald Appreciate your reply and suggestion of how to work around this. Any examples I can refer to of how to write such a script? Thanks again.

This article talks about “ways to use environment variables at Netlify” that has some direct examples:

Thanks, Chris, for your extensive answer on this.

What if there is no build environment to speak of? Like I said, my use case is plain vanilla HTML/CSS/JS, no webpack, no framework or front-end library. Am I to understand that it’s impossible to access env vars in that case?

Thanks again for your help.

The variables are still available during “build” which I understand you don’t do…but you could (and not by adding a framework or SSG!)

In that situation (which is also my situation on several legacy sites), I’d write a build script that does some interpolation. We give you a unix shell, so you can do anything you like there. This is a quick untested hack that probably has syntax errors, but the general concept is illustrated and should work as a build command to interpolate values from the environment into your files. I’d probably put it in a script and call it as chmod a+x scriptname && ./scriptname (but don’t call your script “build” or it will break things!)

cd your-publish-directory # only needed if you don't use / in your repo as the publish directory!
find . -type f -name \*.html -o -name \*.js -o -name \*.css -exec sed -i s/PLACEHOLDER/${VARIABLE}/g

you could also use it more simply, something like:

echo $MY_VARIABLE : ${BRANCHNAME}-${DEPLOY_ID} > version.txt

Anyway, I think they can still be useful since they are still available during build - you just have to use them, and shell script is one way to do that :slight_smile: