Skip to content
LykosJSLYKOSJS
CreatorDeveloperBenchmarkshomeGet started
v1.0.0
Application & serverREST APIGraphQLRouting & groupsRequest context & repliesValidationError handling
PREVIOUSGraphQLNEXT Request context & replies
© 2026 LykosJS · MIT LicenseBun · TypeScript

© 2026 LykosJS. Released under the MIT License.
Built by Zen Allaham.

DocsGitHubX
DOCS/V1.0.0/CORE CONCEPTS
CORE CONCEPTS

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.

ts
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.

ts
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.

Routes are method-specific
A GET /users route and a POST /users route are separate registrations. The router uses both the HTTP method and normalized path when identifying a registered route.

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.

ts
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.

ts
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:

text
1GET /users/1232GET /users/user-13GET /users/abc

The 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:

ts
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:

json
1{2  "userId": "user-1",3  "postId": "post-5"4}
Dynamic parameters occupy complete path segments
A parameter is recognized when its segment starts with :. The router does not implement wildcard or optional parameter syntax in the implementation shown here.

5. Read route parameters

The router extracts parameter values from the incoming URL and makes them available through ctx.params.

ts
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.

text
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.

ts
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:

text
1GET /users?page=2&limit=20

You can retrieve each query parameter using ctx.query.get().

ts
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().

Route parameters and query parameters are different
Route parameters are extracted from the URL path, such as /users/:id. Query parameters are read from the query string, such as ?page=2. LykosJS exposes them through ctx.params and ctx.query, respectively.

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.

text
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:

ts
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.

Normalization does not change parameter values
Path normalization removes empty path segments. Dynamic parameter values are decoded separately during route matching.

8. Route path requirements

Route paths registered through the Lykos application and route groups must start with /.

ts
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.

text
1Prefix:      /api/users/2Child path:  /:id3 4Combined:    /api/users/:id

9. 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.

ts
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.

ts
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:

ts
1app.GET('/users', listUsers)2app.POST('/users', createUser)3app.DELETE('/users', deleteUsers)
Duplicate detection uses normalized paths
Paths such as /users and /users/ normalize to the same registration key when used with the same HTTP method.

10. Understand static and dynamic route matching

The router uses separate collections for static and dynamic routes:

  • routes stores all registered route handlers and is used for duplicate detection and route listing.
  • staticRoutes stores routes without dynamic parameter segments.
  • dynamicRoutes stores 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 undefined from 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.

ts
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.

text
1Example dynamic route patterns:2 3/users/:id/posts4/users/:id5/:category/:id6 7Static routes are checked separately before8the dynamic route collection.
Static routes have their own priority
The router does not simply execute routes in registration order. Static routes are checked first, and dynamic routes are sorted using their segment patterns before matching.

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.

ts
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:

text
1GET     /api/users2GET     /api/users/:id3POST    /api/users4PUT     /api/users/:id5DELETE  /api/users/:id

The 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.

ts
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:

text
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.

ts
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.

ts
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.

ts
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:

text
11. authMiddleware22. permissionMiddleware

16. Use RouteGroup.use()

A RouteGroup exposes a use() method for adding middleware to that group.

ts
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.

ts
1users2  .use(authMiddleware)3  .GET('/', listUsers)
Add group middleware before registering routes
Middleware is copied into the route registration when each route is registered. Calling use() after a route has already been registered does not retroactively modify that route's middleware.

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.

ts
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:

text
1GET /api/users2GET /api/users/:id3 4GET /api/posts5GET /api/posts/:id

Each 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.

ts
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:

text
11. authMiddleware22. adminAuthMiddleware

The 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.

ts
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:

text
11. authMiddleware22. adminAuthMiddleware33. permissionMiddleware

The 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.

ts
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.

ts
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.

Route metadata is not the route handler
The route listing exposes each registered method and path. It does not expose the internal handler function or middleware pipeline.

22. Understand allowedMethods()

The router also provides an allowedMethods(path) method for checking which HTTP methods have been registered for a particular path.

ts
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:

text
1GET2HEAD3POST4PUT5PATCH6DELETE7OPTIONS

Only methods registered for the supplied normalized path are included in the result.

This is a route lookup helper
allowedMethods() reports registered methods for a path. It does not itself execute a request or register an OPTIONS handler.

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.

ts
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.
text
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.

ts
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.

Keep routes organized and predictable
Use static paths for fixed endpoints, dynamic parameters for resource identifiers, and route groups for related endpoints. Apply shared middleware at the group level and route-specific middleware only where it is needed.