ArctonArcton
Middleware

Modifying Responses

Setting headers and status from middleware, replacing the body after next(), and when the response becomes final.

ctx.response carries the status and headers that will be used for the response. Middleware can read and change it on the way in and on the way out:

import { Arcton } from '@arcton/core'

const app = Arcton()

app.use(async (ctx, next) => {
  await next()
  ctx.response.headers.set('X-Powered-By', 'Arcton')
})

app.get('/', () => ({ ok: true }))

app.listen()

Headers

ctx.response.headers is a standard Headers object. set() replaces, append() adds another value:

import { Arcton } from '@arcton/core'

const app = Arcton()

app.use(async (ctx, next) => {
  await next()

  ctx.response.headers.set('X-Request-Id', crypto.randomUUID())
  ctx.response.headers.append('Set-Cookie', 'session=abc; Path=/; HttpOnly')
  ctx.response.headers.append('Set-Cookie', 'theme=dark; Path=/')
})

app.get('/', () => ({ ok: true }))

app.listen()

Header changes work both before and after await next(), and both send the cookies above. Setting a header the handler also sets means the later write wins, so a middleware running after next() can override the handler.

Status

Set ctx.response.status before the body is produced — in the handler, or in a middleware before await next():

import { Arcton } from '@arcton/core'

const app = Arcton()

app.post('/users', ctx => {
  ctx.response.status = 201
  ctx.response.headers.set('Location', '/users/42')

  return { id: '42' }
})

app.listen()

The status is fixed once the response body is produced. Assigning ctx.response.status after await next() throws a TypeError. To change a status on the way out, return a new value or a Response instead — see below.

Replacing the body after next()

Returning a value after await next() replaces the body. The headers and status accumulated so far carry over:

import { Arcton } from '@arcton/core'

const app = Arcton()

app.use(async (ctx, next) => {
  await next()

  return { wrapped: true, at: new Date().toISOString() }
})

app.get('/', () => ({ ok: true }))

app.listen()

The client receives the wrapper object.

To replace the status as well, return a Response. It wins outright — no headers are merged in from ctx.response:

import { Arcton } from '@arcton/core'

const app = Arcton()

app.use(async (ctx, next) => {
  await next()

  if (ctx.response.headers.get('X-Deprecated') === 'yes') {
    return new Response(JSON.stringify({ error: 'gone' }), {
      status: 410,
      headers: { 'content-type': 'application/json' }
    })
  }
})

app.get('/legacy', ctx => {
  ctx.response.headers.set('X-Deprecated', 'yes')
  return { ok: true }
})

app.listen()

Short-circuiting

Returning a value without calling next() answers the request immediately, and nothing further in the chain runs:

import { Arcton } from '@arcton/core'

const app = Arcton()

app.use(async (ctx, next) => {
  if (ctx.request.headers.get('x-api-key') !== 'secret') {
    return new Response('Unauthorized', { status: 401 })
  }

  await next()
})

app.get('/private', () => ({ secret: true }))

app.listen()

A short-circuit can also return a plain value, which is mapped the same way a handler's return value is:

import { Arcton } from '@arcton/core'

const app = Arcton()

app.use(async (ctx, next) => {
  if (!ctx.request.headers.has('authorization')) {
    ctx.response.status = 401
    return { error: 'missing authorization' }
  }

  await next()
})

app.get('/private', () => ({ secret: true }))

app.listen()

Caching and conditional responses

Because middleware sees the response on the way out, it can add cache headers across a whole section of the API:

import { Arcton } from '@arcton/core'

const app = Arcton()

app.use('/static', async (ctx, next) => {
  await next()
  ctx.response.headers.set('Cache-Control', 'public, max-age=3600')
})

app.get('/static/config', () => ({ theme: 'dark' }))

app.listen()

Complete example

Timing, a request id and cookies together:

import { Arcton } from '@arcton/core'

const app = Arcton()

app.use(async (ctx, next) => {
  const start = performance.now()
  const requestId = ctx.request.headers.get('x-request-id') ?? crypto.randomUUID()

  await next()

  ctx.response.headers.set('X-Request-Id', requestId)
  ctx.response.headers.set(
    'X-Response-Time',
    `${(performance.now() - start).toFixed(2)}ms`
  )
})

app.get('/', ctx => {
  ctx.response.status = 200
  ctx.response.headers.append('Set-Cookie', 'visited=1; Path=/')

  return { ok: true }
})

app.listen()

For how a returned value becomes a Response, see Response.

On this page