Skip to content

HTTP Responses ​

Introduction ​

Every handler ends by producing a Response. You can return one explicitly, or return a string or object and let the kernel convert it. Response is a small builder: static constructors make the common kinds, and fluent instance methods set headers, cookies and flash data.

ts
import { Response, Router } from '@plinthjs/http'

const router = new Router()
router.get('/ping', () => Response.text('pong'))

Returning values ​

When a handler returns something other than a Response, the kernel converts it:

ts
router.get('/a', () => 'Hello') // 200 text/html
router.get('/b', () => ({ ok: true })) // 200 application/json
router.get('/c', () => [1, 2, 3]) // 200 application/json
router.get('/d', () => null) // 204 No Content

Return a Response when you need a different status or headers.

Creating responses ​

ts
Response.json({ ok: true }) // 200, application/json; charset=utf-8
Response.json({ id: 1 }, 201) // custom status
Response.text('plain') // text/plain; charset=utf-8
Response.html('<h1>Hi</h1>') // text/html; charset=utf-8
Response.noContent() // 204
Response.make('body', 202) // text/html; charset=utf-8
Response.make({ ok: true }) // object: JSON, application/json; charset=utf-8
Response.make(null) // no body, no Content-Type; build up with the fluent methods
Response.make('x', 200, { 'Content-Type': 'text/plain' }) // headers win

status, headers and body are public properties, so middleware can also change them directly. setStatus() changes the status code and chains.

Views ​

@plinthjs/http renders no templates itself. Render a view with your view engine and wrap the string in Response.html(). See Views. A route can also render a view directly with router.view(), see Routing.

ts
router.get('/welcome', () => Response.html(engine.render('welcome', { name: 'Ada' })))

Headers ​

ts
Response.json(data)
  .header('X-Request-Id', 'abc123') // one header
  .withHeaders({ 'Cache-Control': 'no-store', 'X-App': 'plinth' }) // several

Headers are stored in a plain object, so reading one is res.headers['X-App'] with the exact casing you used.

Cookies ​

cookie() queues a Set-Cookie header. Calling it more than once adds distinct cookies.

ts
Response.make('ok').cookie('seen', '1', {
  maxAge: 3600, // seconds
  httpOnly: true,
  secure: true,
  sameSite: 'Lax', // 'Strict' | 'Lax' | 'None'
  path: '/', // default '/'
  domain: 'example.com',
  expires: new Date('2030-01-01'),
})

res.cookies() // => ['seen=1; Path=/; Max-Age=3600; Secure; HttpOnly; SameSite=Lax; ...']

Values are URL-encoded for you. Read cookies from the request with req.cookie(), see Requests. Cookies that must be tamper proof or secret should go through the session or encryption rather than being set by hand.

Redirects ​

ts
Response.redirectTo('/dashboard') // 302
Response.redirect('/dashboard', 301) // custom status
Response.redirectTo('https://example.com') // an absolute URL is fine too

Use named routes to avoid hard coded paths: Response.redirectTo(router.url('users.show', { id: 7 })).

Redirecting back ​

Pass the request and Response.back(request, fallback) redirects to the Referer header when it points at the same host as the request, and to the fallback (default /) otherwise. A foreign or malformed referer is ignored, so a forged header cannot turn it into an open redirect.

ts
router.post('/posts', (req) => Response.back(req, '/posts'))

The older Response.back(fallback) form still works but has no request to consult, so it always redirects to the fallback.

The scaffolded application's src/support/http.ts wraps that as a back(request) helper, and the redirect(url) helper there is a thin wrapper over Response.redirectTo.

Flashing data and errors ​

A redirect can carry data for the next request. The chainable methods store it on the response, and the session middleware moves it into the session when the response passes back through it. See Session.

ts
router.post(
  '/profile',
  (req) =>
    Response.redirectTo('/profile')
      .with('status', 'Profile saved') // one key
      .with({ highlight: 'name' }), // or a bag of keys
)

