Skip to content
LykosJSLYKOSJS
CreatorDeveloperBenchmarkshomeGet started
v1.0.0
Application & serverREST APIGraphQLRouting & groupsRequest context & repliesValidationError handling
PREVIOUSRouting & groupsNEXT Validation
© 2026 LykosJS · MIT LicenseBun · TypeScript

© 2026 LykosJS. Released under the MIT License.
Built by Zen Allaham.

DocsGitHubX
DOCS/V1.0.0/CORE CONCEPTS
CORE CONCEPTS

Request context & replies

Understand the complete request context, read typed request data, and build explicit HTTP responses with LykosJS reply helpers.

Understanding the request lifecycle

Every matched HTTP request is passed to a route handler with two arguments: ctx and reply. The context contains information about the incoming request, while the reply object provides methods for creating the outgoing HTTP response.

ts
1app.GET('/users/:id', async (ctx, reply) => {2  const id = ctx.params.id3 4  return reply.OK({ id })5})

The first argument is a Context object. The second argument implements the Reply interface. Both are created for the individual request.

1. Request context properties

The Context interface describes the data available inside a route handler and middleware.

ts
1export interface Context<2  TUser extends AuthenticationUser = AuthenticationUser3> {4  readonly request: Request5  readonly method: string6  readonly url: URL7  readonly path: string8  readonly params: Record<string, string>9  readonly query: URLSearchParams10  readonly headers: Headers11 12  user?: TUser13  auth?: AuthToken14 15  json<T = unknown>(): Promise<T>16  formData(): Promise<FormData>17  text(): Promise<string>18}

request — Incoming Request

request is the original Fetch API Requestobject received by Bun. It provides access to the complete incoming HTTP request.

ts
1app.GET('/request', async (ctx, reply) => {2  const request = ctx.request3 4  return reply.OK({5    method: request.method,6    url: request.url,7    contentType: request.headers.get('content-type'),8  })9})

Its type is Request, not a custom LykosJS request object. You can use standard Fetch API properties and methods.

  • request.method — HTTP method.
  • request.url — complete request URL as a string.
  • request.headers — incoming request headers.
  • request.body — request body stream.
  • request.signal — request cancellation signal.
  • request.bodyUsed — whether the request body has been consumed.
  • request.json(), request.text() and other native body methods are part of the standard Request API.
Prefer the context body readers
LykosJS provides ctx.json(), ctx.text()and ctx.formData() to read request bodies through its request-body handling. Prefer these helpers when working inside route handlers.

method — HTTP method

The method property contains the HTTP method used by the incoming request. Its TypeScript type is string.

ts
1app.GET('/request-method', async (ctx, reply) => {2  return reply.OK({ method: ctx.method })3})

Common values include GET, POST,PUT, PATCH, DELETE,HEAD and OPTIONS.

url — Parsed request URL

url is a standard JavaScript URL object. It represents the complete URL of the incoming request.

ts
1app.GET('/inspect', async (ctx, reply) => {2  return reply.OK({3    href: ctx.url.href,4    hostname: ctx.url.hostname,5    pathname: ctx.url.pathname,6    search: ctx.url.search,7    origin: ctx.url.origin,8  })9})

You can use standard URL properties such as hostname, pathname, search, originand href.

path — Request pathname

path contains the pathname extracted from the request URL. Its type is string. It does not include the query string.

ts
1// Request: GET /users/42?page=22 3app.GET('/users/:id', async (ctx, reply) => {4  return reply.OK({5    path: ctx.path,6    queryString: ctx.url.search,7  })8})9 10// Example:11// {12//   path: "/users/42",13//   queryString: "?page=2"14// }

params — Route parameters

params is a Record<string, string>containing the dynamic parameters extracted from the matched route. Parameter values are decoded using decodeURIComponent().

ts
1app.GET('/users/:id', async (ctx, reply) => {2  const id = ctx.params.id3 4  return reply.OK({ id })5})6 7// Request: GET /users/1238// Result: { id: "123" }

Multiple dynamic segments are supported. Each parameter is available through its name.

ts
1app.GET('/users/:userId/posts/:postId', async (ctx, reply) => {2  const { userId, postId } = ctx.params3 4  return reply.OK({5    userId,6    postId,7  })8})

Since the type is Record<string, string>, TypeScript treats parameter values as strings. Convert them when your application requires numbers or another type.

ts
1app.GET('/users/:id', async (ctx, reply) => {2  const id = Number(ctx.params.id)3 4  if (!Number.isInteger(id)) {5    return reply.BadRequest({ error: 'Invalid user ID' })6  }7 8  return reply.OK({ id })9})
Parameters are strings
A route parameter such as :id is never automatically converted into a number. Use Number(), parseInt() or your preferred parsing method, and validate the result before using it.

query — Query string parameters

query is a standard URLSearchParamsinstance. It provides methods for reading query string values.

ts
1// Request: GET /users?page=2&limit=102 3app.GET('/users', async (ctx, reply) => {4  const page = ctx.query.get('page')5  const limit = ctx.query.get('limit')6 7  return reply.OK({ page, limit })8})

Important URLSearchParams methods:

  • get(name): string | null — returns the first matching value, or null.
  • getAll(name): string[] — returns all values associated with a key.
  • has(name): boolean — checks whether a key exists.
  • set(name, value): void — sets a value.
  • append(name, value): void — adds another value.
  • delete(name): void — removes a parameter.
  • toString(): string — serializes the query parameters.

The return value of get() is string | null. Always account for the possibility that the requested parameter does not exist.

ts
1app.GET('/products', async (ctx, reply) => {2  const page = Number(ctx.query.get('page') ?? 1)3  const limit = Number(ctx.query.get('limit') ?? 20)4 5  return reply.OK({ page, limit })6})

You can also retrieve repeated query parameters:

ts
1// Request: GET /products?tag=node&tag=bun2 3app.GET('/products', async (ctx, reply) => {4  const tags = ctx.query.getAll('tag')5 6  return reply.OK({ tags })7})8 9// Result: { tags: ["node", "bun"] }

headers — Incoming HTTP headers

headers is a standard Fetch API Headersinstance containing the headers sent by the client.

ts
1app.GET('/headers', async (ctx, reply) => {2  const authorization = ctx.headers.get('authorization')3  const contentType = ctx.headers.get('content-type')4  const userAgent = ctx.headers.get('user-agent')5 6  return reply.OK({7    authorization,8    contentType,9    userAgent,10  })11})

Common methods include:

  • get(name): string | null — reads a header.
  • has(name): boolean — checks whether a header exists.
  • entries() — iterates over header entries.
  • keys() — iterates over header names.
  • values() — iterates over header values.
  • forEach(callback) — executes a callback for each header.

Header names are case-insensitive. The get() method returns string | null, not always a string.

user — Authenticated user

user is an optional property intended to hold the authenticated user associated with the request.

ts
1export interface AuthenticationUser {2  id: string3  [key: string]: unknown4}

The default user type requires an id string and permits additional properties with values typed as unknown.

ts
1app.GET('/profile', async (ctx, reply) => {2  const user = ctx.user3 4  if (!user) {5    return reply.Unauthorized()6  }7 8  return reply.OK({ id: user.id })9})

The property is optional because a request may not have an authenticated user. The HTTP server does not automatically populate it. Authentication middleware or application code must assign it.

Custom authenticated user types

You can extend AuthenticationUser to describe the additional fields your application associates with an authenticated user.

ts
1interface AppUser {2  id: string3  email: string4  role: 'admin' | 'user'5}6 7// Context<AppUser> describes a context whose user,8// when assigned, follows the AppUser shape.

The generic type improves TypeScript information, but it does not create the user object or validate its runtime structure.

auth — Authentication token

auth is an optional property typed as AuthToken.

ts
1export interface AuthToken {2  token: string3}

When assigned by authentication logic, it can hold the token associated with the request.

ts
1app.GET('/session', async (ctx, reply) => {2  if (!ctx.auth) {3    return reply.Unauthorized()4  }5 6  return reply.OK({ token: ctx.auth.token })7})
Authentication data is optional
Both user and auth are optional context properties. They are not automatically populated by the HTTP server. Check their existence before accessing their properties.

2. Reading request bodies

