aladov3.13.0

Docs/Application

Application Setup

initializeApplication

TypeScript
import { initializeApplication } from 'alado';
import { UserController } from '@user';

const app = initializeApplication({
  serverOptions: {
    port: 3000,
    appId: 'my-api', // optional — used to scope multi-app setups
    logger: {
      log: console.log,
      error: console.error,
    },
  },
  controllers: [UserController],
});

app.start((error) => (error ? console.error('Cannot start', error) : console.log('Started')));
app.stop(() => console.log('Stopped'));

The start() callback is called once: without an argument when the server listens, with the error when it cannot (EADDRINUSE, EACCES). Without a callback such an error is emitted by the returned http.Server. The stop() callback is always called, also when the server was not listening.

Requests that are still running when stop() is called are answered first, with Connection: close: their connections are not kept alive, so stop() returns as soon as the last of them is answered (3.11.1). Before, it waited for keepAliveTimeout after each of them: 5 seconds by default, a minute or more where the value is raised for a load balancer.

Passing options to controller constructors

TypeScript
initializeApplication({
  serverOptions: { port: 3000 },
  controllers: [
    {
      controller: UserController,
      options: [{ service: UserService }], // passed to new UserController(...)
    },
  ],
});

Request limits, proxies and route matching

TypeScript
initializeApplication({
  serverOptions: {
    port: 3000,
    maxBodySizeBytes: 5 * 1024 * 1024, // default 1 MB; 0 removes the limit (text bodies stay capped at ~512 MB)
    trustProxy: 1, // read request.ip from X-Forwarded-For behind one proxy; default false
    caseSensitiveRoutes: true, // default: /Admin does not match /admin
    handlerTimeoutMs: 120_000, // default 60 s; 0: no limit
    bodyIdleTimeoutMs: 30_000, // default 30 s without body data; 0: no limit
    securityHeaders: true, // HSTS, Referrer-Policy, X-Frame-Options, CSP frame-ancestors; default none
    rateLimit: { requests: 100, windowMs: 60_000 }, // per IP address, over it 429; default none
  },
  controllers: [UserController],
});

A route can set its own body limit, which replaces maxBodySizeBytes for that route (0 removes it): raise it on an upload route rather than for the whole server. Multipart bodies hold at most parsing.maxParts parts (default 1000).

TypeScript
@post('/user/:id/avatar', { maxBodySizeBytes: 20 * 1024 * 1024 })

See Security Defaults for what each option protects against, and Rate Limiting for rateLimit (3.13.0), per endpoint and per route.

Timeouts

A handler has 60 seconds to answer by default (handlerTimeoutMs); a slower one gets 503 Service Unavailable, the connection is closed and the timeout is logged, so a handler that never answers cannot hold its connection and memory for good. Before 3.9.2 there was no limit: set handlerTimeoutMs: 0 to keep that, or a larger value when handlers legitimately take longer (reports, exports). The limit covers the time until the handler returns its response, the beforeHandler hooks before it included; a stream body it returns is sent after that without a limit. Whatever the handler does after the timeout is ignored; it is not cancelled, so make slow work cancellable where it matters.

A request body that stops arriving gets 408 Request body timeout after 30 seconds without data (bodyIdleTimeoutMs, 0 for no limit, 3.9.3) and the connection is closed, so a client that sends half an upload and stalls does not hold the buffered part for long. The timer restarts with every chunk: a slow but steady upload is not cut off.

Both limits are kept by one coarse timer per server, not a timer per request (3.9.18; from 3.9.2 to 3.9.17 a timer per request cost up to 20% of a small route). It ticks every twentieth of the limit, from 5 ms to 1 s, so a timeout fires between the limit and the limit plus one tick (60 to 61 s for the default handler limit), never earlier.

The total time a client gets to send a request is Node's: requestTimeout (300 s), headersTimeout (60 s) and keepAliveTimeout (5 s) can be changed through serverOptions, e.g. serverOptions: { requestTimeout: 30_000 }.

Response headers

Every response carries X-Content-Type-Options: nosniff, so a browser never guesses a type from the bytes of a JSON or text response. A value set by a handler, or in the headers server option (headers added to every response), replaces it.

securityHeaders: true (3.9.4) adds a preset suited to an API to every response, errors included: Strict-Transport-Security: max-age=31536000; includeSubDomains (browsers ignore it over plain HTTP, so it is safe behind a TLS proxy), Referrer-Policy: no-referrer, X-Frame-Options: DENY and Content-Security-Policy: frame-ancestors 'none'. An object changes the preset: a string replaces or adds a header, false leaves one out, names in any letter case. A header of the same name in headers or set by a handler wins. The default is none. A fuller Content-Security-Policy depends on what a page loads, and Cache-Control: no-store on what may be cached, so both are left to the application.

TypeScript
serverOptions: {
  securityHeaders: { 'Strict-Transport-Security': false, 'Permissions-Policy': 'camera=()' },
}

Hooks

serverOptions.hooks takes functions run at fixed points of every request (3.12.0): onRequest before routing, beforeHandler right before the handler, beforeSend before a response is written and onFinished after it. See Hooks.

