Home

Awesome

JsRoutes

CI

Generates javascript file that defines all Rails named routes as javascript helpers

Intallation

Your Rails Gemfile:

gem "js-routes"

Setup

There are several possible ways to setup JsRoutes:

<div id='quick-start'></div>

Quick Start

Setup Rack Middleware to automatically generate and maintain routes.js file and corresponding Typescript definitions routes.d.ts:

Use a Generator

Run a command:

rails generate js_routes:middleware

Setup Manually

Add the following to config/environments/development.rb:

  config.middleware.use(JsRoutes::Middleware)

Use it in any JS file:

import {post_path} from '../routes';

alert(post_path(1))

Upgrade js building process to update js-routes files in Rakefile:

task "javascript:build" => "js:routes:typescript"
# For setups without jsbundling-rails
task "assets:precompile" => "js:routes:typescript"

Add js-routes files to .gitignore:

/app/javascript/routes.js
/app/javascript/routes.d.ts
<div id='webpacker'></div>

Webpacker ERB loader

IMPORTANT: the setup doesn't support IDE autocompletion with Typescript

Use a Generator

Run a command:

./bin/rails generate js_routes:webpacker

Setup manually

The routes files can be automatically updated without rake task being called manually. It requires rails-erb-loader npm package to work.

Add erb loader to webpacker:

yarn add rails-erb-loader
rm -f app/javascript/routes.js # delete static file if any

Create webpack ERB config config/webpack/loaders/erb.js:

module.exports = {
  module: {
    rules: [
      {
        test: /\.erb$/,
        enforce: 'pre',
        loader: 'rails-erb-loader'
      },
    ]
  }
};

Enable erb extension in config/webpack/environment.js:

const erb = require('./loaders/erb')
environment.loaders.append('erb', erb)

Create routes file app/javascript/routes.js.erb:

<%= JsRoutes.generate() %>

Use routes wherever you need them:

import {post_path} from 'routes.js.erb';

alert(post_path(2));
<div id='advanced-setup'></div>

Advanced Setup

IMPORTANT: that this setup requires the JS routes file to be updates manually

Routes file can be generated with a rake task:

rake js:routes 
# OR for typescript support
rake js:routes:typescript

In case you need multiple route files for different parts of your application, you have to create the files manually. If your application has an admin and an application namespace for example:

IMPORTANT: Requires Webpacker ERB Loader setup.

// app/javascript/admin/routes.js.erb
<%= JsRoutes.generate(include: /admin/) %>
// app/javascript/customer/routes.js.erb
<%= JsRoutes.generate(exclude: /admin/) %>

You can manipulate the generated helper manually by injecting ruby into javascript:

export const routes = <%= JsRoutes.generate(module_type: nil, namespace: nil) %>

If you want to generate the routes files manually with custom options, you can use JsRoutes.generate!:

path = Rails.root.join("app/javascript")

JsRoutes.generate!(
  "#{path}/app_routes.js", exclude: [/^admin_/, /^api_/]
)
JsRoutes.generate!(
"#{path}/adm_routes.js", include: /^admin_/
)
JsRoutes.generate!(
  "#{path}/api_routes.js", include: /^api_/, default_url_options: {format: "json"}
)
<div id='definitions'></div>

Typescript Definitions

JsRoutes has typescript support out of the box.

Restrictions:

For the basic setup of typscript definitions see Quick Start setup. More advanced setup would involve calling manually:

JsRoutes.definitions! # to output to file
# or 
JsRoutes.definitions # to output to string

Even more advanced setups can be achieved by setting module_type to DTS inside configuration which will cause any JsRoutes instance to generate defintions instead of routes themselves.

<div id="sprockets"></div>

Sprockets (Deprecated)

If you are using Sprockets you may configure js-routes in the following way.

Setup the initializer (e.g. config/initializers/js_routes.rb):

JsRoutes.setup do |config|
  config.module_type = nil
  config.namespace = 'Routes'
end

Require JsRoutes in app/assets/javascripts/application.js or other bundle

//= require js-routes

Also in order to flush asset pipeline cache sometimes you might need to run:

rake tmp:cache:clear

This cache is not flushed on server restart in development environment.

Important: If routes.js file is not updated after some configuration change you need to run this rake task again.

Configuration

You can configure JsRoutes in two main ways. Either with an initializer (e.g. config/initializers/js_routes.rb):

JsRoutes.setup do |config|
  config.option = value
end

Or dynamically in JavaScript, although only Formatter Options are supported:

import {configure, config} from 'routes'

configure({
  option: value
});
config(); // current config

Available Options

Generator Options

Options to configure JavaScript file generator. These options are only available in Ruby context but not JavaScript.

<div id='module-type'></div> <div id="formatter-options"></div>

Formatter Options

Options to configure routes formatting. These options are available both in Ruby and JavaScript context.

Usage

Configuration above will create a nice javascript file with Routes object that has all the rails routes available:

import {
  user_path, user_project_path, company_path
} as Routes from 'routes';

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"

var google = {id: 1, name: "Google"};
company_path(google) 
  // => "/companies/1"

var google = {id: 1, name: "Google", to_param: "google"};
company_path(google) 
  // => "/companies/google"

In order to make routes helpers available globally:

import * as Routes from '../routes';
jQuery.extend(window, Routes)

Get spec of routes and required params

Possible to get spec of route by function toString:

import {user_path, users_path}  from '../routes'

users_path.toString() // => "/users(.:format)"
user_path.toString() // => "/users/:id(.:format)"

Route function also contain method requiredParams inside which returns required param names array:

users_path.requiredParams() // => []
user_path.requiredParams() // => ['id']

Rails Compatibility

JsRoutes tries to replicate the Rails routing API as closely as possible. If you find any incompatibilities (outside of what is described below), please open an issue.

Object and Hash distinction issue

Sometimes the destinction between JS Hash and Object can not be found by JsRoutes. In this case you would need to pass a special key to help:

import {company_project_path} from '../routes'

company_project_path({company_id: 1, id: 2}) // => Not enough parameters
company_project_path({company_id: 1, id: 2, _options: true}) // => "/companies/1/projects/2"

What about security?

JsRoutes itself does not have security holes. It makes URLs without access protection more reachable by potential attacker. If that is an issue for you, you may use one of the following solutions:

ESM Tree shaking

Make sure module_type is set to ESM (the default). Modern JS bundlers like Webpack can statically determine which ESM exports are used, and remove the unused exports to reduce bundle size. This is known as Tree Shaking.

JS files can use named imports to import only required routes into the file, like:

import {
  inbox_path,
  inboxes_path,
  inbox_message_path,
  inbox_attachment_path,
  user_path,
} from '../routes'

JS files can also use star imports (import * as) for tree shaking, as long as only explicit property accesses are used.

import * as routes from '../routes';

console.log(routes.inbox_path); // OK, only `inbox_path` is included in the bundle

console.log(Object.keys(routes)); // forces bundler to include all exports, breaking tree shaking

Exclude option

Split your routes into multiple files related to each section of your website like:

// admin-routes.js.erb
<%= JsRoutes.generate(include: /^admin_/) %>
// app-routes.js.erb
<%= JsRoutes.generate(exclude: /^admin_/) %>

Advantages over alternatives

There are some alternatives available. Most of them has only basic feature and don't reach the level of quality I accept. Advantages of this one are:

Thanks to contributors

Have fun

License

FOSSA Status