Core Concepts / Routing

Routing

How MiiaJS matches URLs to handlers - static routes, dynamic parameters, wildcards, and route compilation.

MiiaJS uses a trie-based router with a static route fast path. Routes are defined via decorators on controllers, and the router compiles them into an optimized matching structure before handling the first request.

How matching works

When a request arrives, the router resolves a handler in this order:

  1. Static lookup - O(1) Map check for routes without parameters (e.g. /users, /health)
  2. Trie traversal - walks the trie for routes with :param or * wildcard segments, backing up when a branch leads nowhere
  3. HEAD fallback - a HEAD request also tries the GET routes, each kind right after its HEAD counterpart: the static GET route after the static HEAD one, the GET patterns after the HEAD patterns - see HEAD requests

Priority

When multiple routes could match a URL, the router picks the most specific one, segment by segment:

static segment  >  :param  >  * wildcard

Given these routes:

typescript
@Get('/users/me')      // static
@Get('/users/:id')     // param
@Get('/users/*')       // wildcard

A request to /users/me matches the static route. /users/42 matches the param route. /users/42/posts/1 matches the wildcard.

The last one works because the router backs up. 42 fits :id, but no route continues with /posts/1 from there, so the router returns to /users/ and takes the next option at that segment - the wildcard. It backs up only when a branch dead-ends: a URL that matches on the first try costs one walk down the trie. Routes of other methods do not take part - POST /users/:id/avatar does not stop GET /users/42/avatar from reaching the wildcard.

The first segment that differs decides, not the number of static segments: with /a/b/:x and /a/:y/c, a request to /a/b/c matches /a/b/:x. The other route is tried only when nothing under /a/b/ matches.

Duplicate routes

Two routes with the same method on the same path are an error, however they were registered - addRoute() twice, or a controller route and an addRoute() that land on one path:

[Miia] Route GET /users/:userId conflicts with GET /users/:id

Parameter names do not make two routes different: /users/:id and /users/:userId occupy the same slot, so the second is rejected instead of silently replacing the first. Paths are compared after the global prefix is applied. GET and HEAD on one path are separate routes - see HEAD requests for which one a HEAD request reaches.

addRoute() throws on the call. Controller routes are written when the module graph is processed (first init(), app.get() or fetch()), so a conflict there surfaces from that call.

Path parameters

Dynamic segments prefixed with : capture a single path segment:

typescript
@Controller('/users')
class UserController {
  @Get('/:id')
  findOne(ctx: RequestContext) {
    return { id: ctx.params.id }
  }
}

Multiple parameters work across nested segments:

typescript
@Get('/:userId/posts/:postId')
getPost(ctx: RequestContext) {
  const { userId, postId } = ctx.params
  return { userId, postId }
}

GET /users/42/posts/7 → { userId: '42', postId: '7' }

Parameter names belong to the route. /:id and /:userId/posts/:postId in the same controller start with a parameter at the same position, yet GET /users/42 gets { id: '42' } and GET /users/42/posts/7 gets { userId: '42', postId: '7' }.

Parameters are always strings. Parse them in your handler if you need numbers.

Wildcards

A * segment captures the entire remaining path:

typescript
app.addRoute('GET', '/files/*', (ctx) => {
  // GET /files/images/logo.png → ctx.params['*'] = 'images/logo.png'
  return { path: ctx.params['*'] }
})

