aladov3.13.0

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

src/main.ts
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:

TypeScript
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.state is 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.route is { method, path } of the route that answers, path as registered (/users/:id). It is unset in onRequest, and in beforeSend and onFinished when no route matched (404, 405, the docs). A HEAD request answered by a GET route has that route's GET.

What each hook sees

  • onRequest gets the request with request, ip, origin, method, url, headers and state only: path, query, body and auth are filled in later, for the route.
  • beforeHandler gets the request the handler would get: authenticated, validated, with its body.
  • beforeSend gets 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 the 503 of handlerTimeoutMs, which is written from a timer.
  • onFinished gets the request and { statusCode, durationMs, aborted } (FinishedInfo), once for every request, the ones beforeSend does not see included. statusCode is 0 and aborted is true when 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 is 500 and goes to the logger. A beforeSend hook that fails is answered with 500 without running the hooks again. An onFinished hook that throws, or whose promise rejects, is logged and changes nothing.
  • Timeouts. handlerTimeoutMs covers the beforeHandler hooks and the handler together. onRequest and beforeSend have 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 onFinished hook.

The types are exported from 'alado': Hooks, RouteHooks, OnRequestHook, BeforeHandlerHook, BeforeSendHook, OnFinishedHook, FinishedInfo, RouteInfo. See Main Contracts.