Docs/Features
Hooks
Hooks (3.12.0) are functions Alado calls at fixed points of every request: for a request id, an access log, metrics, a maintenance switch, a cache. There is no next(): a hook returns nothing to let the request go on, or a response to answer it.
| Hook | When | It may |
|---|---|---|
onRequest |
Before routing: for every request, also unknown paths, the docs and CORS preflights | Answer the request (return a response, or throw an HttpError) |
beforeHandler |
After authentication, access control and validation, right before the handler | Answer the request: the handler is then not called |
beforeSend |
Before a response is written: the handler's, a hook's, or an error | Change statusCode, headers and body, or return another response |
onFinished |
After the response was written to its end, or the connection ended first | Only observe: it is not awaited |
Hooks of the server
import { randomUUID } from 'node:crypto';
import { initializeApplication, HttpError } from 'alado';
const app = initializeApplication({
serverOptions: {
port: 3000,
hooks: {
onRequest: (req) => {
req.state.id = req.headers['x-request-id'] || randomUUID();
if (maintenance.on) {
throw new HttpError(503, 'Maintenance'); // or: return { statusCode: 503, body: { message: 'Maintenance' } }
}
},
beforeSend: (req, res) => {
res.headers = { ...res.headers, 'X-Request-Id': req.state.id };
},
onFinished: (req, { statusCode, durationMs, aborted }) => {
// req.route.path is the path as registered ("/users/:id"), so one label per route
metrics.observe(req.method, req.route?.path ?? 'unmatched', statusCode, durationMs);
console.log(req.state.id, req.method, req.url, statusCode, `${durationMs.toFixed(1)} ms`, aborted ? 'aborted' : '');
},
},
},
controllers: [UserController],
});Each hook is one function or a list of them, run in order.
Hooks of a route
A route adds its own with @hooks; they run after the server's hooks of the same kind:
import { get, hooks, defineRequest, Request } from 'alado';
@get('/reports/:id')
@hooks({
beforeHandler: async (req: Request) => {
const cached = await cache.get(req.url);
return cached ? { statusCode: 200, body: cached } : undefined; // a response: the handler is not called
},
})
@defineRequest({ path: ReportIdDto })
async getReport(req: Request) { ... }@hooks is applied once per method and goes below the HTTP method decorator, as @withAuth does. A route has no onRequest: it runs before a route is known. Without decorators the same object is hooks in the route context (app.get(path, { ..., hooks }, handler)).
req.state and req.route
req.stateis an empty object for every request, also without hooks. Alado never reads it: what a hook leaves there is there for the hooks after it and for the handler.req.routeis{ method, path }of the route that answers,pathas registered (/users/:id). It is unset inonRequest, and inbeforeSendandonFinishedwhen no route matched (404,405, the docs). AHEADrequest answered by aGETroute has that route'sGET.
What each hook sees
onRequestgets the request withrequest,ip,origin,method,url,headersandstateonly:path,query,bodyandauthare filled in later, for the route.beforeHandlergets the request the handler would get: authenticated, validated, with its body.beforeSendgets the request and a copy of the response, so a handler that returns the same object for every request is not changed by it. It runs for API responses, errors included (404,405, a refused or invalid request, an exception), but not for the docs, CORS preflights, and the503ofhandlerTimeoutMs, which is written from a timer.onFinishedgets the request and{ statusCode, durationMs, aborted }(FinishedInfo), once for every request, the onesbeforeSenddoes not see included.statusCodeis0andabortedistruewhen the client left before a response.
Errors, timeouts and cost
- Errors. A hook that throws is handled as a handler that throws: an
HttpError(or{ statusCode, message }) is the answer, anything else is500and goes to the logger. AbeforeSendhook that fails is answered with500without running the hooks again. AnonFinishedhook that throws, or whose promise rejects, is logged and changes nothing. - Timeouts.
handlerTimeoutMscovers thebeforeHandlerhooks and the handler together.onRequestandbeforeSendhave no limit of their own: keep them short. - Startup. Hooks are checked when the server is created and when a route is defined: a value that is not a function, or a name that is not a hook (
onFinish), throws there and not on the first request. - Cost. Without hooks a request does no extra work. With hooks, only the kinds that are set run; the duration is measured only when there is an
onFinishedhook.
The types are exported from 'alado': Hooks, RouteHooks, OnRequestHook, BeforeHandlerHook, BeforeSendHook, OnFinishedHook, FinishedInfo, RouteInfo. See Main Contracts.