Top Related Projects
Ruby on Rails
Parse and render REST API documents using representers.
A Rails engine that helps you put together a super-flexible admin dashboard.
Ruby implementation of GraphQL
The web, with simplicity.
Use Turbo in your Ruby on Rails app
Quick Overview
js-routes is a Rails gem that generates JavaScript functions for Rails routes. It allows you to use your Rails routes in JavaScript, providing a seamless integration between your server-side and client-side routing.
Pros
- Eliminates the need to manually maintain JavaScript route helpers
- Keeps client-side routing in sync with server-side routes
- Supports all Rails routing features, including named routes and route constraints
- Improves code maintainability and reduces errors caused by mismatched routes
Cons
- Adds an extra step to the asset compilation process
- May increase the size of your JavaScript bundle
- Requires recompilation when routes change
- Limited customization options for generated JavaScript
Code Examples
- Basic route generation:
Routes.users_path() // => "/users"
Routes.user_path(1) // => "/users/1"
- Using with query parameters:
Routes.search_path({query: 'test', page: 2}) // => "/search?query=test&page=2"
- Handling optional parameters:
Routes.book_path(1, {format: 'pdf'}) // => "/books/1.pdf"
Routes.book_path(1) // => "/books/1"
Getting Started
- Add to your Gemfile:
gem 'js-routes'
-
Run
bundle install
-
Add to your application.js:
//= require js-routes
- In your Rails configuration (e.g.,
config/initializers/jsroutes.rb
):
JsRoutes.setup do |config|
config.exclude = [/^admin_/, /^api_/]
end
This setup excludes admin and API routes from being generated in JavaScript.
Competitor Comparisons
Ruby on Rails
Pros of Rails
- Comprehensive full-stack web application framework
- Large, active community with extensive documentation and resources
- Built-in testing tools and conventions for rapid development
Cons of Rails
- Steeper learning curve for beginners
- Can be overkill for smaller projects or simple applications
- Slower performance compared to some lightweight alternatives
Code Comparison
Rails (config/routes.rb):
Rails.application.routes.draw do
resources :users
get '/about', to: 'pages#about'
end
js-routes (app/javascript/routes.js):
import Routes from 'js-routes';
const userPath = Routes.user_path(1);
const aboutPath = Routes.about_path();
Summary
Rails is a full-featured web application framework, while js-routes is a specific tool for generating JavaScript routes from Rails routes. Rails offers a complete ecosystem for building web applications, but may be more complex for simple projects. js-routes provides a focused solution for using Rails routes in JavaScript, enhancing frontend development in Rails applications. The choice between them depends on project requirements and development preferences.
Parse and render REST API documents using representers.
Pros of Roar
- Provides a more comprehensive API representation solution, including hypermedia support
- Offers greater flexibility in defining and customizing representations
- Supports multiple formats (JSON, XML, etc.) out of the box
Cons of Roar
- Steeper learning curve due to its more complex architecture
- May require more setup and configuration for basic use cases
- Less focused on route generation, which is js-routes' primary function
Code Comparison
Roar example:
class SongRepresenter < Roar::Decorator
include Roar::JSON
property :title
property :artist
link :self do
song_url(represented)
end
end
js-routes example:
Routes.song_path(1) // => "/songs/1"
Routes.song_url(1) // => "http://example.com/songs/1"
Summary
Roar is a more comprehensive solution for API representations, offering greater flexibility and support for hypermedia. However, it comes with a steeper learning curve and may be overkill for simpler use cases. js-routes, on the other hand, focuses specifically on generating JavaScript functions for Rails routes, making it easier to use but less feature-rich for complex API scenarios. The choice between the two depends on the specific needs of your project and the level of API complexity you're dealing with.
A Rails engine that helps you put together a super-flexible admin dashboard.
Pros of Administrate
- Provides a full-featured admin dashboard interface out of the box
- Offers customizable views and forms for managing resources
- Integrates well with existing Rails applications and follows Rails conventions
Cons of Administrate
- Less flexible for generating custom JavaScript routes
- May introduce unnecessary overhead for projects that don't need a full admin panel
- Requires more setup and configuration compared to a simple route generation tool
Code Comparison
Administrate (dashboard configuration):
class UserDashboard < Administrate::BaseDashboard
ATTRIBUTE_TYPES = {
id: Field::Number,
name: Field::String,
email: Field::String,
created_at: Field::DateTime,
}
# ... more configuration
end
js-routes (route generation):
Routes.users_path() // => "/users"
Routes.user_path(1) // => "/users/1"
Routes.new_user_path() // => "/users/new"
Summary
Administrate is a comprehensive admin panel solution for Rails applications, offering a full set of features for managing resources. It's ideal for projects requiring a robust admin interface but may be overkill for simpler needs. js-routes, on the other hand, focuses solely on generating JavaScript routes, providing a lightweight and flexible solution for front-end route handling in Rails applications. The choice between the two depends on the specific requirements of your project and the level of admin functionality needed.
Ruby implementation of GraphQL
Pros of graphql-ruby
- Provides a flexible and powerful GraphQL implementation for Ruby applications
- Supports schema definition, query execution, and introspection
- Offers built-in tools for authorization, pagination, and error handling
Cons of graphql-ruby
- Steeper learning curve for developers new to GraphQL
- Requires more setup and configuration compared to traditional REST APIs
- May introduce additional complexity for simple CRUD operations
Code Comparison
graphql-ruby:
class QueryType < GraphQL::Schema::Object
field :user, UserType, null: true do
argument :id, ID, required: true
end
def user(id:)
User.find(id)
end
end
js-routes:
# config/routes.rb
Rails.application.routes.draw do
resources :users, only: [:show]
end
# In JavaScript
Routes.user_path(1) // => "/users/1"
Summary
graphql-ruby is a comprehensive GraphQL implementation for Ruby, offering flexibility and powerful features for building GraphQL APIs. It provides a robust solution for complex data requirements but may introduce additional complexity.
js-routes, on the other hand, focuses on generating JavaScript helpers for Rails routes, simplifying client-side route handling in JavaScript applications. It's more straightforward for traditional REST APIs but lacks the advanced querying capabilities of GraphQL.
Choose graphql-ruby for complex, data-intensive applications where flexible querying is crucial. Opt for js-routes in simpler Rails applications with straightforward routing needs and JavaScript integration.
The web, with simplicity.
Pros of Hanami
- Full-stack web framework with a modular architecture, offering more comprehensive features than js-routes
- Emphasizes clean architecture and separation of concerns, promoting maintainable code
- Provides a complete ecosystem for building web applications, including routing, persistence, and security
Cons of Hanami
- Steeper learning curve due to its comprehensive nature and unique architecture
- Less focused on JavaScript integration compared to js-routes
- May be overkill for smaller projects or those primarily needing route helpers
Code Comparison
Hanami routing example:
# config/routes.rb
root to: 'home#index'
resources :books, only: [:index, :show]
js-routes routing example:
// In JavaScript
Routes.root_path() // => "/"
Routes.books_path() // => "/books"
Routes.book_path(1) // => "/books/1"
While Hanami provides a full-stack solution with Ruby-based routing, js-routes focuses on exposing Rails routes to JavaScript, offering different approaches to handling application routing.
Use Turbo in your Ruby on Rails app
Pros of Turbo Rails
- Provides a full-stack solution for building modern web applications with Rails
- Offers seamless integration with Rails, including automatic form handling and page updates
- Supports real-time updates and partial page reloads without writing custom JavaScript
Cons of Turbo Rails
- Requires a specific application architecture and may not be suitable for all projects
- Has a steeper learning curve compared to simpler JavaScript routing solutions
- May introduce complexity for developers unfamiliar with Hotwire concepts
Code Comparison
Turbo Rails (view component):
<%= turbo_frame_tag "messages" do %>
<%= render @messages %>
<% end %>
js-routes (JavaScript usage):
Routes.user_path(1) // => "/users/1"
Routes.new_user_project_path(1) // => "/users/1/projects/new"
Routes.user_project_path(1,2,'json') // => "/users/1/projects/2.json"
Summary
Turbo Rails offers a comprehensive solution for building modern Rails applications with real-time updates and minimal JavaScript. It integrates deeply with Rails but requires adopting specific patterns. js-routes, on the other hand, provides a simpler approach to generating Rails routes in JavaScript, offering flexibility without imposing architectural constraints. The choice between them depends on project requirements and team preferences.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
JsRoutes
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:
- Quick and easy - Recommended
- Uses Rack Middleware to automatically update routes locally
- Automatically generates routes files on javascript build
- Works great for a simple Rails application
- Advanced Setup
- Allows very custom setups
- Automatic updates need to be customized
- Webpacker ERB Loader - Legacy
- Requires ESM module system (the default)
- Doesn't support typescript definitions
- Sprockets - Legacy
- Deprecated and not recommended for modern apps
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
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));
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"}
)
Typescript Definitions
JsRoutes has typescript support out of the box.
Restrictions:
- Only available if
module_type
is set toESM
(strongly recommended and default). - Webpacker Automatic Updates are not available because typescript compiler can not be configured to understand
.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.
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.
module_type
- JavaScript module type for generated code. Article- Options:
ESM
,UMD
,CJS
,AMD
,DTS
,nil
. - Default:
ESM
nil
option can be used in case you don't want generated code to export anything.
- Options:
documentation
- specifies if each route should be annotated with JSDoc comment- Default:
true
- Default:
exclude
- Array of regexps to exclude from routes.- Default:
[]
- The regexp applies only to the name before the
_path
suffix, eg: you want to match exactlysettings_path
, the regexp should be/^settings$/
- Default:
include
- Array of regexps to include in routes.- Default:
[]
- The regexp applies only to the name before the
_path
suffix, eg: you want to match exactlysettings_path
, the regexp should be/^settings$/
- Default:
namespace
- global object used to access routes.- Only available if
module_type
option is set tonil
. - Supports nested namespace like
MyProject.routes
- Default:
nil
- Only available if
camel_case
- specifies if route helpers should be generated in camel case instead of underscore case.- Default:
false
- Default:
url_links
- specifies if*_url
helpers should be generated (in addition to the default*_path
helpers).- Default:
false
- Note: generated URLs will first use the protocol, host, and port options specified in the route definition. Otherwise, the URL will be based on the option specified in the
default_url_options
config. If no default option has been set, then the URL will fallback to the current URL based onwindow.location
.
- Default:
compact
- Remove_path
suffix in path routes(*_url
routes stay untouched if they were enabled)- Default:
false
- Sample route call when option is set to true:
users() // => /users
- Default:
application
- a key to specify which rails engine you want to generate routes too.- This option allows to only generate routes for a specific rails engine, that is mounted into routes instead of all Rails app routes
- Default:
Rails.application
file
- a file location where generated routes are stored- Default:
app/javascript/routes.js
if setup with Webpacker, otherwiseapp/assets/javascripts/routes.js
if setup with Sprockets.
- Default:
Formatter Options
Options to configure routes formatting. These options are available both in Ruby and JavaScript context.
default_url_options
- default parameters used when generating URLs- Example:
{format: "json", trailing_slash: true, protocol: "https", subdomain: "api", host: "example.com", port: 3000}
- Default:
{}
- Example:
prefix
- string that will prepend any generated URL. Usually used when app URL root includes a path component.- Example:
/rails-app
- Default:
Rails.application.config.relative_url_root
- Example:
serializer
- a JS function that serializes a Javascript Hash object into URL paramters like{a: 1, b: 2} => "a=1&b=2"
.- Default:
nil
. Uses built-in serializer compatible with Rails - Example:
jQuery.param
- use jQuery's serializer algorithm. You can attach serialize function from your favorite AJAX framework. - Example:
function (object) { ... }
- use completely custom serializer of your application.
- Default:
special_options_key
- a special key that helps JsRoutes to destinguish serialized model from options hash- This option exists because JS doesn't provide a difference between an object and a hash
- Default:
_options
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:
- Rails 4,5,6 support
- ESM Tree shaking support
- Rich options set
- Full rails compatibility
- Support Rails
#to_param
convention for seo optimized paths - Well tested
Thanks to contributors
Have fun
License
Top Related Projects
Ruby on Rails
Parse and render REST API documents using representers.
A Rails engine that helps you put together a super-flexible admin dashboard.
Ruby implementation of GraphQL
The web, with simplicity.
Use Turbo in your Ruby on Rails app
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot