Docs / Request context

Request context

The ctx object: params, query, headers, body, db client, logger.

Every handler receives a ctx object holding the request surface, a logger, and the database client. Its return value is serialized into a response.

The ctx object

Every handler receives ctx:

defineRoute({
  handler: async (ctx) => {
    ctx.method;             // 'GET' | 'POST' | ...
    ctx.path;               // '/posts/123'
    ctx.url;                // URL object
    ctx.params;             // { id: '123' }
    ctx.query;              // URLSearchParams
    ctx.headers;            // Request headers
    ctx.ip;                 // string | undefined
    ctx.startedAt;          // number — request start (Date.now()), used for duration
    ctx.requestId;          // string | undefined — set if requestId() middleware ran

    const body = await ctx.body();   // parsed JSON
    const raw  = await ctx.text();   // raw body

    ctx.setStatus(201);
    ctx.setHeader('X-Custom', 'value');

    ctx.log.info('handler running', { id: ctx.params.id });

    const post = await ctx.db?.model('post').findOne(Number(ctx.params.id));

    return { ok: true };    // any value → JSON response
  },
});

Return-value serialization

Return values are serialized: