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
  webSocket: true, // false turns off upgradeWebSocket (default true)
  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
  webSocket: true, // false desliga o upgradeWebSocket (padrão true)
  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

WebSocket

The upgrade request goes through the app like any request: hooks, middleware, access and validation run before the 101. The route handler accepts it with upgradeWebSocket(ctx, handlers, options), so an anonymous client gets its 401 before the handshake. The frame layer (RFC 6455) is native, with no dependency.

A requisição de upgrade passa pelo app como qualquer requisição: hooks, middleware, access e validação rodam antes do 101. O handler da rota aceita com upgradeWebSocket(ctx, handlers, options), então um cliente anônimo recebe 401 antes do handshake. A camada de quadros (RFC 6455) é nativa, sem dependência.

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

// anonymous clients get 401 before the handshake
const live = createModule('', { access: 'authenticated' }).get('/ws', {
  handler: (ctx) =>
    upgradeWebSocket(
      ctx,
      {
        open: (ws) => ws.send('hello ' + ctx.principal.id),
        message: (ws, data) => ws.send(typeof data === 'string' ? data.toUpperCase() : data),
        close: (ws, code, reason) => console.log('closed', code, reason),
      },
      { maxPayload: 64 * 1024, origin: ['https://app.example.com'] },
    ),
});

serve(createApp({ authenticate: findUser }).register(live), { port: 3000 });
import { createApp, createModule } from '@tupik/core';
import { serve, upgradeWebSocket } from '@tupik/node';

// cliente anônimo recebe 401 antes do handshake
const live = createModule('', { access: 'authenticated' }).get('/ws', {
  handler: (ctx) =>
    upgradeWebSocket(
      ctx,
      {
        open: (ws) => ws.send('hello ' + ctx.principal.id),
        message: (ws, data) => ws.send(typeof data === 'string' ? data.toUpperCase() : data),
        close: (ws, code, reason) => console.log('closed', code, reason),
      },
      { maxPayload: 64 * 1024, origin: ['https://app.example.com'] },
    ),
});

serve(createApp({ authenticate: findUser }).register(live), { port: 3000 });

HandlersHandlers

  • open(ws): The 101 response is out and the socket is open.A resposta 101 saiu e o socket está aberto.
  • message(ws, data): A complete message: string for text, Uint8Array for binary.Uma mensagem completa: string para texto, Uint8Array para binário.
  • close(ws, code, reason): Called once when the socket is gone; code is 1006 when no close frame arrived.Chamado uma vez quando o socket some; code é 1006 quando nenhum quadro de fechamento chegou.
  • error(ws, error): A handler threw and the connection closes with 1011. Default: the driver onError.Um handler lançou erro e a conexão fecha com 1011. Padrão: o onError do driver.

OptionsOpções

OptionOpção DefaultPadrão BehaviorComportamento
maxPayload 1 MiB Largest message after joining fragments, checked on each frame header before buffering. Bigger messages close with 1009.Maior mensagem depois de juntar os fragmentos, conferida no cabeçalho de cada quadro antes de bufferizar. Mensagens maiores fecham com 1009.
origin undefined A list of allowed Origin values (exact match) or a function. Other origins get 403 before the upgrade. Unset means no check: rely on access, SameSite cookies or a token.Lista de valores de Origin permitidos (igualdade exata) ou uma função. Outras origens recebem 403 antes do upgrade. Sem ela não há checagem: conte com o access, cookies SameSite ou um token.
idleTimeout 120 s A connection with no traffic in either direction for this long closes with 1001; 0 disables it.Conexão sem tráfego em nenhum sentido por esse tempo fecha com 1001; 0 desliga.
closeTimeout 5 s How long to wait for the client close frame before dropping the socket.Quanto esperar pelo quadro de fechamento do cliente antes de derrubar o socket.
protocols [] Subprotocols the server speaks; the first one the client offers wins (Sec-WebSocket-Protocol).Subprotocolos que o servidor fala; vence o primeiro que o cliente oferece (Sec-WebSocket-Protocol).

Limits and your own serverLimites e servidor próprio

  • Text, binary, fragmented messages, ping/pong and the closing handshake. Invalid UTF-8 closes with 1007, protocol errors with 1002.
  • No permessage-deflate: frames are never compressed.
  • A plain HTTP request to the route, or the same route on any runtime other than @tupik/node, gets 426 Upgrade Required.
  • server.close() sends 1001 to open sockets. serve(app, { webSocket: false }) turns the feature off, and the driver also steps aside when you attach your own 'upgrade' listener.
  • With your own node:http server, call dispatchUpgrade(app, req, socket, head) from its 'upgrade' event.
  • Texto, binário, mensagens fragmentadas, ping/pong e o handshake de fechamento. UTF-8 inválido fecha com 1007, erro de protocolo com 1002.
  • Sem permessage-deflate: os quadros nunca são comprimidos.
  • Uma requisição HTTP comum para a rota, ou a mesma rota em qualquer runtime que não o @tupik/node, recebe 426 Upgrade Required.
  • server.close() manda 1001 aos sockets abertos. serve(app, { webSocket: false }) desliga o recurso, e o driver também sai do caminho quando você liga o seu próprio listener de 'upgrade'.
  • Com o seu próprio servidor node:http, chame dispatchUpgrade(app, req, socket, head) no evento 'upgrade' dele.
custom-server.ts
import { createServer } from 'node:http';
import { dispatch, dispatchUpgrade } from '@tupik/node';

const server = createServer((req, res) => void dispatch(app, req, res));
// the upgrade runs the same pipeline (hooks, middleware, access)
server.on('upgrade', (req, socket, head) => void dispatchUpgrade(app, req, socket, head));
server.listen(3000);
import { createServer } from 'node:http';
import { dispatch, dispatchUpgrade } from '@tupik/node';

const server = createServer((req, res) => void dispatch(app, req, res));
// o upgrade passa pelo mesmo pipeline (hooks, middleware, access)
server.on('upgrade', (req, socket, head) => void dispatchUpgrade(app, req, socket, head));
server.listen(3000);

The realtime example uses this upgrade next to SSE, and createWebSocket reconnects on the client side.

O exemplo realtime usa esse upgrade ao lado do SSE, e o createWebSocket reconecta do lado do cliente.

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