Rails route URL helpers in JavaScript

Good Morning,

Rails route URL helpers are great. Their API is concise and intuitive.
I believe that we should have that API available in Javascript too:

users_path() // => “/users”
user_path(1) // => “/users/1”
user_path(1, {format: ‘json’}) // => “/users/1.json”
user_path(1, {anchor: ‘profile’}) // => “/users/1#profile”
new_user_project_path(1, {format: ‘json’}) // => “/users/1/projects/new.json”
user_project_path(1,2, {q: ‘hello’, custom: true}) // => “/users/1/projects/2?q=hello&custom=true”
user_project_path(1,2, {hello: [‘world’, ‘mars’]}) // => “/users/1/projects/2?hello%5B%5D=world&hello%5B%5D=mars”

``

Most Rails projects I know hardcode routes in Javascript, some pass those routes from HTML as data attributes.

Like:

jQuery.get("/posts/" + post.id + “/comments/” + comment.id + “.json”, function(){ …});
// slightly better
jQuery.get($(this).data(“url”), function(){ …});

``

But I believe that extensive use of JS should require URL helpers.

Here is the “prototype” 8 years old project I maintain: https://github.com/railsware/js-routes

But I believe 90% of Rails projects need that out of the box now.

What do you think about adding the functionality to the Rails core?

I’ve generally got around this issue by including helper generated urls in data-* attributes or in json generated on the server, but perhaps there’s situations where those solutions don’t work.

We use data-url attributes alongside Stimulus at Basecamp. I don’t see that a JS router is something we’d ship by default. But great to have that as a gem :+1:

I feel that exposing all routes through JS would be a huge security issue.

Using data URL attributes would be fine - exposing only routes available to the current user.

I use data-* attributes as well or pass the urls back to the client via json generated on the server.