Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't set values on `process.env` in client-side Javascript

I have a system (it happens to be Gatsby, but I don't believe that's relevant to this question) which is using webpack DefinePlugin to attach some EnvironmentVariables to the global variable: process.env

I can read this just fine.

Unfortunatley, due to weirdnesses in the app startup proces, I need have chosen to do some brief overwritting of those EnvironmentVariables after the site loads. (Not interested in discussing whether that's the best option, in the context of this question. I know there are other options; I want to know whether this is possible)

But it doesn't work :(


If I try to do it explicitly:
process.env.myVar = 'foo';

Then I get ReferenceError: invalid assignment left-hand side.


If I do it by indexer (which appears to be what dotenv does) then it doesn't error, but also doesn't work:

console.log(process.env.myVar);
process.env['myVar'] = 'foo';
console.log(process.env.myVar);

will log undefined twice.


What am I doing wrong, and how do I fix this?
like image 780
Brondahl Avatar asked Dec 17 '22 20:12

Brondahl


1 Answers

The premise behind this attempted solution was flawed.

I was under the impression that webpack "made process.env.* available as an object in the browser".

It doesn't!

What it actually does is to transpile you code down into literals wherever you reference process.env. So what looks like fetch(process.env.MY_URL_VAR); isn't in fact referencing a variable, it's actually being transpiled down into fetch("http://theActualValue.com") at compile time.

That means that it's conceptually impossible to modify the values on the "process.env object", because there is not in fact an actual object, in the transpiled javascript.


This explains why the direct assignment gives a ref error (you tried to execute "someString" = "someOtherString";) but the indexer doesn't. (I assume that process.env gets compiled into some different literal, which technically supports an indexed setter)


The only solutions available would be to modify the webpack build process (not an option, though I will shortly raise a PR to make it possible :) ), use a different process for getting the Env.Vars into the frontEnd (sub-optimal for various other reasons) or to hack around with various bits of environment control that Gatsby provides to make it all kinda-sorta work (distasteful for yet other reasons).

like image 161
Brondahl Avatar answered Jan 06 '23 14:01

Brondahl