Skip to content

Harden the passing of data from the backend to the frontend in <script> blocks #1215

@philayres

Description

@philayres

Requirements

Harden the passing of data from the backend to the frontend in <script> blocks within .erb partials.

For example, the file app/views/layouts/_setup_app.html.erb sets up a lot of _fpa data for the app on load, by explicitly setting attributes like:

<%= javascript_tag nonce: true do %>
  _fpa.version = '<%=Application.version%>-<%=Application.server_cache_version%>';
  _fpa.status.session = new _fpa.session(<%= current_user ? current_user.timeout_in :  "null" %>);
...
  _fpa.state.is_admin_page = <%= (admin_or_user_class == 'admin_page').to_s %>;
  <% if current_user %>
  _fpa.state.app_configs = <%= Admin::AppConfiguration.all_for(current_user).to_json.html_safe %>;
...

A clearer and more reliable approach would be to set up Ruby hashes of attributes to be changed, and write a <script type="application/json>" block with the hashes .to_json. In the Javascript, get the element and use single line Javascript spread operator or Object.assign to merge the results into _fpa and _fpa.state.

An alternative would be to set data attributes on a DOM element using a Rails content tag, then retrieve in Javascript and merge them in the Javascript.

Other best practice approaches may also be considered.

Notes

There are other views that should be addressed in the same way. A search across .erb files for .to_json might identify them.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions