{"id":13747503,"url":"https://github.com/railsware/js-routes","last_synced_at":"2025-05-11T14:02:42.012Z","repository":{"id":1597946,"uuid":"2149005","full_name":"railsware/js-routes","owner":"railsware","description":"Brings Rails named routes to javascript","archived":false,"fork":false,"pushed_at":"2025-03-03T09:23:40.000Z","size":2212,"stargazers_count":1634,"open_issues_count":1,"forks_count":152,"subscribers_count":41,"default_branch":"main","last_synced_at":"2025-05-11T14:01:46.272Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"http://railsware.github.io/js-routes/","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":"luismreis/WebSaver","license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/railsware.png","metadata":{"files":{"readme":"Readme.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2011-08-03T14:53:48.000Z","updated_at":"2025-05-09T22:15:15.000Z","dependencies_parsed_at":"2024-11-15T19:29:22.592Z","dependency_job_id":"430c35d4-890c-4af7-85c7-0d2e94cffd3e","html_url":"https://github.com/railsware/js-routes","commit_stats":{"total_commits":756,"total_committers":76,"mean_commits":9.947368421052632,"dds":"0.32539682539682535","last_synced_commit":"9bedb7f20a0d125189f8bcd9883d7c21314b47e3"},"previous_names":[],"tags_count":95,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/railsware%2Fjs-routes","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/railsware%2Fjs-routes/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/railsware%2Fjs-routes/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/railsware%2Fjs-routes/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/railsware","download_url":"https://codeload.github.com/railsware/js-routes/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253576264,"owners_count":21930169,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-03T06:01:31.575Z","updated_at":"2025-05-11T14:02:41.961Z","avatar_url":"https://github.com/railsware.png","language":"Ruby","funding_links":[],"categories":["Ruby","Gems"],"sub_categories":["Articles"],"readme":"# JsRoutes\n\n[![CI](https://github.com/railsware/js-routes/actions/workflows/ci.yml/badge.svg)](https://github.com/railsware/js-routes/actions/workflows/ci.yml)\n\n\u003cimg src=\"/logo.webp\" alt=\"Logo\" width=\"200\" height=\"200\"\u003e\n\nGenerates javascript file that defines all Rails named routes as javascript helpers:\n\n``` js\nimport { root_path, api_user_path } from './routes';\n\nroot_path() # =\u003e /\napi_user_path(25, include_profile: true, format: 'json') // =\u003e /api/users/25.json?include_profile=true\n```\n\n[More Examples](#usage)\n\n## Intallation\n\nYour Rails Gemfile:\n\n``` ruby\ngem \"js-routes\"\n```\n\n## Setup\n\nThere are several possible ways to setup JsRoutes:\n\n1. [Quick and easy](#quick-start) - Recommended\n  * Uses Rack Middleware to automatically update routes locally\n  * Automatically generates routes files on javascript build\n  * Works great for a simple Rails application\n2. [Advanced Setup](#advanced-setup)\n  * Allows very custom setups\n  * Automatic updates need to be customized\n3. [Webpacker ERB Loader](#webpacker) - Legacy\n  * Requires ESM module system (the default)\n  * Doesn't support typescript definitions\n4. [Sprockets](#sprockets) - Legacy\n  * Deprecated and not recommended for modern apps\n\n\u003cdiv id=\"quick-start\"\u003e\u003c/div\u003e\n\n### Quick Start\n\nSetup [Rack Middleware](https://guides.rubyonrails.org/rails_on_rack.html#action-dispatcher-middleware-stack)\nto automatically generate and maintain `routes.js` file and corresponding\n[Typescript definitions](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/module-d-ts.html) `routes.d.ts`:\n\n#### Use a Generator\n\nRun a command:\n\n``` sh\nrails generate js_routes:middleware\n```\n\n#### Setup Manually\n\nAdd the following to `config/environments/development.rb`:\n\n``` ruby\n  config.middleware.use(JsRoutes::Middleware)\n```\n\nUse it in any JS file:\n\n``` javascript\nimport {post_path} from '../routes';\n\nalert(post_path(1))\n```\n\nUpgrade js building process to update js-routes files in `Rakefile`:\n\n``` ruby\ntask \"javascript:build\" =\u003e \"js:routes\"\n# For setups without jsbundling-rails\ntask \"assets:precompile\" =\u003e \"js:routes\"\n```\n\nAdd js-routes files to `.gitignore`:\n\n```\n/app/javascript/routes.js\n/app/javascript/routes.d.ts\n```\n\n\u003cdiv id=\"webpack\"\u003e\u003c/div\u003e\n\n### Webpacker ERB loader\n\n**IMPORTANT**: the setup doesn't support IDE autocompletion with [Typescript](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/module-d-ts.html)\n\n#### Use a Generator\n\nRun a command:\n\n``` sh\n./bin/rails generate js_routes:webpacker\n```\n\n#### Setup manually\n\nThe routes files can be automatically updated  without `rake` task being called manually.\nIt requires [rails-erb-loader](https://github.com/usabilityhub/rails-erb-loader) npm package to work.\n\nAdd `erb` loader to webpacker:\n\n``` sh\nyarn add rails-erb-loader\nrm -f app/javascript/routes.js # delete static file if any\n```\n\nCreate webpack ERB config `config/webpack/loaders/erb.js`:\n\n``` javascript\nmodule.exports = {\n  module: {\n    rules: [\n      {\n        test: /\\.erb$/,\n        enforce: 'pre',\n        loader: 'rails-erb-loader'\n      },\n    ]\n  }\n};\n```\n\nEnable `erb` extension in `config/webpack/environment.js`:\n\n``` javascript\nconst erb = require('./loaders/erb')\nenvironment.loaders.append('erb', erb)\n```\n\nCreate routes file `app/javascript/routes.js.erb`:\n\n``` erb\n\u003c%= JsRoutes.generate() %\u003e\n```\n\nUse routes wherever you need them:\n\n``` javascript\nimport {post_path} from 'routes.js.erb';\n\nalert(post_path(2));\n```\n\n\u003cdiv id=\"advanced-setup\"\u003e\u003c/div\u003e\n\n### Advanced Setup\n\nIn case you need multiple route files for different parts of your application, there are low level methods:\n\n``` ruby\n# Returns a routes file as a string\nJsRoutes.generate(options)\n# Writes routes to specific file location\nJsRoutes.generate!(file_name, options)\n# Writes Typescript definitions file for routes\nJsRoutes.definitions!(file_name, options)\n```\n\nThey can also be used in ERB context\n\n``` erb\n\u003cscript\u003e\n    var AdminRoutes = \u003c%= JsRoutes.generate(\n      include: /admin/, module_type: nil, namespace: nil\n    ) %\u003e;\n\u003c/script\u003e\n```\n\nRoutes can be returns via API:\n\n``` ruby\nclass Api::RoutesController \u003c Api::BaseController\n  def index\n    options = {\n      include: /\\Aapi_/,\n      default_url_options: { format: 'json' },\n    }\n    render json: {\n      routes: {\n        source: JsRoutes.generate(options),\n        definitions: JsRoutes.definitions(options),\n      }\n    }\n  end\nend\n\n```\n\nDefault auto-update middleware for development\ndoesn't support configuration out of the box,\nbut it can be extended through inheritence:\n\n``` ruby\nclass AdvancedJsRoutesMiddleware \u003c JsRoutes::Middleware\n  def regenerate\n    path = Rails.root.join(\"app/javascript\")\n\n    JsRoutes.generate!(\n      \"#{path}/app_routes.js\", exclude: [/^admin_/, /^api_/]\n    )\n    JsRoutes.generate!(\n    \"#{path}/adm_routes.js\", include: /^admin_/\n    )\n    JsRoutes.generate!(\n      \"#{path}/api_routes.js\", include: /^api_/, default_url_options: {format: \"json\"}\n    )\n  end\nend\n```\n\n\u003cdiv id=\"definitions\"\u003e\u003c/div\u003e\n\n#### Typescript Definitions\n\nJsRoutes has typescript support out of the box.\n\nRestrictions:\n\n* Only available if `module_type` is set to `ESM` (strongly recommended and default).\n* Webpacker Automatic Updates are not available because typescript compiler can not be configured to understand `.erb` extensions.\n\nFor the basic setup of typscript definitions  see [Quick Start](#quick-start) setup.\nMore advanced setup would involve calling manually:\n\n``` ruby\nJsRoutes.definitions! # to output to file\n# or\nJsRoutes.definitions # to output to string\n```\n\nEven more advanced setups can be achieved by setting `module_type` to `DTS` inside [configuration](#module_type)\nwhich will cause any `JsRoutes` instance to generate defintions instead of routes themselves.\n\n\u003cdiv id=\"sprockets\"\u003e\u003c/div\u003e\n\n### Sprockets (Deprecated)\n\nIf you are using [Sprockets](https://github.com/rails/sprockets-rails) you may configure js-routes in the following way.\n\nSetup the initializer (e.g. `config/initializers/js_routes.rb`):\n\n``` ruby\nJsRoutes.setup do |config|\n  config.module_type = nil\n  config.namespace = 'Routes'\nend\n```\n\nRequire JsRoutes in `app/assets/javascripts/application.js` or other bundle\n\n``` js\n//= require js-routes\n```\n\nAlso in order to flush asset pipeline cache sometimes you might need to run:\n\n``` sh\nrake tmp:cache:clear\n```\n\nThis cache is not flushed on server restart in development environment.\n\n**Important:** If routes.js file is not updated after some configuration change you need to run this rake task again.\n\n## Configuration\n\nYou can configure JsRoutes in two main ways. Either with an initializer (e.g. `config/initializers/js_routes.rb`):\n\n``` ruby\nJsRoutes.setup do |config|\n  config.option = value\nend\n```\n\nOr dynamically in JavaScript, although only [Formatter Options](#formatter-options) are supported:\n\n``` js\nimport {configure, config} from 'routes'\n\nconfigure({\n  option: value\n});\nconfig(); // current config\n```\n\n### Available Options\n\n#### Generator Options\n\nOptions to configure JavaScript file generator. These options are only available in Ruby context but not JavaScript.\n\n\u003cdiv id='module-type'\u003e\u003c/div\u003e\n\n* `module_type` - JavaScript module type for generated code. [Article](https://dev.to/iggredible/what-the-heck-are-cjs-amd-umd-and-esm-ikm)\n  * Options: `ESM`, `UMD`, `CJS`, `AMD`, `DTS`, `nil`.\n  * Default: `ESM`\n  * `nil` option can be used in case you don't want generated code to export anything.\n* `documentation` - specifies if each route should be annotated with [JSDoc](https://jsdoc.app/) comment\n  * Default: `true`\n* `exclude` - Array of regexps to exclude from routes.\n  * Default: `[]`\n  * The regexp applies only to the name before the `_path` suffix, eg: you want to match exactly `settings_path`, the regexp should be `/^settings$/`\n* `include` - Array of regexps to include in routes.\n  * Default: `[]`\n  * The regexp applies only to the name before the `_path` suffix, eg: you want to match exactly `settings_path`, the regexp should be `/^settings$/`\n* `namespace` - global object used to access routes.\n  * Only available if `module_type` option is set to `nil`.\n  * Supports nested namespace like `MyProject.routes`\n  * Default: `nil`\n* `camel_case` - specifies if route helpers should be generated in camel case instead of underscore case.\n  * Default: `false`\n* `url_links` - specifies if `*_url` helpers should be generated (in addition to the default `*_path` helpers).\n  * Default: `false`\n  * 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 on `window.location`.\n* `compact` - Remove `_path` suffix in path routes(`*_url` routes stay untouched if they were enabled)\n  * Default: `false`\n  * Sample route call when option is set to true: `users() // =\u003e /users`\n* `application` - a key to specify which rails engine you want to generate routes too.\n  * This option allows to only generate routes for a specific rails engine, that is mounted into routes instead of all Rails app routes\n  * It is recommended to wrap the value with `lambda`. This will reduce the reliance on order during initialization your application.\n  * Default: `-\u003e { Rails.application }`\n* `file` - a file location where generated routes are stored\n  * Default: `app/javascript/routes.js` if setup with Webpacker, otherwise `app/assets/javascripts/routes.js` if setup with Sprockets.\n* `optional_definition_params` - make all route paramters in definition optional\n  * See [related compatibility issue](#optional-definition-params)\n  * Default: `false`\n* `banner` - specify a JSDoc comment on top of the file.\n  * It is not stripped by minifiers by default and helps to originate the content when debugging the build.\n  * You may want to control how much information from backend is exposed to potential attacker at the cost of your own comfort.\n  * See [JSDoc Guide](https://github.com/shri/JSDoc-Style-Guide/blob/master/README.md#files)\n  * Supports a lazy generation with `Proc`.\n  * Default: A string that generates the following:\n\n```\n/**\n * File generated by js-routes 2.3.1 on 2024-12-04 09:45:59 +0100\n * Based on Rails 7.2.0 routes of App\n */\n```\n\n\u003cdiv id=\"formatter-options\"\u003e\u003c/div\u003e\n\n#### Formatter Options\n\nOptions to configure routes formatting. These options are available both in Ruby and JavaScript context.\n\n* `default_url_options` - default parameters used when generating URLs\n  * Example: `{format: \"json\", trailing_slash: true, protocol: \"https\", subdomain: \"api\", host: \"example.com\", port: 3000}`\n  * See [`url_for` doc](https://api.rubyonrails.org/classes/ActionDispatch/Routing/UrlFor.html#method-i-url_for) for list of supported options\n  * Default: `{}`\n* `serializer` - a JS function that serializes a Javascript Hash object into URL paramters like `{a: 1, b: 2} =\u003e \"a=1\u0026b=2\"`.\n  * Default: `nil`. Uses built-in serializer compatible with Rails\n  * Example: `jQuery.param` - use jQuery's serializer algorithm. You can attach serialize function from your favorite AJAX framework.\n  * Example: `function (object) { ... }` - use completely custom serializer of your application.\n* `special_options_key` - a special key that helps JsRoutes to destinguish serialized model from options hash\n  * This option exists because JS doesn't provide a difference between an object and a hash\n  * Default: `_options`\n\n\n## Usage\n\nConfiguration above will create a nice javascript file with `Routes` object that has all the rails routes available:\n\n``` js\nimport {\n  user_path, user_project_path, company_path\n} from 'routes';\n\nusers_path()\n  // =\u003e \"/users\"\n\nuser_path(1)\n  // =\u003e \"/users/1\"\n\nuser_path(1, {format: 'json'})\n  // =\u003e \"/users/1.json\"\n\nuser_path(1, {anchor: 'profile'})\n  // =\u003e \"/users/1#profile\"\n\nnew_user_project_path(1, {format: 'json'})\n  // =\u003e \"/users/1/projects/new.json\"\n\nuser_project_path(1,2, {q: 'hello', custom: true})\n  // =\u003e \"/users/1/projects/2?q=hello\u0026custom=true\"\n\nuser_project_path(1,2, {hello: ['world', 'mars']})\n  // =\u003e \"/users/1/projects/2?hello%5B%5D=world\u0026hello%5B%5D=mars\"\n\nvar google = {id: 1, name: \"Google\"};\ncompany_path(google)\n  // =\u003e \"/companies/1\"\n\nvar google = {id: 1, name: \"Google\", to_param: \"google\"};\ncompany_path(google)\n  // =\u003e \"/companies/google\"\n```\n\nIn order to make routes helpers available globally:\n\n``` js\nimport * as Routes from '../routes';\njQuery.extend(window, Routes)\n```\n\n### Get spec of routes and required params\n\nPossible to get `spec` of route by function `toString`:\n\n```js\nimport {user_path, users_path}  from '../routes'\n\nusers_path.toString() // =\u003e \"/users(.:format)\"\nuser_path.toString() // =\u003e \"/users/:id(.:format)\"\n```\n\n\nRoute function also contain method `requiredParams` inside which returns required param names array:\n\n```js\nusers_path.requiredParams() // =\u003e []\nuser_path.requiredParams() // =\u003e ['id']\n```\n\n\n## Rails Compatibility\n\nJsRoutes tries to replicate the Rails routing API as closely as possible. \nThere are only 2 known issues with compatibility that happen very rarely and have their workarounds.\n\nIf you find any incompatibilities outside of ones below, please [open an issue](https://github.com/railsware/js-routes/issues/new).\n\n### Object and Hash distinction issue\n\nSometimes the destinction between JS Hash and Object can not be found by JsRoutes.\nIn this case you would need to pass a special key to help:\n\n``` js\nimport {company_project_path} from '../routes'\n\ncompany_project_path({company_id: 1, id: 2})\n    // =\u003e Not enough parameters\ncompany_project_path({company_id: 1, id: 2, _options: true})\n    // =\u003e \"/companies/1/projects/2\"\n```\n\nUse `special_options_key` to configure the `_options` parameter name.\n\n\u003cdiv id=\"optional-definition-params\"\u003e\u003c/div\u003e\n\n### Rails required parameters specified as optional\n\nRails is very flexible on how route parameters can be specified.\nAll of the following calls will make the same result:\n\n``` ruby\n# Given route\n# /inboxes/:inbox_id/messages/:message_id/attachments/:id\n# every call below returns:\n# =\u003e \"/inboxes/1/messages/2/attachments/3\"\n\ninbox_message_attachment_path(1, 2, 3)\ninbox_message_attachment_path(1, 2, id: 3)\ninbox_message_attachment_path(1, message_id: 2, id: 3)\ninbox_message_attachment_path(inbox_id: 1, message_id: 2, id: 3)\n\n# including these mad versions\ninbox_message_attachment_path(2, inbox_id: 1, id: 3)\ninbox_message_attachment_path(1, 3, message_id: 2)\ninbox_message_attachment_path(3, inbox_id: 1, message_id: 2)\n```\n\nWhile all of these methods are supported by JsRoutes, it is impossible to support them in `DTS` type definitions.\nIf you are using routes like this, use the following configuration that will prevent required parameters presence to be validated by definition:\n\n``` ruby\nJsRoutes.setup do |c|\n  c.optional_definition_params = true\nend\n```\n\nThis will enforce the following route signature:\n\n``` typescript\nexport const inbox_message_attachment_path: ((\n  inbox_id?: RequiredRouteParameter,\n  message_id?: RequiredRouteParameter,\n  id?: RequiredRouteParameter,\n  options?: RouteOptions\n) =\u003e string) \u0026 RouteHelperExtras;\n```\n\nThat will make every call above valid.\n\n## What about security?\n\nJsRoutes itself does not have security holes.\nIt makes URLs without access protection more reachable by potential attacker.\nIf that is an issue for you, you may use one of the following solutions:\n\n### ESM Tree shaking\n\nMake sure `module_type` is set to `ESM` (the default). Modern JS bundlers like\n[Webpack](https://webpack.js.org) can statically determine which ESM exports are used, and remove\nthe unused exports to reduce bundle size. This is known as [Tree\nShaking](https://webpack.js.org/guides/tree-shaking/).\n\nJS files can use named imports to import only required routes into the file, like:\n\n``` javascript\nimport {\n  inbox_path,\n  inboxes_path,\n  inbox_message_path,\n  inbox_attachment_path,\n  user_path,\n} from '../routes'\n```\n\nJS files can also use star imports (`import * as`) for tree shaking, as long as only explicit property accesses are used.\n\n``` javascript\nimport * as routes from '../routes';\n\nconsole.log(routes.inbox_path); // OK, only `inbox_path` is included in the bundle\n\nconsole.log(Object.keys(routes)); // forces bundler to include all exports, breaking tree shaking\n```\n\n### Exclude/Include options\n\nSplit your routes into multiple files related to each section of your website like:\n\n``` ruby\nJsRoutes.generate!('app/javascript/admin-routes.js', include: /^admin_/) %\u003e\nJsRoutes.generate!('app/javascript/app-routes.js', exclude: /^admin_/) %\u003e\n```\n\n## Advantages over alternatives\n\nThere are some alternatives available. Most of them has only basic feature and don't reach the level of quality I accept.\nAdvantages of this one are:\n\n* Actively maintained\n* [ESM Tree shaking](https://webpack.js.org/guides/tree-shaking/) support\n* Rich options set\n* Full rails compatibility\n* Support Rails `#to_param` convention for seo optimized paths\n* Well tested\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frailsware%2Fjs-routes","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frailsware%2Fjs-routes","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frailsware%2Fjs-routes/lists"}