Documentation menuMenu da documentação

$ cat docs/node.md

Node.jsNode.js

The Node.js driver serves any object with fetch(request) over node:http, on Node.js 22 and 24 (22.12 or newer).O driver Node.js serve qualquer objeto com fetch(request) sobre node:http, em Node.js 22 e 24 (22.12 ou mais novo).

serve()

server.ts
import { createApp, createModule } from '@tupik/core';
import { serve } from '@tupik/node';

const routes = createModule('/api').get('/ping', {
  access: 'public',
  handler: (ctx) => ctx.text('pong'),
});

const server = serve(createApp().register(routes), {
  port: 3000, // 0 picks a free port (default)
  hostname: '127.0.0.1', // default
  bodyLimit: 1024 * 1024, // 1 MiB (default); above it, 413
  onError: (error) => console.error(error), // the client only gets a generic 500
  requestTimeout: 30_000, // also headersTimeout and keepAliveTimeout
});
import { createApp, createModule } from '@tupik/core';
import { serve } from '@tupik/node';

const routes = createModule('/api').get('/ping', {
  access: 'public',
  handler: (ctx) => ctx.text('pong'),
});

const server = serve(createApp().register(routes), {
  port: 3000, // 0 escolhe uma porta livre (padrão)
  hostname: '127.0.0.1', // padrão
  bodyLimit: 1024 * 1024, // 1 MiB (padrão); acima disso, 413
  onError: (error) => console.error(error), // o cliente só recebe 500 genérico
  requestTimeout: 30_000, // também headersTimeout e keepAliveTimeout
});

Request pathCaminho da requisição

  • toWebRequest turns the IncomingMessage into a Request, honoring bodyLimit.
  • sendResponse streams the Response with backpressure through drain (SSE included).
  • If the client disconnects, the request AbortSignal fires and the response stream is cancelled.
  • Multiple Set-Cookie headers are sent separately, without corrupting attributes such as Expires.
  • toWebRequest converte o IncomingMessage em Request, respeitando bodyLimit.
  • sendResponse escreve a Response em streaming, com backpressure via drain (SSE incluso).
  • Se o cliente desconecta, o AbortSignal da requisição dispara e o stream de resposta é cancelado.
  • Múltiplos Set-Cookie são enviados separados, sem corromper atributos como Expires.
custom-server.ts
import { createServer } from 'node:http';
import { dispatch } from '@tupik/node';

// Bring your own server (HTTPS, HTTP/2 compat, tests):
createServer((req, res) => void dispatch(app, req, res)).listen(3000);
import { createServer } from 'node:http';
import { dispatch } from '@tupik/node';

// Use o seu próprio servidor (HTTPS, HTTP/2 compat, testes):
createServer((req, res) => void dispatch(app, req, res)).listen(3000);

Several coresVários núcleos

workers forks node:cluster workers. On Linux each one binds its own socket with SO_REUSEPORT (reusePort: false turns it off). A crashed worker is replaced, and SIGTERM drains in-flight requests for up to shutdownTimeout (10 s). In-memory state (rate limits, caches, sessions) is per worker. Details in performance.

workers cria workers do node:cluster. No Linux cada um abre o próprio socket com SO_REUSEPORT (reusePort: false desliga). Worker que cai é substituído, e o SIGTERM espera as requisições em andamento por até shutdownTimeout (10 s). Estado em memória (rate limit, cache, sessão) é por worker. Detalhes em desempenho.

server.ts
// each worker runs this file again; the same call only listens
serve(app, { port: 3000, workers: 'auto' }); // or a number
// cada worker roda este arquivo de novo; a mesma chamada só escuta
serve(app, { port: 3000, workers: 'auto' }); // ou um número

Fast-path

A body-less GET/HEAD request is answered through a lightweight request object built directly from IncomingMessage, without allocating a native undici Request. Combined with light responses for ctx.json()/text()/html() that carry no custom headers, this is the cheapest path through the driver. The gain is structural; the numbers below are the measured result, not a promise.

Uma requisição GET/HEAD sem corpo é respondida por um objeto de requisição leve, montado direto do IncomingMessage, sem alocar um Request nativo do undici. Somado às respostas leves para ctx.json()/text()/html() sem headers customizados, esse é o caminho mais barato pelo driver. O ganho é estrutural; os números abaixo são o resultado medido, não uma promessa.

Measured throughputThroughput medido

Measured on Node 24.21.0 on 2026-12-01 with autocannon on the same machine, which was under load. Each row carries the command, the connections and the duration.

Medido no Node 24.21.0 em 2026-12-01 com autocannon na mesma máquina, que estava com carga. Cada linha traz o comando, as conexões e a duração.

MeasurementMedição ResultResultado ConditionCondição
Tupik, GET / JSON 26.9k to 29.4k req/s
before and after the driver workantes e depois do trabalho no driver
Node 24.21.0 · Phase 7 before/after run, autocannon, 8 interleaved rounds · 2026-12-01
Tupik, POST with a validated JSON body 9.0k to 12.0k req/s
before vs after Phase 7 (one body stream)antes vs depois da Fase 7 (um stream de corpo)
Node 24.21.0 · Phase 7 before/after run, autocannon, 8 interleaved rounds · 2026-12-01
serve({ workers: 4 }) about 68k req/s
about 26k with one processcerca de 26k com um processo
Node 24.21.0 · autocannon on GET / JSON, Linux with SO_REUSEPORT · 2026-12-01