Rails has a cornucopia of options to access configuration values in your application. JavaScript, not so much.
What I’ve done is standardized on storing and retrieving values from meta tags in the <head>
:
# app/helpers/application_helper.rb
def js_config(name, value)
tag.meta name: name, content: value
end
<% content_for :head do %>
<%= js_config "userId", Current.user.id %>
<% end %>
// app/javascript/helpers/configuration.js
export function getConfig(name) {
return document.head
.querySelector(`meta[name="${name}"]`)
?.getAttribute("content")
}
// Wrap global helpers
export function getUserId() {
return getConfig("userId")
}
This approach avoids adding additional HTTP requests or relying on JSON blobs inserted into the page. It’s lightweight, keeps your app organized, and ensures configuration values are always accessible when you need them.
Ready to standardize your JavaScript configuration? Try this approach, and let me know how it works for you!