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.

Zaheer
  • 2,794
  • 5
  • 28
  • 33

2 Answers2

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 %>'); 
Colonel Panic
  • 132,665
  • 89
  • 401
  • 465
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.

Community
  • 1
  • 1
jefflunt
  • 33,527
  • 7
  • 88
  • 126