3

I have a ruby/rack app on Heroku serving a site. The site uses Javascript and I want to access an Heroku environment variable in the Javascript file (an API key). I've tried:

process.env.API_KEY
// As well as:
process.env['API_KEY']

But neither seem to work. I get a process is not defined error. The above lines of code I got were from a Node.js app running on Heroku. I thought it'd be the same way to access the keys from a normal js file but it doesn't work.

2 Answers 2

3

You're confused. That Javascript is running in visitors' web browsers, not on Heroku, so can't read the server's environment variables. This is a common problem. The solution is for your web app to serve the Javascript by a Ruby template, inserting the public API key.

Simple app I wrote has an example. https://github.com/hickford/nanoblogger The Javascript file nano.js is rendered by a Ruby erb template

var pusher = new Pusher( '<%= Pusher.key %>'); 
Sign up to request clarification or add additional context in comments.

Comments

1

The process.env stuff is part of Node.js, and not part of JavaScript, so it's not going to come over to your app.

Your rack app should have access to environment variables, however, so if you can pass that value up to something that's accessible to your JavaScript (without exposing it to the user/DOM, if it's sensitive information) then that should work.

This other answer may point you in a useful direction, or at least clarify if what you're trying to do is possible from JavaScript.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.