Core Concepts / Response

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

typescript
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 + text/plain; charset=utf-8
  .html(data: string)                  // HTML body + text/html; charset=utf-8
  .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

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

HTML

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

Redirect

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

Streaming

typescript
@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

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

How the response is built

When the handler returns, its result and ctx.res become one response:

Handler resultResponse
Object, array, string, number or booleanJSON with 200 (or the @Status() value)
Response instancePassed through as is
null / undefinedBuilt from ctx.res - its status, headers and body, if any. Without a body it is empty with 200 (or the @Status() value), e.g. @Status(204) for No Content
ctx.res itselfThe same as returning nothing
typescript
// 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() {}

// Returning the builder is returning nothing
@Get('/login')
login(ctx: RequestContext) {
  return ctx.res.redirect('/auth/github')
}

A few rules decide what happens when the return value and ctx.res meet:

  • A string is JSON too. return 'ok' sends "ok" with Content-Type: application/json, the same encoding as any other value. For a plain-text body call ctx.res.text('ok').
  • A body on ctx.res wins. Once the handler or a middleware has called json(), text(), html() or stream(), that body is sent under its own Content-Type, and a value the handler also returns is ignored.
  • Status and headers carry over. A value returned after ctx.res.status(201) or ctx.res.header(...) goes out as JSON with that status and those headers.
  • A Content-Type of your own is kept. A handler that sets the header and returns a value gets the value serialized as JSON under the type it set:
    typescript
    @Get('/:id')
    findOne(ctx: RequestContext) {
      ctx.res.header('Content-Type', 'application/vnd.api+json')
      return { data: { type: 'users', id: ctx.params.id } }
    }
    
  • HEAD never serializes. On a HEAD request - to a @Head route or to the GET route it falls back to - the returned value is not turned into a body: the response carries the status and headers a GET would get, Content-Type: application/json included when the value would have been JSON, and no body. A returned Response loses its body the same way.

Thrown errors take a separate path - see Exceptions.

Edit this page on GitHub