LykosJS provides three body-reading methods: json(), text() and formData(). Each method returns a Promise because reading a request body is asynchronous.

json<T>() — Read JSON

The json() method reads and parses a JSON request body. It accepts an optional TypeScript generic that describes the expected result.

ts
1json<T = unknown>(): Promise<T>

Its default type is unknown. If you do not specify a generic, TypeScript will not assume that the parsed JSON has a particular object structure.

ts
1app.POST('/echo', async (ctx, reply) => {2  const payload = await ctx.json()3 4  // payload has type unknown5 6  return reply.OK({ received: payload })7})

To obtain a typed result, provide a generic:

ts
1interface CreateUserDto {2  name: string3  email: string4  age: number5}6 7app.POST('/users', async (ctx, reply) => {8  const payload = await ctx.json<CreateUserDto>()9 10  return reply.Created({11    name: payload.name,12    email: payload.email,13    age: payload.age,14  })15})

Now TypeScript understands the declared properties and their types. For example, payload.name is a string and payload.age is a number.

A generic does not validate JSON
ctx.json<CreateUserDto>() is a TypeScript type declaration, not runtime validation. It does not check whether the client actually sent a string for nameor a number for age. Use a runtime validation mechanism when you need to validate untrusted input.

The JSON reader requires a JSON content type. Invalid JSON is rejected with an HTTP 400 error. A missing or unsupported JSON content type is also rejected by the content-type check.

text() — Read plain text

The text() method reads the request body and decodes it as a UTF-8 string.

ts
1text(): Promise<string>
ts
1app.POST('/messages', async (ctx, reply) => {2  const message = await ctx.text()3 4  return reply.OK({ message })5})

The result is always typed as string. Unlike json(), this method does not parse the content as JSON or require a JSON content type.

Use it for plain-text payloads, raw text input and other text-based request bodies.

formData() — Read form data

The formData() method reads form data and returns a standard FormData object.

ts
1formData(): Promise<FormData>
ts
1app.POST('/profile', async (ctx, reply) => {2  const form = await ctx.formData()3 4  const name = form.get('name')5  const avatar = form.get('avatar')6 7  return reply.OK({8    name,9    hasAvatar: avatar !== null,10  })11})

Useful FormData methods include:

  • get(name): FormDataEntryValue | null — reads the first matching entry.
  • getAll(name): FormDataEntryValue[] — reads all entries with the same name.
  • has(name): boolean — checks whether an entry exists.
  • append(name, value) — adds an entry.
  • set(name, value) — sets an entry.
  • delete(name) — removes an entry.

The type FormDataEntryValue is string | File. Therefore, a form field may return a string or a file. Do not assume that every value is a string.

ts
1app.POST('/upload', async (ctx, reply) => {2  const form = await ctx.formData()3  const file = form.get('avatar')4 5  if (!(file instanceof File)) {6    return reply.BadRequest({ error: 'Avatar file is required' })7  }8 9  return reply.OK({10    filename: file.name,11    size: file.size,12    type: file.type,13  })14})

If the request has no Content-Type header, formData() returns an HTTP 400 error. Invalid form data is also rejected with HTTP 400.

Request body limitations

Request bodies are streams. Reading a body consumes it, so do not expect to call multiple body readers on the same request and independently receive the same body.

LykosJS also applies a maximum request body size. Requests exceeding the configured internal limit are rejected with HTTP 413 (Content Too Large).

Choose the correct body reader
Use json<T>() for JSON, text()for plain text, and formData() for form submissions and file uploads. Do not use a JSON reader for multipart form data.

3. Understanding the Reply interface

The Reply interface provides a consistent way to create HTTP responses. Every reply helper returns a standard Fetch API Response object.

ts
1export interface Reply {2  send(body: string): Response3  json(data: unknown, status?: number): Response4  status(code: number): Reply5  header(name: string, value: string): Reply6 7  // Named status helpers8  OK(data?: unknown): Response9  Created(data?: unknown): Response10  NoContent(): Response11  // ...other status helpers12}

The reply object is created separately for every request. Its status and custom headers are maintained on that request's reply manager, not shared as mutable state between requests.

send(body) — Send a text response

send() accepts a string and returns a Response.

ts
1send(body: string): Response
ts
1app.GET('/hello', async (_ctx, reply) => {2  return reply.send('Hello from LykosJS!')3})

When the body is a string and no custom Content-Type has been supplied, LykosJS sets:

ts
1Content-Type: text/plain; charset=utf-8

If you previously set a Content-Type through header(), the custom value is preserved.

ts
1app.GET('/hello', async (_ctx, reply) => {2  return reply.header('Content-Type', 'text/html').send('<h1>Hello</h1>')3})

json(data, status?) — Send JSON

json() serializes the supplied data as a JSON response. It accepts any value typed as unknownand an optional HTTP status code.

ts
1json(data: unknown, status?: number): Response
ts
1app.GET('/users', async (_ctx, reply) => {2  return reply.json([3    { id: 1, name: 'Zen' },4    { id: 2, name: 'Alex' },5  ])6})

If you omit the status argument, the method uses the current status configured through status(). The default status is 200 OK.

ts
1app.POST('/jobs', async (_ctx, reply) => {2  return reply.status(202).json({ queued: true })3})

You can also provide the status directly:

ts
1return reply.json({ created: true }, 201)

JSON responses cannot use statuses 204, 205 or 304, because these statuses do not permit a response body in this implementation.

status(code) — Set the response status

status() sets the HTTP status code that will be used by subsequent generic response methods such as send()and json().

ts
1status(code: number): Reply
ts
1app.POST('/jobs', async (_ctx, reply) => {2  return reply.status(202).json({ message: 'Job accepted' })3})

It returns the same reply object, allowing method chaining. The status is stored until a response is created.

At response creation time, the status must be an integer between 200 and 599. Otherwise, the response helper throws a RangeError.

status() does not send a response
Calling reply.status(202) only configures the response status. You still need to call a response-producing method and return its result.

header(name, value) — Set response headers

header() sets a custom HTTP response header. It returns the reply object, so you can chain it with other response methods.

ts
1header(name: string, value: string): Reply
ts
1app.GET('/download', async (_ctx, reply) => {2  return reply3    .header('x-api-version', '1.0')4    .header('cache-control', 'no-store')5    .json({ message: 'Download ready' })6})

LykosJS uses the standard Headers implementation internally. Setting the same header name again replaces its previous value through Headers.set().

Custom response headers are included in the response created by the reply helper. A fresh headers collection is used when building the response.

4. Method chaining

The methods status() and header()return Reply, while response-producing methods return Response. This distinction is important for TypeScript and for understanding the correct method order.

ts
1// status() returns Reply2// header() returns Reply3// json() returns Response4 5return reply6  .status(202)7  .header('x-job-id', 'job_1')8  .json({ queued: true })

You can also use a named status helper after setting a custom header:

ts
1return reply.header('x-resource-id', 'user_123').Created({ id: 'user_123' })
Named helpers use their own status
Named helpers such as OK() and Created()use their predefined status codes. A previously configured status() value does not override the named helper's status.

5. Named HTTP status helpers

LykosJS exposes named methods for common HTTP status codes. These methods return a Response directly and can be used instead of manually calling status()and json().

1xx — Informational responses

These methods are exposed by the Reply interface:

ts
1reply.Continue()2reply.SwitchingProtocols()3reply.Processing()4reply.EarlyHints()
  • Continue() — 100 Continue.
  • SwitchingProtocols() — 101 Switching Protocols.
  • Processing() — 102 Processing.
  • EarlyHints() — 103 Early Hints.
Fetch Response status limitation
These methods are declared in the interface, but their current implementation uses the Fetch API Response constructor with a status validation range of 200–599. Consequently, calling these 1xx helpers throws a RangeError. They should not be treated as working ways to return informational responses.

2xx — Successful responses

Use these methods when a request has been successfully processed or accepted.

ts
1reply.OK(data?)2reply.Created(data?)3reply.Accepted(data?)4reply.NonAuthoritativeInfo(data?)5reply.NoContent()6reply.ResetContent()7reply.PartialContent(data?)8reply.MultiStatus(data?)9reply.AlreadyReported(data?)10reply.IMUsed(data?)
  • OK(data?) — 200 OK. Default body: { message: 'OK' }.
  • Created(data?) — 201 Created. Default body: { message: 'Created' }.
  • Accepted(data?) — 202 Accepted. Default body: { message: 'Accepted' }.
  • NonAuthoritativeInfo(data?) — 203 Non-Authoritative Information. Default body: empty object.
  • NoContent() — 204 No Content. No response body.
  • ResetContent() — 205 Reset Content. No response body.
  • PartialContent(data?) — 206 Partial Content. Default body: empty object.
  • MultiStatus(data?) — 207 Multi-Status. Default body: empty object.
  • AlreadyReported(data?) — 208 Already Reported. Default body: empty object.
  • IMUsed(data?) — 226 IM Used. Default body: empty object.
ts
1// 200 OK2return reply.OK({ users: [] })3 4// 201 Created5return reply.Created({ id: 'user_123' })6 7// 202 Accepted8return reply.Accepted({ queued: true })9 10// 204 No Content11return reply.NoContent()

3xx — Redirection responses

Redirection helpers create responses with a Locationheader. They accept an optional URL.

ts
1reply.MultipleChoices(data?)2reply.MovedPermanently(url?)3reply.Found(url?)4reply.SeeOther(url?)5reply.NotModified()6reply.UseProxy(url?)7reply.TemporaryRedirect(url?)8reply.PermanentRedirect(url?)
  • MultipleChoices(data?) — 300 Multiple Choices.
  • MovedPermanently(url?) — 301 Moved Permanently.
  • Found(url?) — 302 Found.
  • SeeOther(url?) — 303 See Other.
  • NotModified() — 304 Not Modified. No response body.
  • UseProxy(url?) — 305 Use Proxy.
  • TemporaryRedirect(url?) — 307 Temporary Redirect.
  • PermanentRedirect(url?) — 308 Permanent Redirect.
ts
1app.GET('/old-page', async (_ctx, reply) => {2  return reply.MovedPermanently('/new-page')3})4 5app.GET('/external', async (_ctx, reply) => {6  return reply.Found('https://example.com')7})

When the URL is omitted, the redirect helper defaults to '/'. The implementation resolves the supplied URL against http://localhost and places the resulting absolute URL in the Location header.

Custom headers previously set with header() are preserved when a redirect response is created.

4xx — Client error responses

These helpers represent errors associated with the client request. You can pass a custom response body to describe the error.

ts
1reply.BadRequest(data?)2reply.Unauthorized(data?)3reply.PaymentRequired(data?)4reply.Forbidden(data?)5reply.NotFound(data?)6reply.MethodNotAllowed(data?)7reply.NotAcceptable(data?)8reply.ProxyAuthenticationRequired(data?)9reply.RequestTimeout(data?)10reply.Conflict(data?)11reply.Gone(data?)12reply.LengthRequired(data?)13reply.PreconditionFailed(data?)14reply.ContentTooLarge(data?)15reply.URITooLong(data?)16reply.UnsupportedMediaType(data?)17reply.RangeNotSatisfiable(data?)18reply.ExpectationFailed(data?)19reply.ImATeapot(data?)20reply.MisdirectedRequest(data?)21reply.UnprocessableContent(data?)22reply.Locked(data?)23reply.FailedDependency(data?)24reply.TooEarly(data?)25reply.UpgradeRequired(data?)26reply.PreconditionRequired(data?)27reply.TooManyRequests(data?)28reply.RequestHeaderFieldsTooLarge(data?)29reply.UnavailableForLegalReasons(data?)
  • BadRequest(data?) — 400 Bad Request. Default: { error: 'Bad Request' }.
  • Unauthorized(data?) — 401 Unauthorized. Default: { error: 'Unauthorized' }.
  • PaymentRequired(data?) — 402 Payment Required.
  • Forbidden(data?) — 403 Forbidden. Default: { error: 'Forbidden' }.
  • NotFound(data?) — 404 Not Found. Default: { error: 'Not Found' }.
  • MethodNotAllowed(data?) — 405 Method Not Allowed.
  • NotAcceptable(data?) — 406 Not Acceptable.
  • ProxyAuthenticationRequired(data?) — 407 Proxy Authentication Required.
  • RequestTimeout(data?) — 408 Request Timeout.
  • Conflict(data?) — 409 Conflict.
  • Gone(data?) — 410 Gone.
  • LengthRequired(data?) — 411 Length Required.
  • PreconditionFailed(data?) — 412 Precondition Failed.
  • ContentTooLarge(data?) — 413 Content Too Large.
  • URITooLong(data?) — 414 URI Too Long.
  • UnsupportedMediaType(data?) — 415 Unsupported Media Type.
  • RangeNotSatisfiable(data?) — 416 Range Not Satisfiable.
  • ExpectationFailed(data?) — 417 Expectation Failed.
  • ImATeapot(data?) — 418 I'm a Teapot. Default: { message: "I'm a teapot" }.
  • MisdirectedRequest(data?) — 421 Misdirected Request.
  • UnprocessableContent(data?) — 422 Unprocessable Content.
  • Locked(data?) — 423 Locked.
  • FailedDependency(data?) — 424 Failed Dependency.
  • TooEarly(data?) — 425 Too Early.
  • UpgradeRequired(data?) — 426 Upgrade Required.
  • PreconditionRequired(data?) — 428 Precondition Required.
  • TooManyRequests(data?) — 429 Too Many Requests.
  • RequestHeaderFieldsTooLarge(data?) — 431 Request Header Fields Too Large.
  • UnavailableForLegalReasons(data?) — 451 Unavailable For Legal Reasons.
ts
1app.GET('/private', async (_ctx, reply) => {2  return reply.Unauthorized({ error: 'Authentication required' })3})4 5app.GET('/admin', async (_ctx, reply) => {6  return reply.Forbidden({ error: 'Insufficient permissions' })7})8 9app.GET('/missing', async (_ctx, reply) => {10  return reply.NotFound({ error: 'Resource not found' })11})12 13app.POST('/users', async (_ctx, reply) => {14  return reply.Conflict({ error: 'Email already exists' })15})

5xx — Server error responses

These helpers represent failures on the server or in an upstream service.

ts
1reply.InternalServerError(data?)2reply.NotImplemented(data?)3reply.BadGateway(data?)4reply.ServiceUnavailable(data?)5reply.GatewayTimeout(data?)6reply.HTTPVersionNotSupported(data?)7reply.VariantAlsoNegotiates(data?)8reply.InsufficientStorage(data?)9reply.LoopDetected(data?)10reply.NotExtended(data?)11reply.NetworkAuthenticationRequired(data?)
  • InternalServerError(data?) — 500 Internal Server Error. Default: { error: 'Internal Server Error' }.
  • NotImplemented(data?) — 501 Not Implemented.
  • BadGateway(data?) — 502 Bad Gateway.
  • ServiceUnavailable(data?) — 503 Service Unavailable.
  • GatewayTimeout(data?) — 504 Gateway Timeout.
  • HTTPVersionNotSupported(data?) — 505 HTTP Version Not Supported.
  • VariantAlsoNegotiates(data?) — 506 Variant Also Negotiates.
  • InsufficientStorage(data?) — 507 Insufficient Storage.
  • LoopDetected(data?) — 508 Loop Detected.
  • NotExtended(data?) — 510 Not Extended.
  • NetworkAuthenticationRequired(data?) — 511 Network Authentication Required.
ts
1app.GET('/service', async (_ctx, reply) => {2  return reply.ServiceUnavailable({ error: 'Service temporarily unavailable' })3})

6. Understanding response helper types

The most important TypeScript distinction is whether a method returns Reply or Response.

  • send(body: string): Response
  • json(data: unknown, status?: number): Response
  • status(code: number): Reply
  • header(name: string, value: string): Reply
  • OK(data?: unknown): Response
  • Created(data?: unknown): Response
  • NoContent(): Response

This means you can continue chaining after status()and header(), but not after a method that already returns a Response.

ts
1// Correct: status() returns Reply,2// so json() can be called next.3return reply.status(201).json({ id: 1 })4 5// Correct: header() returns Reply,6// so Created() can be called next.7return reply.header('x-id', '1').Created({ id: 1 })8 9// Incorrect: Created() returns Response,10// which does not have the Reply interface.11return reply.Created({ id: 1 }).header('x-id', '1')

7. Returning a Response is required

Every route handler must return a valid Fetch API Response object. Calling a reply helper without returning its result does not complete the handler correctly.

ts
1// Correct2app.GET('/correct', async (_ctx, reply) => {3  return reply.OK({ success: true })4})5 6// Also correct7app.GET('/correct-2', async (_ctx, reply) => {8  const response = reply.Created({ id: 1 })9  return response10})11 12// Incorrect13app.GET('/incorrect', async (_ctx, reply) => {14  reply.OK({ success: true })15})

The HTTP server checks the handler result using instanceof Response. If the handler returns undefined or another non-Response value, LykosJS logs an error and passes the failure to its error handler, resulting in an HTTP 500 response.

Do not return plain objects directly
Returning { success: true } is not equivalent to returning reply.OK({ success: true }). The handler must return an actual Response.

8. Complete practical example

The following example combines route parameters, query parameters, typed JSON input, request headers and response helpers.

ts
1interface UpdateUserDto {2  name: string3  email: string4}5 6app.PUT('/users/:id', async (ctx, reply) => {7  const id = Number(ctx.params.id)8 9  if (!Number.isInteger(id) || id <= 0) {10    return reply.BadRequest({ error: 'Invalid user ID' })11  }12 13  const payload = await ctx.json<UpdateUserDto>()14 15  if (!payload.name || !payload.email) {16    return reply.UnprocessableContent({17      error: 'Name and email are required',18    })19  }20 21  const requestId = ctx.headers.get('x-request-id')22 23  return reply24    .header('x-request-id', requestId ?? 'generated')25    .OK({26      id,27      name: payload.name,28      email: payload.email,29    })30})

This example demonstrates the intended flow: read and interpret request data, perform application-level checks, and return an explicit HTTP response.

9. Common TypeScript mistakes

These are common mistakes to avoid when using the context and reply APIs.

ts
1// Mistake 1: get() can return null2const page: string = ctx.query.get('page')3 4// Correct5const page: string | null = ctx.query.get('page')6 7// Mistake 2: route parameters are strings8const id: number = ctx.params.id9 10// Correct11const id = Number(ctx.params.id)12 13// Mistake 3: json() defaults to unknown14const payload = await ctx.json()15payload.name // TypeScript error: payload is unknown16 17// Correct: provide the expected type18const payload = await ctx.json<{ name: string }>()19payload.name20 21// Mistake 4: FormData values are not always strings22const name: string = form.get('name')23 24// Correct: handle string | File | null25const name = form.get('name')26if (typeof name === 'string') {27  console.log(name)28}29 30// Mistake 5: user is optional31const userId: string = ctx.user.id32 33// Correct34if (!ctx.user) {35  return reply.Unauthorized()36}37const userId = ctx.user.id38 39// Mistake 6: reply helpers return Response40reply.OK({ success: true }).header('x-id', '1')41 42// Correct43return reply.header('x-id', '1').OK({ success: true })44 45// Mistake 7: status() does not return Response46return reply.status(201)47 48// Correct49return reply.status(201).json({ created: true })

10. Important implementation details

  • Context.request, method, url, path, params, query and headers are readonly properties in the TypeScript interface.
  • user and auth are optional and are not initialized by the HTTP server.
  • json<T>() defaults to unknown. Its generic does not perform runtime validation.
  • formData() returns Promise<FormData>. Individual entries can be strings or files.
  • text() returns Promise<string>.
  • send() accepts a string body and sets a plain-text Content-Type when no custom Content-Type is supplied.
  • json() returns a JSON Response and uses the current configured status unless an explicit status is supplied.
  • status() and header() return Reply, enabling method chaining.
  • Named status helpers return Response directly and use their predefined status codes.
  • JSON response bodies cannot be used with status codes204, 205 and 304.
  • Response status validation requires an integer between200 and 599.
  • Every handler must return an actual Response.
The core rule
Think of ctx as the source of incoming request data, and reply as the tool for creating outgoing responses. Read from the context, process your application logic, and always return a Response.