Core Concepts / Middleware

Middleware

Transform requests and responses using the Koa-style onion model.

MiiaJS uses a Koa-style onion model for middleware. A single compose() function replaces the need for separate interceptors, pipes, and filters.

Middleware signature

typescript
type Middleware = (
  ctx: RequestContext,
  next: () => Promise<void>,
) => void | Promise<void>

A middleware calls await next() to pass control to the next middleware, or skips it to short-circuit the pipeline. It can be async or plain: a synchronous middleware that returns next() passes control the same way.

Onion model

Middleware wraps around the handler, executing code before and after:

Request -> [MW1 before] -> [MW2 before] -> [Handler] -> [MW2 after] -> [MW1 after] -> Response
typescript
const timing: Middleware = async (ctx, next) => {
  const start = Date.now()
  await next()
  const duration = Date.now() - start
  ctx.res.header('X-Response-Time', `${duration}ms`)
}

Global middleware

Apply middleware to all routes with app.use():

typescript
import { Miia, cors } from '@miiajs/core'

const app = new Miia()
  .use(cors())
  .use(timing)
  .register(AppModule)

Global middleware executes in the order it's registered.

Global middleware is pre-route: it wraps the entire dispatch, including router.match(). This means it runs on every request, including unmatched routes that return 404. An unmatched route rejects next() with a NotFoundException, which bubbles up through the onion like any other error, so middleware can observe it via try { await next() } catch:

typescript
import { HttpException, type Middleware } from '@miiajs/core'

const requestLogger: Middleware = async (ctx, next) => {
  const start = Date.now()
  let status = 500
  try {
    await next()
    status = ctx.res.getStatus()
  } catch (error) {
    if (error instanceof HttpException) status = error.statusCode
    throw error
  } finally {
    const { pathname } = new URL(ctx.req.url, 'http://localhost')
    console.log(`${ctx.req.method} ${pathname} ${status} (${Date.now() - start}ms)`)
  }
}

The error response is built after the whole onion has unwound, so inside finally ctx.res.getStatus() still says 200 for a request that failed - take the status from the error instead. A handler that returns a native Response carries its own status, which ctx.res does not see either. The base URL in new URL() covers Bun, which hands a request with an invalid Host header over with a relative ctx.req.url.

This is why CORS, request loggers, and request-id middleware set headers that appear on 404 responses - the header was written before the dispatch found no route, and the error response keeps the headers middleware set.

Early termination

A global middleware that does not call next() short-circuits the dispatch - router.match() never runs, the handler never runs, and the response is built from ctx.res:

typescript
const rateLimiter: Middleware = async (ctx, next) => {
  if (await isRateLimited(ctx.req)) {
    ctx.res.status(429).json({ error: 'Too Many Requests' })
    return // no next() → router and handler skipped entirely
  }
  await next()
}

This is the standard Koa pattern - the response is assembled from the ResponseBuilder exactly as if the handler had returned null.

Controller middleware

Apply middleware to all routes in a controller with the @Use() decorator:

typescript
import { Controller, Use } from '@miiajs/core'

@Controller('/api')
@Use(loggingMiddleware, authMiddleware)
class ApiController {
  // All methods get loggingMiddleware and authMiddleware
}

Route middleware

Apply middleware to a specific route:

typescript
@Controller('/items')
class ItemController {
  @Post('/')
  @Use(validateMiddleware)
  async create(ctx: RequestContext) {
    return await ctx.json()
  }
}

Execution order

Global middleware (app.use())
  -> Global guards (app.useGuard())
  -> Controller guards (@UseGuard on class)
  -> Controller middleware (@Use on class)
  -> Route guards (@UseGuard on method)
  -> Route middleware (@Use on method)
  -> Route schemas (params -> query -> body)
  -> Route handler

Global middleware runs on every request; everything from the global guards on runs only once a route has matched.

The schemas from the route decorator (@Post('/', { body }) and the rest) are checked last, right before the handler. A method-level @Use middleware therefore sees the raw ctx.params, ctx.query, and body before await next(), and the validated values once await next() resolves.

Built-in middleware

CORS

typescript
import { cors } from '@miiajs/core'

app.use(cors({
  origin: ['https://example.com', 'https://app.example.com'],
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  credentials: true,
  maxAge: 86400,
}))

Options:

OptionTypeDescription
originstring | string[] | ((origin: string) => boolean)Allowed origins
methodsstring[]Allowed HTTP methods
allowedHeadersstring[]Allowed request headers
exposedHeadersstring[]Headers exposed to the browser
credentialsbooleanAllow credentials
maxAgenumberPreflight cache duration (seconds)

A preflight is an OPTIONS request that carries both Origin and Access-Control-Request-Method, as the Fetch spec defines it. cors() answers it with 204 and the Access-Control-Allow-Methods, Access-Control-Allow-Headers and Access-Control-Max-Age headers, without reaching the router. Any other OPTIONS request goes on like any other method - to your @Options route, or to a 404 - with the CORS headers a GET from the same origin would get. A preflight from a refused origin is not answered by cors() either: it goes on to the router without any Access-Control-* headers - to an @Options route, or to a 404 - and the browser blocks the request it was asking about.

With origin: '*' every answer is the same. Any other origin - a string, a list or a predicate - adds Origin to Vary on every response, including the ones to a refused origin and to requests without Origin: a shared cache would otherwise hand a response without Access-Control-Allow-Origin to an allowed origin. Origin is appended to a Vary an earlier middleware set, not written over it.

Writing custom middleware

typescript
import { UnauthorizedException, type Middleware } from '@miiajs/core'

// Extend RequestContext with custom properties via declaration merging
declare module '@miiajs/core' {
  interface RequestContext {
    user?: { id: string; role: string }
  }
}

const auth: Middleware = async (ctx, next) => {
  const token = ctx.req.headers.get('authorization')
  if (!token) {
    throw new UnauthorizedException()
  }
  ctx.user = await verifyToken(token)
  await next()
}

const errorHandler: Middleware = async (ctx, next) => {
  try {
    await next()
  } catch (error) {
    // Custom error handling
    ctx.res.status(500).json({ error: 'Something went wrong' })
  }
}

compose()

The compose() function combines multiple middleware into one, with the semantics of koa-compose:

typescript
import { compose } from '@miiajs/core'

const combined = compose([auth, logging, timing])

app.use(combined)

The composed function always returns a promise. A middleware that throws synchronously rejects it rather than throwing, calling next() twice in one middleware rejects with next() called multiple times, and the promise resolves to what the first middleware returned. After the last middleware, next() calls the next passed to the composed function.

Edit this page on GitHub