问题
I am attempting to pass my ENV variable of my stripe publishable key to the stripe.js file for Connect.
Dotenv gem:
gem 'dotenv-rails', groups: [:development, :test, :production]
I added it to my dotenv gem .env file:
STRIPE_PUBLISHABLE_KEY=pk_test_xxxxxxxxxx
STRIPE_SECRET_KEY=sk_test_xxxxxxxxxx
Then added to my stripe.js.erb file:
var stripe = Stripe("<%= ENV['STRIPE_PUBLISHABLE_KEY']%>");
changing the stripe.js to stripe.js.erb worked locally, but the ENV doesn't seem to work in production. Within Heroku variables, I have it set. And if I pass the key directly in the stripe.js/.js/erb it will work, so one way or another, the ENV isn't working during production.
Even if i take the code into the views with tags, it won't work unless i pass the key directly in.
I receive no errors on herokus side.
I also tried using credentials:
stripe:
stripe_publishable_key: pk_test_x
stripe_secret_key: sk_test_x
With this in my stripe.js/.js.erb file:
var stripe = Stripe('<%= Rails.application.credentials.dig(:stripe, :stripe_publishable_key) %>');
(i use this exact format for active storage and works and tried:
var stripe = Stripe('<%= Rails.application.credentials.stripe[:stripe_publishable_key] %>');
With these i get the following error pushing to heroku :
NoMethodError: undefined method `[]' for nil:NilClass
Questions: How can I pass the ENV variables through to production?
That question was solved by using .erb, but now the problem is the ENV file not reaching production.
回答1:
If you have remembered to precompile your assets (which I often forget when dealing with heroku), you will need to add the js.erb file to the precompile list explicitly (SO post, more detailed blog post)
In this case though, you actually do not need to wrap this up in a variable anyway. The publishable key can be (should be) included to identify your Stripe account and the interpolation is going to send it in plain text anyway (what you normally want to avoid by using ENV variables) so you can skip the interp step entirely.
Edit from comments: You need to verify that the env key is actually set on Heroku. There are two ways to check:
- login to the CLI and check
- check also through the settings in the dashboard (this has examples on how to do both)
If you're getting an empty string in the compiled JS then that would at least indicate that the ERB is getting processed so the error is likely that there is nothing to interpolate when it is.
Just to reiterate there's no reason to hide a the publishable key (that's why it's called that and why the docs pass it in the clear). Furthermore putting it in an ENV that gets interpolated into text isn't hiding anything anyway.
回答2:
I think you have forgotten to set RAILS_MASTER_KEY
environment variable in your Heroku app while using credentials approach. From your codebase assign content of master.key
to it.
来源:https://stackoverflow.com/questions/55371857/using-dotenv-in-production-or-passing-env-variables-to-js-js-erb-and-attempt-w