← Back to Upcase

Environment Specific 'constants' in Javascript


(Neil Edwards) #1

Hi guys,

I’m about to start using stripe.js (but this should relate to a lot of different JS API code). Part of the call to stripe involves passing the API a public ‘key’ to identify my site.
This key will necessarily be different between my testing and production environments.

My first thought here was to use the preprocessor, make my javascript a .erb. file and just do:

Stripe.setPublishableKey('<%= get_stripe_key %>'); or something similar.

However, I recently really took a liking to the data-* attributes in HTML5 and the flexibility they have and I was wondering what people thought about doing something like:

<body data-stripe-key='<%= get_stripe_key %>' >
...

instead and then the javascript would just read the body data-stripe-key attribute for the key.

For some reason I have an aversion to doing erb preprocessing for my javascript files, whereas erb for views is obviously very common…


(Pedro Moreira) #2

I think you should go with your preference on this one, although personally I’m not really a fan of tying the key to a DOM node. Also, going through the DOM to get a value that can be passed in directly otherwise is probably less effective performance wise.


(Derek Prior) #3

I really like data attributes but I generally want them to be semanticly related to the tag they are applied to. The key your talking about isn’t related to the body at all, really.

If you’re going to have a lot of JS in this project you may already have a JavaScript namespace for your application. You could have an environment_constants.js.coffee.erb file that does something like:

MyApp = MyApp || {}
MyApp.Environment = 
  STRIPE_KEY: <%= ENV['stripe_key'] %>
  OTHER_THING: <%= ENV['other_key'] %>

Then anywhere you need the environment constants you can use MyApp.Environment.STRIPE_KEY and not have to resort to ERB in that file.

I’ve done this in previous, non-rails projects and it worked out well.


(Neil Edwards) #4

You’re absolutely right in terms of having no relation to the body tag at all.

I guess it was a bad example and I’d probably put it in the form tag or something, but anyway, I like your constants idea a lot.

I’ll definitely consider that, it makes complete sense, thank you!