Wildcards are useful for catch-all routes, static file serving, and SPA fallbacks. The captured value is available as ctx.params['*']. The rest may be empty: /files matches /files/* with ''.

A wildcard is the last option at its segment, so it also gets every URL that the more specific routes below it could not finish. A SPA mounted at / therefore answers an unknown /api/... URL unless a catch-all under /api claims it first - see Serve Static → SPA in front of a prefixed API.

Trailing slashes

MiiaJS normalizes trailing slashes - /users and /users/ match the same route. You don't need to register both.

typescript
@Get('/users')
list() { return [] }

// All of these match:
// GET /users
// GET /users/

HEAD requests

HEAD requests fall back to GET routes. The framework returns headers only, without a body - matching HTTP spec behavior.

typescript
@Get('/health')
check() {
  return { status: 'ok' }
}

// GET  /health → 200 { "status": "ok" }
// HEAD /health → 200 (headers only, no body)

A HEAD request is matched in this order: a static HEAD route on the exact path, a static GET route on the exact path, then the HEAD routes with parameters or wildcards, then the GET ones. A static GET route therefore wins over a HEAD pattern that also matches - with @Head('/files/:id') and @Get('/files/latest'), HEAD /files/latest runs the GET handler, and HEAD /files/42 the HEAD one. Give the path its own @Head to answer it differently.

The GET lookup follows the same priority and backs up the same way, so with the routes from Priority, HEAD /users/42/posts/1 reaches GET /users/*.

There is no automatic 405: a URL that has routes only for other methods answers 404.

Manual routes

Use app.addRoute() to register routes without decorators:

typescript
const app = new Miia()
  .addRoute('GET', '/health', () => ({ ok: true }))
  .addRoute('GET', '/users/:id', (ctx) => {
    return { id: ctx.params.id }
  })
  .addRoute('POST', '/upload', uploadHandler, { middlewares: [authMiddleware] })
  .register(AppModule)
typescript
type Handler = (ctx: RequestContext) => unknown

app.addRoute(method: HttpMethod, path: string, handler: Handler, options?: AddRouteOptions): this

The fourth argument is an options object:

typescript
interface AddRouteOptions {
  middlewares?: Middleware[]
  skipGlobalGuards?: boolean
  skippedGuardClasses?: Set<unknown> | null // filled from @SkipGuard for controller routes
  bodyLimit?: number | false
  skipGlobalPrefix?: boolean
}

skipGlobalGuards opts the route out of every guard registered with app.useGuard(), bodyLimit is the per-route form of @BodyLimit(), and skipGlobalPrefix is covered in Routes outside the prefix.

Manual routes participate in the pipeline like any other: global middleware from app.use() wraps them, global guards apply to them, and anything in middlewares runs as route-bound middleware inside the global onion.

Global prefix

Mount the whole application under a path segment with the globalPrefix option:

typescript
const app = new Miia({ globalPrefix: '/api' })
  .addRoute('GET', '/health', () => ({ ok: true }))
  .register(AppModule)

// GET /api/health
// GET /api/users    (from @Controller('/users'))

The prefix is prepended to everything registered through the router: controller routes, app.addRoute(), and the wildcard route that serveStatic() installs. 'api', '/api', and '/api/' are equivalent - the value is normalized before it reaches the route table.

A prefix containing *, :, ?, #, or whitespace throws a TypeError. A * would collapse the entire route table onto one wildcard slot, and a : would inject a parameter segment into every path in the app.

The prefix has to exist before the routes

MiiaJS does not defer route resolution to listen(). addRoute() writes the final path into the route table on the call, and controller routes are written when the module graph is processed - on the first init(), app.get() or fetch(). A prefix assigned after either point would silently apply to later routes only, so it throws instead. The constructor option is the only form that cannot get the ordering wrong.

A prefix that varies per environment is still a constructor argument:

typescript
const app = new Miia({ globalPrefix: process.env.API_PREFIX })

The prefix is a deployment detail read at construction time, so it does not need to travel through the container.

Tests are the one place where it is not a constructor argument. A TestApp is assembled through a builder rather than constructed directly, so @miiajs/testing exposes setGlobalPrefix() as a builder step:

typescript
const app = await TestApp.create(AppModule).setGlobalPrefix('/api').compile()

The builder only records the prefix and compile() hands it to the Miia constructor, so it covers every route. Like every builder step, it throws after compile().

The prefix stays out of the OpenAPI spec

globalPrefix is applied inside the router and never reaches the RESOLVED_PREFIX metadata that @miiajs/swagger reads, so the generated paths stay clean - /users, not /api/users. This is what separates it from @Module({ prefix }), which is part of the resolved controller path and does show up in the spec.

typescript
SwaggerModule.configure({
  title: 'My API',
  version: '1.0.0',
  servers: [{ url: 'http://localhost:3000/api' }],
})

Swagger's own endpoints are not moved either. The spec stays at its configured path and the UI at uiPath - /docs/json and /docs/ by default, not /api/docs/json.

Routes outside the prefix

Health checks and platform probes usually have to answer at a fixed URL. The options object addRoute() takes carries a skipGlobalPrefix flag for them:

typescript
const app = new Miia({ globalPrefix: '/api' })
  .addRoute('GET', '/health', () => ({ ok: true }), { skipGlobalPrefix: true })
  .register(AppModule)

// GET /health      → 200
// GET /api/health  → 404

It is the same object described under Manual routes, so a route can opt out of the prefix and still carry its own middleware or body limit.

serveStatic() forwards the same flag, which is how a SPA stays at the root while the API lives under the prefix:

typescript
serveStatic(app, '/', './dist', { fallback: 'index.html', skipGlobalPrefix: true })

The mount is a wildcard at the root, so an unknown /api/... URL falls through to it. SPA in front of a prefixed API shows the catch-all that keeps those a 404.

Routes registered from inside a provider - after DI is wired up, the way @miiajs/swagger registers its endpoints - go through the injected Router, whose add() takes the same options. From onReady() the route is added after the pipelines were compiled, so bodyLimit and skipGlobalPrefix apply, but middlewares and the global guards do not:

typescript
import { Injectable, Router, inject } from '@miiajs/core'

@Injectable()
export class HealthRoute {
  private router = inject(Router)

  onReady() {
    this.router.add('GET', '/health', () => ({ ok: true }), { skipGlobalPrefix: true })
  }
}

See Discovery → Registering routes in onReady for what a route registered this late does and does not receive.

Absolute paths you wrote by hand

The prefix rewrites URLs in the router, not the strings in your code. Redirect targets, links inside an HTML response, and hardcoded fetch() paths keep pointing exactly where you typed them. Both ends of this two-line example move, and only one of them is visible in the source:

typescript
// With globalPrefix: '/api':
// the mount moves to /api/static/*, so the '/static' target below is a 404,
serveStatic(app, '/static', './public')
// and the route itself moves too - '/' normalizes to the prefix, so this
// answers at /api, not at /.
app.addRoute('GET', '/', (ctx) => {
  ctx.res.redirect('/static')
})

A path of '/' is not a special case: it resolves to the prefix itself, the same way /health resolves to /api/health. So the redirect is both unreachable at the URL you expected and pointing at the wrong target once you do reach it.

Derive such paths from the same prefix value you passed to the constructor, or move both ends out of the prefix with the escape hatch above - the redirect route and the serveStatic() mount both take skipGlobalPrefix.

Route compilation

Before handling the first request, MiiaJS compiles all routes into optimized pipelines:

Global pipeline

Global middleware registered via app.use() is composed once into a single compiledGlobalPipeline that wraps the entire dispatch, including router.match(). This is how global middleware runs on 404 responses and sees the NotFoundException of an unmatched route - see Middleware → Global middleware.

Per-route pipeline

Each decorator route is compiled into its own pipeline in this order:

Global guards (app.useGuard(), unless @SkipGuard filters them)
  → Controller @UseGuard() guards
  → Controller @Use() middlewares
  → Method @UseGuard() guards
  → Method @Use() middlewares
  → Route schemas (params → query → body)
  → Route handler

The per-route pipeline is nested inside the global pipeline at dispatch time: globalMiddleware → router.match → perRouteMiddleware → handler.

Performance

  • Static routes are stored in a Map per method for O(1) exact matching - no trie traversal needed
  • Backing up starts only after a branch dead-ends below a segment that had a lower-priority option, and the search visits each trie node at most once - its cost is bounded by the routes registered for that method, never exponential
  • URL parsing uses indexOf() instead of regex for fast pathname/query extraction
  • Query params are parsed lazily - only when ctx.query is accessed
  • Sync fast path - a route without global middleware, guards, route middleware or schemas whose handler is synchronous skips async/await entirely, returning JSON inline with zero Promise allocation. Without global middleware an unmatched URL gets its 404 without an exception being built
  • Pipeline compilation happens once at startup, not per-request
Edit this page on GitHub