Route
Use your AdonisJs routes in your Inertia.js application
Install / Use
/learn @izzyjs/RouteREADME
@izzyjs/route
Use your AdonisJs routes in JavaScript with advanced HTTP client capabilities.
This package provides a JavaScript route() function and a powerful builder for generating URLs and making HTTP requests to named routes defined in an AdonisJs application. Features include hash fragments, query parameters, optional parameters, TypeScript support, and automatic CSRF protection.
Key Features
- 🚀 Route Generation - Generate URLs for named AdonisJs routes
- 🔗 Hash Fragments - Support for hash fragments (
/path#section) - 🌐 Complete URLs - Generate full URLs with protocol and domain
- 🔧 Builder API - Fluent API for HTTP requests with TypeScript support
- 🛡️ CSRF Protection - Automatic CSRF token handling
- 📝 TypeScript - Full TypeScript support with type inference
- 🎯 Query Parameters - Easy query parameter management
- 🔄 HTTP Methods - Support for GET, POST, PUT, DELETE, PATCH
- ⚡ Error Handling - Global error handling and response management
- 🎨 Route Filtering - Filter routes by patterns or groups
- 🔀 Optional Parameters - Support for both required and optional route parameters
Quick Start
ℹ️ Note: The
baseUrlis mandatory in yourconfig/izzyjs.tsfile and will always be available for complete URLs.
import { route } from '@izzyjs/route/client'
import builder from '@izzyjs/route/builder'
// Generate URLs with required parameters
const userUrl = route('users.show', { params: { id: '123' } })
console.log(userUrl.path) // "/users/123"
console.log(userUrl.url) // "https://example.com/users/123" (requires baseUrl config)
// Generate URLs with optional parameters
const postsUrl = route('posts.index', { params: { category: 'tech' } })
console.log(postsUrl.path) // "/posts/tech"
// Optional parameters can be omitted
const allPostsUrl = route('posts.index')
console.log(allPostsUrl.path) // "/posts"
// With hash fragments
const homeWithHash = route('home', { hash: 'contact' })
console.log(homeWithHash.path) // "/#contact"
// Make HTTP requests
const result = await builder('users.show', { id: '123' })
.withQs({ include: 'profile' })
.withHash('details')
.request()
.successType<UserResponse>()
.run()
if (result.data) {
console.log('User:', result.data)
}
Installation
Recommended (automatic)
The following command will install and configure everything automatically (provider, middleware, Japa plugin, config file config/izzyjs.ts, and route generation):
node ace add @izzyjs/route
Manual (step-by-step)
If you prefer manual setup, install the package with your package manager and then run the configure hook:
# npm
npm install @izzyjs/route
# yarn
yarn add @izzyjs/route
# pnpm
pnpm add @izzyjs/route
# then configure
node ace configure @izzyjs/route
The configure step will generate config/izzyjs.ts, register the provider/middleware/Japa plugin, and trigger an initial routes generation.
Configuration
To use the route() function in your JavaScript applications, you need to follow these steps:
Command
You can run a command to generate the route definitions from @izzyjs/routes with:
node ace izzy:routes
These type definitions are only needed in a development environment, so they can be generated automatically in the next step.
Assemble Hook
Add the following line to the adonisrc.ts file to register the () => import('@izzyjs/route/dev_hook') on onDevServerStarted array list.
{
// rest of adonisrc.ts file
unstable_assembler: {
onBuildStarting: [() => import('@adonisjs/vite/build_hook')],
onDevServerStarted: [() => import('@izzyjs/route/dev_hook')] // Add this line,
}
}
View Helper
Add edge plugin in entry view file @routes to use the route() into javascript.
// resources/views/inertia_layout.edge
<!doctype html>
<html>
<head>
// rest of the file @routes() // Add this line // rest of the file
</head>
<body>
@inertia()
</body>
</html>
Route Filtering
@izzyjs/route supports filtering the list of routes it outputs, which is useful if you have certain routes that you don't want to be included and visible in your HTML source.
Important: Hiding routes from the output is not a replacement for thorough authentication and authorization. Routes that should not be accessible publicly should be protected by authentication whether they're filtered out or not.
Including/Excluding Routes
To set up route filtering, create a config file in your app at config/izzyjs.ts and add either an only or except key containing an array of route name patterns.
Note: You have to choose one or the other. Setting both only and except will disable filtering altogether and return all named routes.
// config/izzyjs.ts
import { defineConfig } from '@izzyjs/route'
export default defineConfig({
baseUrl: 'https://example.com', // ⚠️ MANDATORY - Required for complete URLs
routes: {
// Include only specific routes
only: ['home', 'posts.index', 'posts.show'],
// OR exclude specific routes
// except: ['_debugbar.*', 'horizon.*', 'admin.*'],
},
})
You can use asterisks as wildcards in route filters. In the example below, admin.* will exclude routes named admin.login, admin.register, etc.:
// config/izzyjs.ts
import { defineConfig } from '@izzyjs/route'
export default defineConfig({
baseUrl: 'https://example.com',
routes: {
except: ['_debugbar.*', 'horizon.*', 'admin.*'],
},
})
Filtering with Groups
You can also define groups of routes that you want to make available in different places in your app, using a groups key in your config file:
// config/izzyjs.ts
import { defineConfig } from '@izzyjs/route'
export default defineConfig({
baseUrl: 'https://example.com',
routes: {
groups: {
admin: ['admin.*', 'users.*'],
author: ['posts.*'],
public: ['home', 'about', 'contact'],
},
},
})
Complete URLs
The baseUrl is mandatory in your defineConfig. When configured, the route() function automatically generates complete URLs with protocol, domain, and path. This is useful for:
- External links and redirects
- API calls to different domains
- Email templates and notifications
- Webhook URLs
- Cross-domain requests
// config/izzyjs.ts
import { defineConfig } from '@izzyjs/route'
export default defineConfig({
baseUrl: 'https://api.example.com',
routes: {
except: ['admin.*'],
},
})
Now when you use the route() function, you get both the path and complete URL:
import { route } from '@izzyjs/route/client'
const userRoute = route('users.show', { id: '123' })
console.log(userRoute.path) // "/users/123"
console.log(userRoute.url) // "https://api.example.com/users/123"
// Use url for external requests
fetch(userRoute.url)
window.open(userRoute.url)
The baseUrl can include:
- Protocol:
http://orhttps:// - Domain:
example.comorapi.example.com - Port:
localhost:8080 - Subdomain:
admin.example.com
If the baseUrl is invalid or not configured, url falls back to just the path.
Domain-Specific URLs
When your routes have different domains (not just 'root'), the system automatically uses the route's specific domain instead of the baseUrl.host:
// config/izzyjs.ts
export default defineConfig({
baseUrl: 'https://example.com', // Protocol will be extracted from this
routes: { ... }
})
// Routes with different domains
const homeRoute = route('home') // domain: 'root'
const apiRoute = route('api.users.index') // domain: 'api.example.com'
const adminRoute = route('admin.dashboard') // domain: 'admin.example.com'
console.log(homeRoute.url) // "https://example.com/" (uses baseUrl.host)
console.log(apiRoute.url) // "https://api.example.com/users" (uses route domain)
console.log(adminRoute.url) // "https://admin.example.com/dashboard" (uses route domain)
This is useful for multi-domain applications where different routes need to point to different subdomains or domains.
When groups are configured, they will be available in your generated routes:
import { routes, groups } from '@izzyjs/route/client'
// Access all routes
console.log(routes)
// Access specific groups
console.log(groups.admin) // Admin routes only
console.log(groups.author) // Author routes only
console.log(groups.public) // Public routes only
Usage
Now that we've followed all the steps, we're ready to use route() on the client side to generate URLs for named routes.
import { route } from '@izzyjs/route/client'
const url = route('users.show', { params: { id: '1' } }) // /users/1
Route
Is a callback class with a parameter for route(), with information about the method, pattern and path itself.
API Options
The route() function accepts an options object with the following properties:
params- Route parameters (required for routes with parameters)qs- Query string parameters- **`pre
Related Skills
node-connect
352.0kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
frontend-design
111.1kCreate distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
Writing Hookify Rules
111.1kThis skill should be used when the user asks to "create a hookify rule", "write a hook rule", "configure hookify", "add a hookify rule", or needs guidance on hookify rule syntax and patterns.
review-duplication
100.6kUse this skill during code reviews to proactively investigate the codebase for duplicated functionality, reinvented wheels, or failure to reuse existing project best practices and shared utilities.
