Controllers and handlers
A controller is a class decorated with @Controller(). Each handler in it implements one endpoint declared with @navios/builder; how to write the declarations is covered in Declaring endpoints.
Controllers are singletons. Navios creates each one once at start-up, so nothing is constructed per request, and per-request data comes from the request context passed to every handler.
Handlers
A handler is a method decorated with @Endpoint(declaration). This page adds two endpoints to the example:
list and remove are two more methods on UsersService.
- The first parameter is annotated with
HandlerParams<typeof endpoint>. TypeScript does not infer a method's parameter types from a decorator, so the annotation is needed. - The second parameter,
ctx: RequestContext, is optional. A handler that needs neither takes no parameters. - No return annotation is needed.
@Endpointchecks the method against the declaration. - The method may be
asyncor not.
@Endpoint is the only handler decorator. It serves every kind of declaration: JSON, response: 'void', text, binary, streams and multipart bodies.
What a handler receives
HandlerParams<typeof endpoint> has a key for each part the declaration has:
The values are schema outputs. listUsers above declares limit with z.number().default(20), so the client may send ?limit=5 or nothing, and the handler always receives a number. The table in Sharing with Navios Server compares this with what the client passes.
Text that stands for something else
A query string, URL parameters and the fields of a multipart body are text. Before validation the server gives each field the form its schema describes:
- Only text that is exactly such a value is converted: the numeral of a JSON number,
trueorfalse, the JSON of an object. Anything else (?page=,?page=1x,?draft=1) reaches the schema as it was sent, and fails there. - A field that may be a string is left alone, and so is one about which the schema says nothing, such as
z.any()orz.preprocess(). - A repeated parameter of a field that is not an array stays a list, and fails.
- The elements of an array are converted the same way.
- A required array with a fallback of its own (
.catch()) is left to it when nothing was sent. - In a multipart body, where
nullcannot be written, the empty text that the Builder client sends for it isnullfor a field, or an element, that may benulland not a string: a nullable number, boolean, object, array or file. A query string and URL parameters have nonull; the client leaves it out.
This needs a schema library that implements Standard JSON Schema, such as Zod 4 or ArkType. Schemas of another library receive the text. Do not use z.coerce.boolean() for it: it turns "false" into true.
Request bodies
A body is decoded by its content type, after guards have passed, and only for an endpoint with a requestSchema:
A body is UTF-8. Malformed JSON, and JSON with a __proto__ or constructor.prototype key, is a 400 with source: 'body'. Because a body is never taken for JSON unless its content type says so, a page of another origin cannot send JSON without a CORS preflight.
An endpoint that needs the bytes themselves reads them with ctx.rawBody().
What a handler returns
The last three rows are covered in Streams and server-sent events.
Response headers and cookies are set through ctx.reply, as getUser does above. The status is never set there: it comes from the declaration.
Declared statuses
reply(status, body) answers with a specific status. The status must be listed in the endpoint's responses or errorSchema, and the body must match the schema for it.
- An endpoint declared with
responsesmust returnreply(). A bare value is a compile error and, at run time, a 500. - A status mapped to
nullinresponseshas no body:reply(204). reply()with a status the endpoint does not declare is a compile error and, at run time, a 500 whose log message lists the declared statuses.
Declared error bodies
errorSchema lists the error statuses an endpoint can answer with and the body of each. There are two ways to send one.
Prefer reply() in a handler. Throwing is for code that cannot return a response, such as a service several calls deep. What happens to an exception whose status is not in errorSchema is described in Errors.
What @Endpoint checks
@Endpoint is a compile error when the method does not fit the declaration:
- a parameter type that is not the declared one,
- a returned value of the wrong shape,
reply()with a status the endpoint does not declare, or with the wrong body for that status,- a bare value from an endpoint declared with
responses, - a value that is not a stream from a
response: 'stream'endpoint.
Literal types are widened in this check: a field declared as 'low' | 'high' is checked as string. TypeScript does not pass an expected type into the body of a decorated method, so return { priority: 'high' } is inferred as { priority: string }, and a check against the literal type would reject correct code.
To have literal values checked too, annotate the return type with HandlerResult<typeof endpoint>:
Without the annotation, a wrong literal is still caught at run time by response validation.
Validation
Both directions are validated against the declaration, with whichever Standard Schema library wrote the schemas.
Requests. URL parameters (when the declaration has a urlParamsSchema), then the query, then the body. A declaration that carries a cookiesSchema or a headersSchema has its cookies validated before the URL parameters and its headers between the query and the body. The body is read from the connection only after guards have passed and the earlier parts are valid. A failure answers 400 with a validation error body and the handler does not run.
Headers and cookies are not validated: declareEndpoint has no schema option for them, so read them from ctx.headers and ctx.cookies. @navios/server does validate a headersSchema and a cookiesSchema when a declaration's config carries them, reporting failures with source: 'headers' or 'cookies', but the handler types do not include the results.
Responses. A JSON body is validated against the schema for its status before it is sent. This removes fields the schema does not declare, which keeps internal fields such as a password hash from leaking. A body that does not match its schema is a 500, and the error is logged. text, blob and stream responses are not validated.
Response validation can be switched off with the validateResponses application option.
Controller options
Guards, interceptors and attributes can be attached to a whole controller or to one handler.
@Controller accepts guards, interceptors and attributes. On a handler, @UseGuards, @UseInterceptors and attribute decorators go next to @Endpoint, in any order. Guards and interceptors and Attributes explain what they do.
A controller has no path of its own. Path prefixes belong to modules.
Handlers without decorators
handler() defines a handler as a class field instead of a decorated method. It produces the same route as @Endpoint, and one controller can mix both.
- Both arguments of the function are inferred from the declaration. Nothing is annotated.
- The return value is checked against the declaration including literal values, because TypeScript passes the expected type into the function.
thisinside an arrow function is the controller, soinject()fields work. Afunctionor anasync function*passed tohandler()has nothis; to stream from controller fields, return a generator from an arrow function:handler(tailLogs, ({ params }) => this.follow(params.service)).- An options object between the endpoint and the function takes
guards,interceptorsandattributesfor that handler. @UseGuards,@UseInterceptorsand attribute decorators also work on ahandler()field. Guards and interceptors from decorators run before those from the options, and when the same attribute is set both ways the value from the options wins.- Navios finds these handlers on the controller instance, so the field must be assigned by the time the constructor finishes. A static property is not found.
Use handler() when you prefer inferred parameters to the HandlerParams annotation, or when the code is built without a decorator transform. For the second case, registerController(Class, options?) and registerModule(Class, options?) replace @Controller and @Module and take the same options, and registerInjectable does the same for services:
Route rules checked at start-up
Navios builds the route table during init() and rejects it when a rule is broken. The application does not start, and the error names the classes involved.
One rule is checked earlier, when the class is defined: a method serves one endpoint. A second @Endpoint with another declaration on the same method throws getUser already serves GET /users/$userId; a method can serve one endpoint. A method that overrides an inherited one may serve another endpoint; the guards, interceptors and attributes of the inherited one stay.
After init(), app.routes() returns every route as a RouteInfo: method, path, endpoint (the declaration's config), module, controller, handlerName (the name of the method or of the handler() field), guards, interceptors and attributes. ctx.route is the same object for the route being handled.