Routing & Groups
Build structured HTTP APIs with static and dynamic routes, method-based matching, nested route groups and composable middleware.
Understanding routing in LykosJS
Routing determines how incoming HTTP requests are matched to the handlers responsible for processing them. In LykosJS, the router matches requests using their HTTP method and URL path, then provides the matched handler with route parameters through the request context.
LykosJS supports static paths, parameterized paths, route groups and nested groups. You can also attach middleware globally, to a group or directly to an individual route.
Routes are registered through the Lykosapplication instance. Route groups provide a way to organize related endpoints without repeating their common URL prefixes and middleware.
1. Register your first route
The simplest way to register an endpoint is to call an HTTP method on your application instance and provide a path and a handler.
1import { Lykos } from 'lykosjs'2 3const app = new Lykos()4 5app.GET('/', async (ctx, reply) => {6 return reply.OK({ message: 'Welcome to LykosJS 🐺' })7})8 9app.listen(4000)Each route registration accepts three main parts:
method— the HTTP method used to identify the route.path— the URL path that the route should match.handler— the function executed when an incoming request matches the route.
Route handlers receive the request context and a reply object. A handler must return a Response to complete the request.
2. Supported HTTP methods
LykosJS provides dedicated methods for registering the standard HTTP methods supported by its router.
1app.GET('/users', listUsers)2app.POST('/users', createUser)3app.PUT('/users/:id', replaceUser)4app.PATCH('/users/:id', updateUser)5app.DELETE('/users/:id', deleteUser)6app.HEAD('/users', checkUsers)7app.OPTIONS('/users', getUserOptions)The available methods are:
GET— register a route for retrieving resources.POST— register a route for submitting data or creating resources.PUT— register a route for replacing a resource.PATCH— register a route for partially updating a resource.DELETE— register a route for deleting a resource.HEAD— register a route for HEAD requests.OPTIONS— register a route for OPTIONS requests.
These methods are available on both the main Lykos instance and RouteGroup instances.
3. Register static routes
A static route contains a fixed URL path. Its path segments must match the incoming request path exactly after the router's static-path normalization.
1app.GET('/users', async (_ctx, reply) => {2 return reply.OK([3 { id: 'user-1', name: 'Zen' },4 { id: 'user-2', name: 'Alex' },5 ])6})7 8app.GET('/health', async (_ctx, reply) => {9 return reply.OK({ status: 'healthy' })10})Static routes are stored separately from dynamic routes. When matching a request, the router checks the static route collection first.
This means a matching static route is selected before the router attempts to match parameterized routes registered for the same HTTP method.
4. Register dynamic routes
Dynamic routes allow a URL segment to represent a variable value. Define a parameter by placing a colon before its name in the route path.
1app.GET('/users/:id', async (ctx, reply) => {2 const id = ctx.params.id3 4 return reply.OK({ id })5})In this example, :id is a dynamic segment. Requests such as the following match the same route:
1GET /users/1232GET /users/user-13GET /users/abcThe matched segment is assigned to ctx.params.id. The parameter name comes from the name defined in the route path.
You can define multiple parameters in a route:
1app.GET('/users/:userId/posts/:postId', async (ctx, reply) => {2 const { userId, postId } = ctx.params3 4 return reply.OK({ userId , postId })5 },6)For a request to /users/user-1/posts/post-5, the resulting parameters are:
1{2 "userId": "user-1",3 "postId": "post-5"4}5. Read route parameters
The router extracts parameter values from the incoming URL and makes them available through ctx.params.
1app.GET('/products/:productId', async (ctx, reply) => {2 const productId = ctx.params.productId3 4 return reply.OK({ productId })5})Internally, the router compares the route segments with the incoming request segments. When it finds a segment beginning with :, it extracts the corresponding request segment and assigns it to the parameter name.
Parameter values are decoded using decodeURIComponent(). This allows encoded URL segments to be exposed as decoded parameter values.
1Route:2 /users/:name3 4Request:5 /users/Zen%20Allaham6 7Parameter:8 ctx.params.name === 'Zen Allaham'If a parameter contains invalid percent-encoding, the router treats that route as a non-match and continues searching for another matching dynamic route.
6. Read query string parameters
Query strings are separate from route parameters. They are available through ctx.query, which is a URLSearchParams instance.
1app.GET('/users', async (ctx, reply) => {2 const page = Number(ctx.query.get('page') ?? 1)3 const limit = Number(ctx.query.get('limit') ?? 10)4 5 return reply.OK({ page, limit })6})For a request such as:
1GET /users?page=2&limit=20You can retrieve each query parameter using ctx.query.get().
1const page = ctx.query.get('page')2const limit = ctx.query.get('limit')3const search = ctx.query.get('search')The URLSearchParams API also provides methods such as has(), getAll() and entries().
7. Route path normalization
The router normalizes paths before storing route registrations and matching static paths. Its normalization process splits the path by /, removes empty segments and joins the remaining segments with a single slash.
1Input path Normalized path2 3/users /users4//users /users5/users/ /users6/users//active /users/active7/ /This behavior is implemented by the router's normalizePath() method:
1private normalizePath(path: string): string {2 const parts = path.split('/').filter(Boolean)3 4 return '/' + parts.join('/')5}Normalization is used when registering routes and when checking static route matches. Dynamic route matching also splits paths into segments and filters empty segments before comparing them.
8. Route path requirements
Route paths registered through the Lykos application and route groups must start with /.
1// Valid2app.GET('/users', listUsers)3app.GET('/users/:id', getUser)4 5// Invalid6app.GET('users', listUsers)7app.GET('users/:id', getUser)Route groups apply the same requirement to their prefixes and child paths. When joining a group prefix with a child path, both values must start with a slash.
The group path-joining logic removes trailing slashes from the prefix and leading slashes from the child path before combining them.
1Prefix: /api/users/2Child path: /:id3 4Combined: /api/users/:id9. Prevent duplicate route registrations
The router maintains a map of registered routes. Each registration is identified by a key composed of its HTTP method and normalized path.
1const key = `${method} ${normalizedPath}`2 3if (this.routes.has(key)) {4 throw new Error(5 `Route "${key}" is already registered.`,6 )7}8 9this.routes.set(key, handler)If the same HTTP method and normalized path are registered more than once, the router throws an error instead of silently replacing the previous handler.
1app.GET('/users', listUsers)2 3// Throws a duplicate registration error:4app.GET('/users/', anotherListUsers)However, registering the same path with a different HTTP method is allowed:
1app.GET('/users', listUsers)2app.POST('/users', createUser)3app.DELETE('/users', deleteUsers)10. Understand static and dynamic route matching
The router uses separate collections for static and dynamic routes:
routesstores all registered route handlers and is used for duplicate detection and route listing.staticRoutesstores routes without dynamic parameter segments.dynamicRoutesstores parameterized routes grouped by HTTP method.
When a request arrives, matching follows this sequence:
- Check the static route collection for the requested method and path.
- If no static route matches, retrieve the dynamic routes registered for that method.
- Split the request path into segments.
- Compare each dynamic route's segments with the request segments.
- Return the first matching handler and its extracted parameters.
- If no route matches, return
undefinedfrom the router's matching operation.
The matching logic is based on the HTTP method and path. A route registered for one method does not automatically match requests using another method.
11. Route matching priority
Static routes are checked before dynamic routes. This allows a specific endpoint to take priority over a parameterized route.
1app.GET('/users/me', getCurrentUser)2 3app.GET('/users/:id', getUserById)A request to /users/me matches the static route rather than treating me as the id parameter.
Dynamic routes are also sorted during registration. The comparator examines corresponding segments and places a static segment before a dynamic segment when their positions differ. If the compared segments have the same static or dynamic status throughout the shared length, the longer route is ordered first.
1Example dynamic route patterns:2 3/users/:id/posts4/users/:id5/:category/:id6 7Static routes are checked separately before8the dynamic route collection.12. Create a route group
Route groups let you organize related endpoints under a shared URL prefix. Instead of repeating the same prefix for every route, define it once when creating the group.
1app.group('/api/users', (users) => {2 users.GET('/', listUsers)3 users.GET('/:id', getUser)4 users.POST('/', createUser)5 users.PUT('/:id', updateUser)6 users.DELETE('/:id', deleteUser)7})The resulting route paths are:
1GET /api/users2GET /api/users/:id3POST /api/users4PUT /api/users/:id5DELETE /api/users/:idThe group callback receives a RouteGroup instance. You can use its HTTP method methods just like the main application instance.
A route group's method calls combine the group prefix with the child path before forwarding the registration to the application's route registrar.
13. Understand how group paths are combined
Route groups use a path-joining function to combine the parent prefix and each child route path.
1function joinPaths(2 prefix: string,3 path: string,4): string {5 if (!prefix.startsWith('/')) {6 throw new Error('Invalid group prefix')7 }8 9 if (!path.startsWith('/')) {10 throw new Error('Invalid route path')11 }12 13 const base =14 prefix === '/'15 ? ''16 : prefix.replace(/\/+$/, '')17 18 const segment = path.replace(/^\/+/, '')19 20 return segment21 ? `${base}/${segment}`22 : base || '/'23}This function handles the boundaries between group prefixes and child paths:
1Group prefix Child path Combined path2 3/api /users /api/users4/api/users /:id /api/users/:id5/api/users / /api/users6/ /users /users7/ / /The function removes trailing slashes from the prefix and leading slashes from the child path before combining them. It also validates that both paths start with a slash.
14. Apply middleware to a route group
A route group can receive middleware as additional arguments after its callback. Every route registered inside that group receives the group's middleware.
1app.group(2 '/api/admin',3 (admin) => {4 admin.GET('/reports', getReports)5 admin.GET('/users', getAdminUsers)6 admin.DELETE('/users/:id', deleteAdminUser)7 },8 adminAuth.middleware,9)In this example, the adminAuth.middleware middleware is applied to all three routes registered inside the group.
The group stores its middleware and passes it to the route registrar whenever a route is registered.
This lets you define authentication, authorization or other shared request-processing behavior once instead of repeating the same middleware on every route.
15. Apply middleware to an individual route
You can also attach middleware directly to an individual route. Middleware is passed after the route handler.
1app.GET(2 '/profile',3 getProfile,4 authMiddleware.middleware,5)6 7app.DELETE(8 '/users/:id',9 deleteUser,10 authMiddleware.middleware,11 adminMiddleware.middleware,12)This is useful when only a small number of endpoints require a particular middleware.
Route groups also support individual route middleware. When a route is registered inside a group, the group's middleware is passed before the middleware supplied directly to that route.
1app.group(2 '/api',3 (api) => {4 api.GET(5 '/profile',6 getProfile,7 permissionMiddleware,8 )9 },10 authMiddleware,11)The middleware registration order for this route is:
11. authMiddleware22. permissionMiddleware16. Use RouteGroup.use()
A RouteGroup exposes a use() method for adding middleware to that group.
1const users = new RouteGroup(2 registerRoute,3 '/api/users',4)5 6users.use(authMiddleware)7 8users.GET('/', listUsers)9users.GET('/:id', getUser)The use() method adds the middleware to the group's internal middleware collection and returns the same group instance. This allows method chaining.
1users2 .use(authMiddleware)3 .GET('/', listUsers)17. Nest route groups
Route groups can contain other route groups. This allows you to organize APIs into multiple levels while reusing parent prefixes and middleware.
1app.group('/api', (api) => {2 api.group('/users', (users) => {3 users.GET('/', listUsers)4 users.GET('/:id', getUser)5 })6 7 api.group('/posts', (posts) => {8 posts.GET('/', listPosts)9 posts.GET('/:id', getPost)10 })11})The nested groups generate these paths:
1GET /api/users2GET /api/users/:id3 4GET /api/posts5GET /api/posts/:idEach nested group combines its prefix with the prefix of its parent group. Its routes then combine that full prefix with their individual paths.
18. Inherit middleware across nested groups
Nested groups inherit the middleware already attached to their parent group. Additional middleware passed to a nested group is appended after the inherited middleware.
1app.group(2 '/api',3 (api) => {4 api.group(5 '/admin',6 (admin) => {7 admin.GET('/reports', getReports)8 admin.DELETE('/users/:id', deleteUser)9 },10 adminAuthMiddleware,11 )12 },13 authMiddleware,14)The nested admin routes receive middleware in this order:
11. authMiddleware22. adminAuthMiddlewareThe implementation creates a nested group with a new middleware array containing the parent's middleware followed by the middleware supplied to the nested group.
This makes it possible to build layered middleware policies for public, authenticated and administrative sections of an API.
19. Combine groups and route-level middleware
You can combine inherited group middleware, nested group middleware and route-specific middleware to build more detailed request processing pipelines.
1app.group(2 '/api',3 (api) => {4 api.group(5 '/admin',6 (admin) => {7 admin.DELETE(8 '/users/:id',9 deleteUser,10 permissionMiddleware,11 )12 },13 adminAuthMiddleware,14 )15 },16 authMiddleware,17)For the DELETE route, middleware is passed in the following order:
11. authMiddleware22. adminAuthMiddleware33. permissionMiddlewareThe route group implementation preserves this order by combining inherited middleware, middleware supplied to the current group and middleware supplied to the individual route.
20. Understand the RouteGroup API
The RouteGroup class exposes the same HTTP registration methods as the main application, along with methods for managing nested groups and group middleware.
GET(path, handler, ...middlewares)registers a GET route inside the group.POST(path, handler, ...middlewares)registers a POST route inside the group.PUT(path, handler, ...middlewares)registers a PUT route inside the group.PATCH(path, handler, ...middlewares)registers a PATCH route inside the group.DELETE(path, handler, ...middlewares)registers a DELETE route inside the group.HEAD(path, handler, ...middlewares)registers a HEAD route inside the group.OPTIONS(path, handler, ...middlewares)registers an OPTIONS route inside the group.use(middleware)adds middleware to the group.group(prefix, callback, ...middlewares)creates a nested route group.
The HTTP registration methods return the current group instance, allowing chained route registration. The group() method also returns the parent group instance after invoking the nested group's callback.
21. Inspect registered routes
LykosJS provides readRoutes() on the application instance to inspect the registered route metadata.
1const routes = app.readRoutes()2 3console.log(routes)The router's underlying list() method creates a read-only list containing each registered route's HTTP method and normalized path.
1[2 {3 method: 'GET',4 path: '/users'5 },6 {7 method: 'GET',8 path: '/users/:id'9 },10 {11 method: 'POST',12 path: '/users'13 }14]The returned array and its route objects are frozen using Object.freeze(). This prevents callers from modifying the returned route metadata.
22. Understand allowedMethods()
The router also provides an allowedMethods(path) method for checking which HTTP methods have been registered for a particular path.
1const methods = router.allowedMethods('/users')2 3console.log(methods)The method normalizes the supplied path and checks the registered route map against the supported HTTP methods.
The supported method list is:
1GET2HEAD3POST4PUT5PATCH6DELETE7OPTIONSOnly methods registered for the supplied normalized path are included in the result.
23. Understand dynamic route matching internally
Dynamic routes are stored with their normalized path, handler and individual path segments. They are grouped by HTTP method.
1interface DynamicRoute {2 path: string3 handler: ContextHandler4 parts: string[]5}When matching a dynamic route, the router first checks that the number of route segments equals the number of request segments.
It then compares each segment:
- If the route segment starts with
:, the request segment is extracted as a parameter. - If the route segment is static, it must equal the request segment.
- If either segment is missing, matching fails.
- If the number of segments differs, matching fails immediately.
1Route:2 /users/:id/posts/:postId3 4Request:5 /users/user-1/posts/post-56 7Comparison:8 users = users9 :id = user-110 posts = posts11 :postId = post-512 13Result:14 {15 id: 'user-1',16 postId: 'post-5'17 }If all segments match, the router returns the handler together with the extracted parameters.
24. Build a complete resource-oriented API
The following example combines static routes, dynamic routes, query strings and route groups to create a small users API.
1import { Lykos } from 'lykosjs'2 3const app = new Lykos()4 5app.group('/api/users', (users) => {6 // GET /api/users7 users.GET('/', async (ctx, reply) => {8 const page = Number(ctx.query.get('page') ?? 1)9 10 return reply.OK({ page, users: [] })11 })12 13 // GET /api/users/:id14 users.GET('/:id', async (ctx, reply) => {15 const { id } = ctx.params16 17 return reply.OK({ id, name: 'Zen' })18 })19 20 // POST /api/users21 users.POST('/', async (ctx, reply) => {22 const body = await ctx.json<{23 name: string24 email: string25 }>()26 27 return reply.Created({ id: 'user-1', ...body })28 })29 30 // PATCH /api/users/:id31 users.PATCH('/:id', async (ctx, reply) => {32 const { id } = ctx.params33 const body = await ctx.json<{ name?: string }>()34 35 return reply.OK({ id, ...body })36 })37 38 // DELETE /api/users/:id39 users.DELETE('/:id', async (ctx, reply) => {40 const { id } = ctx.params41 42 return reply.NoContent()43 })44})45 46app.listen(4000)This example demonstrates how a route group keeps related endpoints under one prefix while each handler accesses the request data it needs.
25. Routing behavior and implementation boundaries
The current LykosJS router implementation provides the following routing capabilities:
- Static route registration and matching.
- Dynamic path parameters using colon-prefixed segments.
- Multiple parameters within the same path.
- Decoding of dynamic parameter values.
- Path normalization and duplicate registration detection.
- Static route matching before dynamic route matching.
- Dynamic route sorting based on segment patterns.
- Route groups with shared URL prefixes.
- Nested groups with inherited middleware.
- Middleware supplied to individual routes.
- Route listing and allowed-method lookup helpers.
The implementation shown here does not provide wildcard routes, optional path parameters or regular-expression route constraints. These should not be assumed to be supported by the routing API.