What is best practice for importing .env variables into the Stimulus scope?

Hello! I love Hotwire! Thanks to everyone who made this a thing.

Is there a best practice for importing .env variables into the stimulus scope? My intention is to have a JWT_SECRET value accessible to both the Rails and Javascript environments for encoding and decoding data. Of course, this means I need to keep it hidden from any bad actors.

I am using importmaps with Stimulus. I tried implementing dotenv but was unsuccessful getting it to register and config in my application.js controller.

Any advice would be greatly appreciated. Google did not yield any valuable results and I am sure I am not the only one with this question.

Thanks in advance for your time! You, awesome unknown person, ROCK!

1 Like

Hi, be careful with that. You should not expose any secret values in the client, i.e. javascript.

Agreed! That’s the entire point. :slight_smile: I would never expose any secrets on the client. What I am looking for is the Stimulus equivalent of using dotenv in React or Node. Something along the lines of: process.env.VARIABLE_NAME.

I’ve tried getting dotenv to work with Stimulus but have had enough difficulty to warrant asking about best practices.

But Stimulus is the client. It’s javascript client side code and meant to interact with the HTML the client sees. The HTML is server-rendered, but the Stimulus code isn’t. It’s served as a static asset. It’s not meant to process backend stuff. Unless I’m misunderstanding what you’re trying to do (which is possible!), your only way to make it work would be using a js.erb file extension and let it be processed at runtime, but this is a very bad practice for a number of reasons and might not even work.

I’d look into issuing the JWT_SECRET through an HTTPOnly cookie, unreadable to Stimulus (or the javascript for that matter). I think that might be just the thing you need.

I think if you issue a fetch from Stimulus to a host from which a JWT_SECRET HTTPOnly cookie was received, that cookie will be sent a long with your fetch request.

In that case, you could include the environment variables from the html, for example in some meta tag and then get them from stimulus. Or using the stimulus value api as well. But always injecting the environment variables in the html. Another option is to store them in the html element as data-my-variable-name.