Response

Build HTTP responses with the fluent ResponseBuilder API.

MiiaJS provides a ResponseBuilder on ctx.res for building responses with a fluent API.

ResponseBuilder API

ctx.res
  .status(code: number)                // Set status code
  .header(name: string, value: string) // Add header
  .json(data: unknown)                 // JSON body + Content-Type
  .text(data: string)                  // Text body + Content-Type
  .html(data: string)                  // HTML body + Content-Type
  .redirect(url: string, status?: number) // Redirect (default 302)
  .stream(readable: ReadableStream)    // Streaming body
  .cookie(name, value, options?)       // Append a Set-Cookie header
  .deleteCookie(name, { path?, domain? }) // Expire a cookie

All methods return this for chaining.

cookie() and deleteCookie() write response cookies. See Cookies for the full cookie API, including reading incoming cookies via ctx.cookies.

Examples

JSON with custom headers

@Get('/data')
getData(ctx: RequestContext) {
  ctx.res
    .status(200)
    .header('X-Request-Id', 'abc-123')
    .json({ data: 'value' })
}

HTML

@Get('/page')
getPage(ctx: RequestContext) {
  ctx.res.html('<h1>Hello, World!</h1>')
}

Redirect

@Get('/old-path')
redirect(ctx: RequestContext) {
  ctx.res.redirect('/new-path', 301)
}

Streaming

@Get('/download')
download(ctx: RequestContext) {
  const stream = getFileStream('report.csv')
  ctx.res
    .header('Content-Disposition', 'attachment; filename="report.csv"')
    .header('Content-Type', 'text/csv')
    .stream(stream)
}

Plain text

@Get('/health')
health(ctx: RequestContext) {
  ctx.res.text('OK')
}

Auto response

If you don't use ctx.res, the return value of the handler determines the response:

Return valueResponse
Object / ArrayJSON with 200 (or @Status() value)
Response instancePassed through as-is
null / undefined204 No Content
// Auto JSON
@Get('/')
list() {
  return [{ id: 1 }]
}

// Native Response
@Get('/raw')
raw() {
  return new Response('body', { status: 200 })
}

// No content
@Delete('/:id')
@Status(204)
remove() {}