ctx.response.set()

Sets one or more response headers; aliased as `ctx.set()`.

Since Koa 2 Spec ↗

Syntax

ctx.response.set(field, value)
ctx.response.set(headers)

Parameters

NameTypeRequiredDescription
field string No Header field name (case-insensitive) when using the two-argument form.
value string | string[] No Header value or array of values.
headers object No An object of `{ name: value }` pairs to set multiple headers at once.

Returns

void — Returns nothing.

Examples

import Koa from 'koa';

const app = new Koa();

app.use(async (ctx) => {
  ctx.set('X-Request-Id', crypto.randomUUID());
  ctx.set({
    'Cache-Control': 'max-age=3600, public',
    'Vary': 'Accept-Encoding',
  });
  ctx.body = 'cached';
});

app.listen(3000);
Output
X-Request-Id: 550e8400-e29b-41d4-a716-446655440000
Cache-Control: max-age=3600, public
Vary: Accept-Encoding

Notes

`ctx.set()` replaces any existing value for the given field. To append a value to an existing header (e.g. multiple `Set-Cookie`), use `ctx.append(field, value)`. Setting headers after `ctx.body` has been written has no effect.

See also