Zach Newburgh Zach Newburgh - 24 days ago 9
AngularJS Question

Accessing ENV variables in Rails-AngularJS (1.5) application

Working on a Rails-AngularJS (1.5) application and I'm having trouble accessing my ENV variables in the JavaScript (services, console, etc.).

I'm using dotenv, placed my SECRET_KEY in a .env file, and added the following to the bottom of my body tags in my application's layout.html.erb:

<script type="text/javascript">
var SECRET_KEY = "<% ENV['SECRET_KEY'].html_safe %>";
</script>


So grateful for any guidance!

Answer

I recommend you to do it in this way:

<%= content_tag "div", id: "secret_key", data: { key: ENV['SECRET_KEY'] } do %>
<% end %>

Add this to your layout.html.erb, so you can access the data from JS using:

var secret_key = document.getElementById("secret_key").dataset.key
Comments