Brings Rails named routes to javascript
See the code
Generates javascript file that defines all Rails named routes as javascript functions:
Rails.application.routes.draw do
root "home#index"
namespace :api do
resources :users
end
end
import { root_path, api_user_path } from './routes';
root_path() # => /
api_user_path(25, include_profile: true, format: 'json') // => /api/users/25.json?include_profile=true
Your Rails Gemfile:
gem "js-routes"
There are several possible ways to setup JsRoutes:
Setup Rack Middleware
to automatically generate and maintain routes.js file and corresponding
Typescript definitions routes.d.ts:
Run a command:
rails generate js_routes:middleware
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"
# For setups without jsbundling-rails
task "assets:precompile" => "js:routes"
Add js-routes files to .gitignore:
/app/javascript/routes.js
/app/javascript/routes.d.ts
IMPORTANT: the setup doesn't support IDE autocompletion with Typescript
Run a command:
./bin/rails generate js_routes:webpacker
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 = {
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));
In case you need multiple route files for different parts of your application, there are low level methods:
# Returns a routes file as a string
JsRoutes.generate(options)
# Writes routes to specific file location
JsRoutes.generate!(file_name, options)
# Writes Typescript definitions file for routes
JsRoutes.definitions!(file_name, options)
They can also be used in ERB context
<script>
var AdminRoutes = <%= JsRoutes.generate(
include: /admin/, module_type: nil, namespace: nil
) %>;
</script>
Routes can be returns via API:
class Api::RoutesController < Api::BaseController
def index
options = {
include: /\Aapi_/,
default_url_options: { format: 'json' },
}
render json: {
routes: {
source: JsRoutes.generate(options),
definitions: JsRoutes.definitions(options),
}
}
end
end
Default auto-update middleware for development doesn't support configuration out of the box, but it can be extended through inheritence:
class AdvancedJsRoutesMiddleware < JsRoutes::Middleware
def regenerate
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"}
)
end
end
JsRoutes has typescript support out of the box.
Restrictions:
module_type is set to ESM (strongly recommended and default)..erb extensions.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.
Some setups may benefit from splitting routes into multiple files with the core js-routes utils shared between these files. This can be helpful for codebases that have a large number of routes and can improve tree shaking. This is only available when the module_type is set to ESM.
class AdvancedJsRoutesMiddleware < JsRoutes::Middleware
def regenerate
JsRoutes.package!
JsRoutes.generate!(
"admin_routes.js",
include: /^admin_/,
package: './router.js'
)
JsRoutes.generate!(
"api_routes.js",
include: /^api_/,
package: './router.js'
)
end
end
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.
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
Options to configure JavaScript file generator. These options are only available in Ruby context but not JavaScript.
module_type - JavaScript module type for generated code. Article
ESM, UMD, CJS, AMD, DTS, nil.ESMnil option can be used in case you don't want generated code to export anything.documentation - specifies if each route should be annotated with JSDoc comment
trueexclude - Array of regexps to exclude from routes.
[]_path suffix, eg: you want to match exactly settings_path, the regexp should be /^settings$/include - Array of regexps to include in routes.
[]_path suffix, eg: you want to match exactly settings_path, the regexp should be /^settings$/namespace - global object used to access routes.
module_type option is set to nil.MyProject.routesnilcamel_case - specifies if route helpers should be generated in camel case instead of underscore case.
falseurl_links - specifies if *_url helpers should be generated (in addition to the default *_path helpers).
falsedefault_url_options config. If no default option has been set, then the URL will fallback to the current URL based on window.location.compact - Remove _path suffix in path routes(*_url routes stay untouched if they were enabled)
falseusers() // => /usersapplication - a key to specify which rails engine you want to generate routes too.
lambda. This will reduce the reliance on order during initialization your application.-> { Rails.application }file - a file location where generated routes are stored
app/javascript/routes.js if setup with Webpacker, otherwise app/assets/javascripts/routes.js if setup with Sprockets.package - specify where the shared package will be imported from. e.g. './router.js'.
package!.niloptional_definition_params - make all route paramters in definition optional
falsebanner - specify a JSDoc comment on top of the file.
Proc./**
* File generated by js-routes 2.3.1 on 2024-12-04 09:45:59 +0100
* Based on Rails 7.2.0 routes of App
*/
Options to configure routes formatting. These options are available both in Ruby and JavaScript context.
default_url_options - default parameters used when generating URLs
{format: "json", trailing_slash: true, protocol: "https", subdomain: "api", host: "example.com", port: 3000}url_for doc for list of supported options{}serializer - a JS function that serializes a Javascript Hash object into URL paramters like {a: 1, b: 2} => "a=1&b=2".
nil. Uses built-in serializer compatible with RailsjQuery.param - use jQuery's serializer algorithm. You can attach serialize function from your favorite AJAX framework.function (object) { ... } - use completely custom serializer of your application.include_undefined_query_parameters - when using the built-in serializer, include query object properties whose value is undefined as Rails nil instead of omitting them.
nil. Preserves legacy serialization and emits a warning until this option is set explicitly.false.false to omit undefined query object properties.null still serializes as Rails nil, including the Rails 8.1 bare-key behavior.serializer functions remain responsible for their own undefined handling.special_options_key - a special key that helps JsRoutes to destinguish serialized model from options hash
_optionsConfiguration 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
} 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)
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']
JsRoutes tries to replicate the Rails routing API as closely as possible. There are only 2 known issues with compatibility that happen very rarely and have their workarounds.
If you find any incompatibilities outside of ones below, please open an 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"
Use special_options_key to configure the _options parameter name.
Rails is very flexible on how route parameters can be specified. All of the following calls will make the same result:
# Given route
# /inboxes/:inbox_id/messages/:message_id/attachments/:id
# every call below returns:
# => "/inboxes/1/messages/2/attachments/3"
inbox_message_attachment_path(1, 2, 3)
inbox_message_attachment_path(1, 2, id: 3)
inbox_message_attachment_path(1, message_id: 2, id: 3)
inbox_message_attachment_path(inbox_id: 1, message_id: 2, id: 3)
# including these mad versions
inbox_message_attachment_path(2, inbox_id: 1, id: 3)
inbox_message_attachment_path(1, 3, message_id: 2)
inbox_message_attachment_path(3, inbox_id: 1, message_id: 2)
While all of these methods are supported by JsRoutes, it is impossible to support them in DTS type definitions.
If you are using routes like this, use the following configuration that will prevent required parameters presence to be validated by definition:
JsRoutes.setup do |c|
c.optional_definition_params = true
end
This will enforce the following route signature:
export const inbox_message_attachment_path: ((
inbox_id?: RequiredRouteParameter,
message_id?: RequiredRouteParameter,
id?: RequiredRouteParameter,
options?: RouteOptions
) => string) & RouteHelperExtras;
That will make every call above valid.
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:
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
Split your routes into multiple files related to each section of your website like:
JsRoutes.generate!('app/javascript/admin-routes.js', include: /^admin_/) %>
JsRoutes.generate!('app/javascript/app-routes.js', exclude: /^admin_/) %>
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:
#to_param convention for seo optimized pathsOverall
Maintained
Code review
RubyGems
Latest release
Releases this year
207 followers · starred Apr 2014
966 followers · starred Oct 2025
58 followers · starred Jul 2025
213 followers · starred Jul 2024
Brings Rails named routes to javascript
See the code
Generates javascript file that defines all Rails named routes as javascript functions:
Rails.application.routes.draw do
root "home#index"
namespace :api do
resources :users
end
end
import { root_path, api_user_path } from './routes';
root_path() # => /
api_user_path(25, include_profile: true, format: 'json') // => /api/users/25.json?include_profile=true
Your Rails Gemfile:
gem "js-routes"
There are several possible ways to setup JsRoutes:
Setup Rack Middleware
to automatically generate and maintain routes.js file and corresponding
Typescript definitions routes.d.ts:
Run a command:
rails generate js_routes:middleware
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"
# For setups without jsbundling-rails
task "assets:precompile" => "js:routes"
Add js-routes files to .gitignore:
/app/javascript/routes.js
/app/javascript/routes.d.ts
IMPORTANT: the setup doesn't support IDE autocompletion with Typescript
Run a command:
./bin/rails generate js_routes:webpacker
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 = {
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));
In case you need multiple route files for different parts of your application, there are low level methods:
# Returns a routes file as a string
JsRoutes.generate(options)
# Writes routes to specific file location
JsRoutes.generate!(file_name, options)
# Writes Typescript definitions file for routes
JsRoutes.definitions!(file_name, options)
They can also be used in ERB context
<script>
var AdminRoutes = <%= JsRoutes.generate(
include: /admin/, module_type: nil, namespace: nil
) %>;
</script>
Routes can be returns via API:
class Api::RoutesController < Api::BaseController
def index
options = {
include: /\Aapi_/,
default_url_options: { format: 'json' },
}
render json: {
routes: {
source: JsRoutes.generate(options),
definitions: JsRoutes.definitions(options),
}
}
end
end
Default auto-update middleware for development doesn't support configuration out of the box, but it can be extended through inheritence:
class AdvancedJsRoutesMiddleware < JsRoutes::Middleware
def regenerate
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"}
)
end
end
JsRoutes has typescript support out of the box.
Restrictions:
module_type is set to ESM (strongly recommended and default)..erb extensions.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.
Some setups may benefit from splitting routes into multiple files with the core js-routes utils shared between these files. This can be helpful for codebases that have a large number of routes and can improve tree shaking. This is only available when the module_type is set to ESM.
class AdvancedJsRoutesMiddleware < JsRoutes::Middleware
def regenerate
JsRoutes.package!
JsRoutes.generate!(
"admin_routes.js",
include: /^admin_/,
package: './router.js'
)
JsRoutes.generate!(
"api_routes.js",
include: /^api_/,
package: './router.js'
)
end
end
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.
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
Options to configure JavaScript file generator. These options are only available in Ruby context but not JavaScript.
module_type - JavaScript module type for generated code. Article
ESM, UMD, CJS, AMD, DTS, nil.ESMnil option can be used in case you don't want generated code to export anything.documentation - specifies if each route should be annotated with JSDoc comment
trueexclude - Array of regexps to exclude from routes.
[]_path suffix, eg: you want to match exactly settings_path, the regexp should be /^settings$/include - Array of regexps to include in routes.
[]_path suffix, eg: you want to match exactly settings_path, the regexp should be /^settings$/namespace - global object used to access routes.
module_type option is set to nil.MyProject.routesnilcamel_case - specifies if route helpers should be generated in camel case instead of underscore case.
falseurl_links - specifies if *_url helpers should be generated (in addition to the default *_path helpers).
falsedefault_url_options config. If no default option has been set, then the URL will fallback to the current URL based on window.location.compact - Remove _path suffix in path routes(*_url routes stay untouched if they were enabled)
falseusers() // => /usersapplication - a key to specify which rails engine you want to generate routes too.
lambda. This will reduce the reliance on order during initialization your application.-> { Rails.application }file - a file location where generated routes are stored
app/javascript/routes.js if setup with Webpacker, otherwise app/assets/javascripts/routes.js if setup with Sprockets.package - specify where the shared package will be imported from. e.g. './router.js'.
package!.niloptional_definition_params - make all route paramters in definition optional
falsebanner - specify a JSDoc comment on top of the file.
Proc./**
* File generated by js-routes 2.3.1 on 2024-12-04 09:45:59 +0100
* Based on Rails 7.2.0 routes of App
*/
Options to configure routes formatting. These options are available both in Ruby and JavaScript context.
default_url_options - default parameters used when generating URLs
{format: "json", trailing_slash: true, protocol: "https", subdomain: "api", host: "example.com", port: 3000}url_for doc for list of supported options{}serializer - a JS function that serializes a Javascript Hash object into URL paramters like {a: 1, b: 2} => "a=1&b=2".
nil. Uses built-in serializer compatible with RailsjQuery.param - use jQuery's serializer algorithm. You can attach serialize function from your favorite AJAX framework.function (object) { ... } - use completely custom serializer of your application.include_undefined_query_parameters - when using the built-in serializer, include query object properties whose value is undefined as Rails nil instead of omitting them.
nil. Preserves legacy serialization and emits a warning until this option is set explicitly.false.false to omit undefined query object properties.null still serializes as Rails nil, including the Rails 8.1 bare-key behavior.serializer functions remain responsible for their own undefined handling.special_options_key - a special key that helps JsRoutes to destinguish serialized model from options hash
_optionsConfiguration 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
} 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)
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']
JsRoutes tries to replicate the Rails routing API as closely as possible. There are only 2 known issues with compatibility that happen very rarely and have their workarounds.
If you find any incompatibilities outside of ones below, please open an 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"
Use special_options_key to configure the _options parameter name.
Rails is very flexible on how route parameters can be specified. All of the following calls will make the same result:
# Given route
# /inboxes/:inbox_id/messages/:message_id/attachments/:id
# every call below returns:
# => "/inboxes/1/messages/2/attachments/3"
inbox_message_attachment_path(1, 2, 3)
inbox_message_attachment_path(1, 2, id: 3)
inbox_message_attachment_path(1, message_id: 2, id: 3)
inbox_message_attachment_path(inbox_id: 1, message_id: 2, id: 3)
# including these mad versions
inbox_message_attachment_path(2, inbox_id: 1, id: 3)
inbox_message_attachment_path(1, 3, message_id: 2)
inbox_message_attachment_path(3, inbox_id: 1, message_id: 2)
While all of these methods are supported by JsRoutes, it is impossible to support them in DTS type definitions.
If you are using routes like this, use the following configuration that will prevent required parameters presence to be validated by definition:
JsRoutes.setup do |c|
c.optional_definition_params = true
end
This will enforce the following route signature:
export const inbox_message_attachment_path: ((
inbox_id?: RequiredRouteParameter,
message_id?: RequiredRouteParameter,
id?: RequiredRouteParameter,
options?: RouteOptions
) => string) & RouteHelperExtras;
That will make every call above valid.
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:
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
Split your routes into multiple files related to each section of your website like:
JsRoutes.generate!('app/javascript/admin-routes.js', include: /^admin_/) %>
JsRoutes.generate!('app/javascript/app-routes.js', exclude: /^admin_/) %>
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:
#to_param convention for seo optimized pathsOverall
Maintained
Code review
RubyGems
Latest release
Releases this year
207 followers · starred Apr 2014
966 followers · starred Oct 2025
58 followers · starred Jul 2025
213 followers · starred Jul 2024