Skip to content
PLAY VIDEO PLAY VIDEO PLAY VIDEO
By Sebastian Porto

Rails server sent JavaScript considered harmful

Rails provides a very convenient way of sending forms via AJAX using the Rails UJS helpers e.g.

<%= form_for @articles, remote: true do |f| %>
  ...
<% end %>

Then in your controller you can process that form and respond with javascript:

// app/views/articles/create.js.erb
$("<%= escape_javascript(render @article) %>").appendTo("#article");

This makes for an impressive demo of the capabilities of Rails, but there are problems with it:

Hooking into the lifecycle is awkward

At some point you might want to do some client side validation or something else before sending the form. To do this you will need to hook into the lifecycle by doing something like:

$('#new_account_form').on('ajax:before', function () {
    // do some validation
    // return false if not valid
 });

So now you have some JavaScript in the front-end and some in the server. This is of course harder to maintain than having the JavaScript in only one place.

They end up doing too much

Once you have some JavaScript returned by the server manipulating part of the page, it is just too easy to start doing too much in this response, for example start modifying elements outside the scope of the original element.

// app/views/articles/create.js.erb
$("<%= escape_javascript(render @article) %>").appendTo("#article");
$("#header .article-count").html(<%= Article.size %>);
$("#footer .info").html("Last updated by");

In this example the returned JavaScript is doing way too much. Of course you can also do this kind of thing in the front-end, but at least the mess is in one place.

What to do

I am going to be blunt and say that Rails UJS when combined with server sent JavaScript encourages bad design. They are good for small trivial things, but soon they get out of control. Some alternatives are:

Using Rails UJS but without the server sent JavaScript

Rails remote is still useful, using it is easier than just plain DIY. You can hook into the lifecycle of remote calls and get html from the server, then insert that HTML yourself without having to send back JavaScript. e.g.

$('#new_account_form')
    .on('ajax:before', function () {
        // some validation
    })
    .on('ajax:success', function (data, status, xhr) {
        // insert the data returned into the page
        $('#articles').append(data);
     });

Your server will only return HTML. So what is the improvement? At least your JavaScript code is in one place making it easier to refactor later.

Other alternatives

Other good alternatives are not to use Rails UJS at all, just plain AJAX or using a JavaScript framework. These can encourage better structured applications, but that is too big of a topic to cover here.

Conclusion

Rails UJS + server sent JavaScript is great for trivial things, but it doesn't scale very well for medium to large applications. So I believe that completely avoiding JavaScript responses from the server is a good first step for making more robust and maintainable applications (there is a lot more to it than that, of course).

Your server should only respond with either HTML or JSON, never JavaScript.

Latest Articles by Our Team

Our expert team of designers and developers love what the do and enjoy sharing their knowledge with the world.

We Hire Only the Best

reinteractive is Australia’s largest dedicated Ruby on Rails development company. We don’t cut corners and we know what we are doing.

We are an organisation made up of amazing individuals and we take pride in our team. We are 100% remote work enabling us to choose the best talent no matter which part of the country they live in. reinteractive is dedicated to making it a great place for any developer to work.

Free Community Workshops

We created the Ruby on Rails InstallFest and Ruby on Rails Development Hub to help introduce new people to software development and to help existing developers hone their skills. These workshops provide invaluable mentorship to train developers, addressing key skills shortages in the industry. Software development is a great career choice for all ages and these events help you get started and skilled up.

  • Webinars

    Webinars

    Webinars are our online portal for tips, tricks and lessons learned in everything we do. Make the most of this free resource to help you become a better developer.

    Learn more about webinars

  • Installfest

    Installfest

    The Ruby on Rails Installfest includes a full setup of your development environment and step-by-step instructions on how to build your first app hosted on Heroku. Over 1,800 attendees to date and counting.

    Learn more about Installfest

  • Development Hub

    Development Hub

    The Ruby on Rails Development Hub is a monthly event where you will get the chance to spend time with our team and others in the community to improve and hone your Ruby on Rails skills.

    Learn more about Development Hub

Get the “reinteractive Review” Monthly Email