router.post(
  '/signup',
  (req) =>
    Response.back(req, '/signup')
      .withErrors({ email: ['That email is taken.'] }) // a validation error bag
      .withInput(req.except(['password'])), // repopulates the form
)

withErrors() stores the bag under the errors key, and withInput() stores it as old input, so the next request can read session.get('errors') and session.old('email'). Keep sensitive fields such as passwords out of withInput(). The validation integration does this for you, see Validation. The queued flash data is readable with res.flashes() and res.getFlash('status'), which is useful in tests.

WARNING

Flash data is only persisted when the session middleware is installed. Without it the data stays on the response object and is dropped.

File responses ​

Response.file() serves a file inline, inferring Content-Type from the extension and setting Content-Length. Response.download() sends it with a Content-Disposition: attachment header so browsers save it.

ts
Response.file('/srv/reports/q3.pdf') // inline
Response.download('/srv/reports/q3.pdf') // saves as q3.pdf
Response.download('/srv/reports/q3.pdf', 'quarterly-report.pdf') // custom name
Response.download('/srv/data.bin', 'data.bin', { 'Cache-Control': 'private' }) // extra headers

Both read the file into memory synchronously, so use them for modestly sized files and use streaming for large ones. A missing file throws the underlying filesystem error.

Streaming responses ​

A streamed response writes each chunk to the client as the source produces it, using chunked transfer encoding and respecting backpressure, so a large payload never sits whole in memory.

Streaming text or bytes ​

Response.stream() accepts an iterable, an async iterable, or a function returning one (a generator function is the usual choice). Chunks are strings or Uint8Arrays.

ts
router.get('/events', () =>
  Response.stream(
    async function* () {
      for (let i = 1; i <= 3; i++) {
        yield `chunk ${i}\n`
      }
    },
    200,
    { 'Content-Type': 'text/plain' },
  ),
)
// the client receives: chunk 1, chunk 2, chunk 3

A function source is invoked once, lazily, when the response is flushed. res.isStream() tells you whether a response is streamed.

Streamed downloads ​

Response.streamDownload() is stream() with a download file name and a default application/octet-stream type:

ts
router.get('/export.csv', () =>
  Response.streamDownload(
    function* () {
      yield 'id,name\n'
      yield '1,Ada\n'
    },
    'export.csv',
    { 'Content-Type': 'text/csv' }, // override the default type
  ),
)

Streaming JSON ​

Response.streamJson() serializes rows as they arrive. An iterable becomes one JSON array. An object is written key by key, and any value that is itself an iterable is streamed as an array.

ts
async function* rows() {
  yield { id: 1 }
  yield { id: 2 }
}

Response.streamJson(rows()) // => [{"id":1},{"id":2}]
Response.streamJson({ users: rows(), total: 2 }) // => {"users":[{"id":1},{"id":2}],"total":2}

TIP

Combine streamJson() with a database cursor or any async generator to return a huge result set with constant memory.

WARNING

Once streaming has begun the status and headers have been sent, so an error part way through cannot become an error page. The server adapter ends the connection abruptly instead. Validate and authorize before you start the stream.

Response macros ​

A macro is a reusable response builder you register once and call by name. Re-registering a name replaces it.

ts
Response.macro('created', (data: unknown) => Response.json(data, 201))
Response.hasMacro('created') // => true

Response.callMacro('created', { id: 1 } as never) // a 201 response

callMacro() types its arguments as never[], so cast them (as never) or wrap the call in a small typed helper in your application. Register several at once with mixin():

ts
Response.mixin({
  accepted: () => Response.json({ accepted: true }, 202),
  teapot: () => Response.make('I am a teapot', 418),
})

Calling a name that is not registered throws Response macro [name] is not defined.

Status helpers ​

There is no separate catalog of status helpers: pick the status when you build the response, or use the exceptions in Error handling to produce error statuses from anywhere.

ts
Response.json(user, 201) // created
Response.noContent() // 204
Response.json({ message: 'Gone' }, 410)
Response.make('Accepted', 202)
res.setStatus(206) // change the status of an existing response

Released under the MIT License.