Controllers
Controllers are responsible for handling incoming HTTP requests and returning responses. A controller groups related routes under a common path prefix.
Defining a controller
Use the @Controller() decorator to define a controller and its path prefix:
import { Controller, Get, Post, type RequestContext } from '@miiajs/core'
@Controller('/users')
class UserController {
@Get('/')
list() {
return [{ id: 1, name: 'Alice' }]
}
@Get('/:id')
findOne(ctx: RequestContext) {
return { id: ctx.params.id }
}
@Post('/')
async create(ctx: RequestContext) {
return await ctx.json()
}
}
Controllers must be registered in a Module to be discovered by the framework.
Route decorators
MiiaJS provides decorators for all standard HTTP methods:
| Decorator | HTTP Method |
|---|---|
@Get(path?, options?) / @Get(options) | GET |
@Post(path?, options?) / @Post(options) | POST |
@Put(path?, options?) / @Put(options) | PUT |
@Patch(path?, options?) / @Patch(options) | PATCH |
@Delete(path?, options?) / @Delete(options) | DELETE |
@Head(path?, options?) / @Head(options) | HEAD |
@Options(path?, options?) / @Options(options) | OPTIONS |
The path argument is optional and defaults to '' (the controller prefix itself). options carries the route's request schemas - { body, query, params }, see Validation - and can be passed alone when the route sits at the controller prefix: @Get({ query: Paging }).
RequestContext
Every route handler receives a RequestContext object as its first argument:
interface RequestContext {
req: Request // Native Fetch API Request
res: ResponseBuilder // Fluent response builder
params: Record<string, any> // URL path parameters
query: Record<string, any> // Parsed query string
rawQuery: URLSearchParams // Raw query for multi-value params
readonly conn: ConnInfo // Transport-level connection info (lazy)
readonly ip: string | undefined // Client IP (respects trustProxy)
readonly cookies: CookieJar // Incoming cookies (lazy)
json<T = any>(): Promise<T> // Parsed JSON body (cached)
text(): Promise<string> // Raw body as text (cached)
resolve<T>(token: Token<T> | AbstractConstructor<T>): T // Provider for this request (request scope lives here)
}
query, rawQuery, conn, and cookies are lazy-loaded on first access for better performance. params and query hold strings until a route schema replaces them with its output.
ctx.resolve() reaches any provider; a request-scoped one belongs to this request and is destroyed once the response is built, so resolve it before the handler returns.
ctx.json() reads the body through ctx.text(), so the two share one read, are both cached per request, and can be combined in any order. An empty body, or none at all, makes ctx.json() resolve to undefined; a body that is not valid JSON rejects with a 400 Bad Request (Malformed JSON body). The raw stream (ctx.req.body, ctx.req.formData(), ctx.req.arrayBuffer()) is available only until the first call to either helper.
RequestContext is extensible via declaration merging. For example, an app using @miiajs/auth declares user this way - see Typing ctx.user.
Client IP and connection info
ctx.conn is the transport-level connection info - { remoteAddress?, remotePort?, family? }. It always reflects the socket, is resolved lazily, and is cached per request. On runtimes or adapters that cannot provide it (for example serverless app.fetch usage) it is an empty object.
ctx.ip is the client IP. By default it equals ctx.conn.remoteAddress; behind a reverse proxy that is the proxy's address, so tell the app which headers to trust:
new Miia({ trustProxy: true }) // leftmost X-Forwarded-For entry
new Miia({ trustProxy: 'cf-connecting-ip' }) // a single trusted header (Cloudflare)
new Miia({ trustProxy: ['cf-connecting-ip', 'x-real-ip'] }) // first present, in priority order
ctx.conn.remoteAddress always stays the honest socket address regardless of trustProxy. The default client key in @miiajs/rate-limit is ctx.ip.
Route parameters
Dynamic segments in the path are extracted as ctx.params:
@Get('/:userId/posts/:postId')
getPost(ctx: RequestContext) {
const { userId, postId } = ctx.params
return { userId, postId }
}
Response handling
Route handlers can return values in several ways:
Auto JSON
Return any object or array and it will be serialized as JSON with status 200:
@Get('/')
list() {
return [{ id: 1 }, { id: 2 }]
}
Every other value goes out as JSON too: return 'ok' sends "ok" with Content-Type: application/json. Use ctx.res.text() for a plain-text body.
Custom status
Use the @Status() decorator to set a different status code:
import { Status } from '@miiajs/core'
@Post('/')
@Status(201)
create(ctx: RequestContext) {
return { id: 3, created: true }
}
Native Response
Return a Response object for full control:
@Get('/download')
download() {
return new Response('raw body', {
status: 200,
headers: { 'Content-Type': 'text/plain' },
})
}
Response builder
Use ctx.res for a fluent API:
@Get('/html')
page(ctx: RequestContext) {
ctx.res
.status(200)
.header('X-Request-Id', 'abc')
.html('<h1>Hello</h1>')
}
A body set through ctx.res wins over the return value, and a HEAD request never serializes it. See How the response is built for the full rules.
Validation
A route's request schemas go into its route decorator. Any ZodLike schema works (Zod, or any object with safeParse()):
import { Controller, Get, Post, Status, type RequestContext } from '@miiajs/core'
import { z } from 'zod'
const CreateUserSchema = z.object({
name: z.string().min(1),
email: z.string().email(),
})
const QuerySchema = z.object({
page: z.coerce.number().default(1),
limit: z.coerce.number().default(10),
})
const IdParamsSchema = z.object({
id: z.string().uuid(),
})
type CreateUserInput = z.infer<typeof CreateUserSchema>
@Controller('/users')
class UserController {
@Post('/', { body: CreateUserSchema })
@Status(201)
async create(ctx: RequestContext) {
// ctx.json<T>() returns the validated (and possibly transformed) data.
const data = await ctx.json<CreateUserInput>()
return data
}
@Get({ query: QuerySchema })
list(ctx: RequestContext) {
return { page: ctx.query.page, limit: ctx.query.limit }
}
@Get('/:id', { params: IdParamsSchema })
findOne(ctx: RequestContext) {
return { id: ctx.params.id }
}
}
Handler methods that read the request body must be async, since ctx.json() returns a Promise.
| Key | Validates | Validated value |
|---|---|---|
body | Request body | await ctx.json<T>() |
query | Query parameters | ctx.query |
params | Path parameters | ctx.params |
A schema's output replaces the raw value, so transforms and defaults are what the handler sees. A route without schemas gets no validation step at all.
body exists only on @Post, @Put, @Patch, and @Delete. GET, HEAD, and OPTIONS carry no request body, so their options type has no body key, and passing one anyway from plain JavaScript throws a TypeError when the class is defined.
When validation runs
Validation is the last step before the handler - after global guards, controller guards and middleware, and method guards and middleware - and always checks params, then query, then body. A request a guard turns away gets its 401/403 before any schema sees it, and a @Use middleware on the method sees the raw ctx.params and ctx.query before await next() and the validated ones after it.
A failed check throws UnprocessableException (422) with the schema's issues in details:
{
"statusCode": 422,
"error": "Unprocessable Entity",
"message": "Body validation failed",
"details": [
{
"expected": "string",
"code": "invalid_type",
"path": ["email"],
"message": "Invalid input: expected string, received undefined"
}
]
}
The message names the part that failed: Params validation failed, Query validation failed, or Body validation failed. A body that is not valid JSON never reaches the schema: it is a 400 with the message Malformed JSON body, the same as on a route without one. An empty body counts as no body, so the schema gets undefined and a required object fails with 422. A body over the route's size limit is still a 413.
Several routes on one handler
Schemas belong to the handler, not to a single route. When you stack route decorators on one method, the routes share its schemas: a route without options uses the schemas another route on that method declared, and giving the same key two different schemas throws a TypeError at class definition. A GET, HEAD, or OPTIONS route cannot share a handler with a body schema either, whichever decorator comes first.
@Get('/', { query: QuerySchema })
@Get('/all') // same handler, so /all validates its query too
list(ctx: RequestContext) { /* ... */ }
The body schema reads JSON unless a package says otherwise. On a @Multipart route it validates the buffered form instead.
Body size limits
Every app enforces a request body limit of 1 MiB by default. A request whose declared Content-Length exceeds the route's limit gets a 413 Payload Too Large response before the handler runs. Configure the default app-wide and override per controller or per route with @BodyLimit(bytes):
import { Miia, BodyLimit } from '@miiajs/core'
// App-wide default (bytes). `false` disables the limit entirely.
const app = new Miia({ maxBodySize: 512 * 1024 })
@Controller('/files')
@BodyLimit(5 * 1024 * 1024) // all routes in this controller: 5 MiB
class FileController {
@Post('/avatar')
@BodyLimit(2 * 1024 * 1024) // this route only: 2 MiB (method beats class)
async uploadAvatar(ctx: RequestContext) {
const form = await ctx.req.formData()
// ...
}
@Post('/meta')
async meta(ctx: RequestContext) {
return ctx.json() // controller-level 5 MiB applies
}
}
Precedence: method-level @BodyLimit > class-level @BodyLimit > maxBodySize app option. A method-level @BodyLimit applies even when the app sets maxBodySize: false. GET and HEAD requests are not checked against the limit in core.
A chunked body (no Content-Length) has no length to check up front, so it is counted as it arrives. Routing happens first, so core knows the route's limit by then and hands it to whichever adapter owns the body stream; the bytes are counted against that limit rather than against the app-wide ceiling.
How the cap is enforced per runtime:
| Runtime | Declared Content-Length | No declared length |
|---|---|---|
@miiajs/node-server | Early 413 in the adapter, before the handler | Counted against the route's limit |
| Bun | 413 in core after route matching | Counted against the ceiling by Bun.serve({ maxRequestBodySize }) |
| Deno | 413 in core after route matching | Counted against the ceiling by a stream wrapper applied in listen() |
@miiajs/uws-server | Early 413 in the adapter, before the handler | Counted against the ceiling in-stream |
The ceiling is max(maxBodySize, all @BodyLimit values across the app), so where it is what applies, one generous route relaxes the bound for every route that shares the runtime.
Extending a controller
A controller can extend a class that declares routes and serves all of them. Overriding a handler changes what runs; whether it also changes the routes depends on the decorators on the override:
class CrudController {
@Get('/:id', { params: IdParamsSchema })
findOne(ctx: RequestContext) { /* ... */ }
@Post('/', { body: CreateSchema })
async create(ctx: RequestContext) { /* ... */ }
}
@Controller('/users')
class UserController extends CrudController {
// No route decorator: still GET /users/:id with IdParamsSchema, this method runs
override findOne(ctx: RequestContext) { /* ... */ }
// A route decorator of its own: replaces POST /users and the body schema
@Post('/', { body: CreateUserSchema })
override async create(ctx: RequestContext) { /* ... */ }
}
- Replaced. Route decorators on an override replace the routes and the
body/query/paramsschemas the handler inherited. Repeat the parent's path to keep it, or give another path or method to move the route; a schema the override does not pass is dropped. - Kept. An override without route decorators keeps the inherited routes and schemas.
- Added up. Guards and middleware are not replaced:
@UseGuardand@Useon the override or the subclass run after the parent's, with or without route decorators.@Status,@BodyLimitand package decorators such as@Multipartkeep the parent's value until the override sets its own - a@Multiparton the override replaces the parent's, options and all, so stricter limits there are the ones that apply. A@BodyLimiton the override does not reach an inherited@Multipart, which keeps the parent's body budget; repeat@Multiparton the override to change it. - Documentation.
@ApiBodyfrom@miiajs/swaggeris inherited like@Status, and in the spec it wins over the route'sbodyschema - an override that changes the body schema with a route decorator of its own still shows the parent's@ApiBody. Repeat@ApiBodyon the override with the schema it takes.
To drop a guard the parent put on the handler or the class, put @SkipGuard on the override:
class AdminCrud {
@UseGuard(AdminOnly)
@Get('/:id')
findOne(ctx: RequestContext) { /* ... */ }
}
@Controller('/public')
class PublicController extends AdminCrud {
@SkipGuard(AdminOnly)
override findOne(ctx: RequestContext) { /* ... */ }
}
The parent class is never changed by its subclasses, so it can be a controller of its own, and two subclasses can override the same handler in different ways.