TypeScript
initializeApplication({
  serverOptions: {
    port: 3000,
    hooks: {
      onFinished: (req, { statusCode, durationMs }) => console.log(req.method, req.url, statusCode, `${durationMs.toFixed(1)} ms`),
    },
  },
  controllers: [UserController],
});

Logging

Errors go to serverOptions.logger (default: console):

  • An internal failure (a handler or an auth handler that throws, a stream that breaks, response headers Node refuses) is always logged with logger.error. The client only gets 500 Internal Server Error, so the log is the one place the cause shows up.
  • A handler that returns no usable response (a forgotten return, a statusCode that is not a number from 100 to 999) is such a failure. Since 3.11.4 the log names the route and what came back: Handler of GET /orders/7 returned undefined instead of a response ({ statusCode, headers?, body? }).
  • An error the client caused (a thrown error with a 4xx statusCode, an auth handler refusing credentials with a 4xx statusCode, an invalid or oversized body, a client that disconnects mid-response) is logged only with verbose: true.
  • A logger without error gets these through logger.log.
  • Logger methods may be sync or async. A returned promise is not awaited (a slow logger never delays a response), only watched for rejection.
  • If the logger itself fails, by throwing or with a rejected promise (a transport that is down), its error and the error it was logging both go to console.error, and the request is still answered. A logger can never end the process.
TypeScript
initializeApplication({
  serverOptions: {
    port: 3000,
    logger: { log: console.log, error: console.error },
    verbose: true, // also log 4xx errors
  },
  controllers: [UserController],
});

CORS

TypeScript
initializeApplication({
  serverOptions: {
    port: 3000,
    cors: {
      enable: true,
      allowedOrigin: ['https://app.example.com'], // one origin, a list, '*' (alone or in the list), or a function returning one; default '*'
      allowedHeaders: ['authorization', 'content-type'], // default ['Content-Type', 'Authorization'], [] for none
      exposeHeaders: ['x-total-count'],
      allowedCredentials: true,
      maxAge: 600, // preflight cache in seconds; default 86400, 0 disables caching
    },
  },
  controllers: [UserController],
});

allowedOrigin decides the Access-Control-Allow-Origin a browser gets:

allowedOrigin Origin listed by name Any other origin
'https://a.com' (one origin) https://a.com https://a.com (the browser refuses it)
['https://a.com', 'https://b.com'] that origin no header (refused)
'*', or a list containing '*' that origin *
'*' with allowedCredentials: true that origin its own Origin, sent back

Browsers refuse * on credentialed requests, so with allowedCredentials the request's Origin is sent back instead (Vary: Origin tells caches the answer depends on it). Any website can then send requests with the user's cookies and read the answers: when a cookie carries the session, list the origins instead. With Authorization headers the risk is small, since browsers do not attach them on their own. The null origin (sandboxed frames, file: pages) is only allowed when listed by name.

CORS for many partners

When the callers are other companies' web apps, too many or unknown to list, choose by how they authenticate:

  • Tokens or API keys (Authorization, X-Api-Key): the calling code adds them, a foreign site does not have them. allowedOrigin: '*' without allowedCredentials lets any origin call the API, and is safe: no credential is sent on its own.
  • Cookies with SameSite=Lax or Strict: browsers leave them out of cross-site requests, so '*' with allowedCredentials sends back each Origin without exposing a session.
  • Cross-site cookies (SameSite=None): allow only your partners' origins, from a list that can change while the server runs. Since 3.9.5 allowedOrigin takes a function returning the origins (or '*') as they are now (CorsOriginList):
TypeScript
let partnerOrigins: string[] = await PartnerRegistry.origins();
setInterval(async () => (partnerOrigins = await PartnerRegistry.origins()), 60_000).unref();

initializeApplication({
  serverOptions: {
    port: 3000,
    cors: { enable: true, allowedCredentials: true, allowedOrigin: () => partnerOrigins },
  },
  controllers: [ApiController],
});

The function is called synchronously for each CORS request, so it should return a value kept up to date elsewhere, never look one up. A function that throws or returns something other than an origin or a list of them (a promise included) allows no origin and is logged; the request itself is still answered. Every answer carries Vary: Origin.

allowedHeaders lists the request headers browsers may send cross-origin. Left out, it is ['Content-Type', 'Authorization']: the two a JSON API call needs (both make the browser send a preflight first). Add your own headers (X-Api-Key, X-Request-Id) to the list; [] allows none. Empty header lists are not sent, and Access-Control-Allow-Credentials is sent only when it is true.

CORS never refuses a request: it only tells browsers which pages may read the answer. Requests without an Origin header, from another server or curl, are answered under every setting.

An origin is written as browsers send it: scheme://host[:port] in lower case, without a path or a trailing slash. Anything else (https://app.example.com/, https://App.Example.com) could never match and is refused at startup, with the correct form in the message. maxBodySizeBytes and cors.maxAge must be finite numbers.

Error responses (an invalid body, 413, a failed auth) carry the CORS headers too, so browser clients can read them.

HTTPS

TypeScript
import { readFileSync } from 'fs';

const app = initializeApplication({
  serverOptions: {
    port: 443,
    ssl: {
      cert: readFileSync('/path/to/cert.pem'),
      key: readFileSync('/path/to/key.pem'),
    },
  },
  controllers: [UserController],
});