Reference

Programming languages

Choose TypeScript, Go, Rust or C++ and find syntax, everyday APIs, standard libraries and tools in one place.

Scope and conventions

TypeScript/Node, Go 1.23+, Rust 2024 and C++23: from a first CLI to files, JSON, HTTP, concurrency and testing. Complete programs are labeled; other examples identify their surrounding code/imports. Optional libraries and version requirements are named in each entry.

HTTP & services

Make an HTTP request and check the response

TypeScript

fetch rejects for some transport failures, but an HTTP error response still resolves. Check ok/status before accepting the body.

Fragment

Modern Node/browser API, inside an async function. For large/untrusted bodies, stream with an explicit size limit. A browser also enforces CORS.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const response = await fetch("https://example.com/", {
  signal: AbortSignal.timeout(5000)
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const text = await response.text();

Send a JSON request body

TypeScript

Serialize the body and declare its media type. Status handling remains the caller’s responsibility.

Fragment

Inside an async function. This requires an application implementing POST /items; it is separate from the /health server example.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const response = await fetch("http://127.0.0.1:3000/items", {
  method: "POST", headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ name: "Ada" }),
  signal: AbortSignal.timeout(5000)
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);

A complete small HTTP health endpoint

TypeScript

Node has a built-in HTTP server. This complete program binds a loopback interface and handles one route.

Complete program

Save as a separate main.ts using the project setup. Visit http://127.0.0.1:3000/health. Add your own routes and explicit shutdown policy as the app grows.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import { createServer } from "node:http";

const server = createServer((request, response) => {
  const healthy = request.method === "GET" && request.url === "/health";
  response.writeHead(healthy ? 200 : 404, {
    "Content-Type": "text/plain; charset=utf-8"
  });
  response.end(healthy ? "ok\n" : "not found\n");
});
server.listen(3000, "127.0.0.1");

Set timeouts and cancel HTTP requests: AbortSignal.timeout, http.Client.Timeout, reqwest, cpp-httplib

TypeScript

fetch has no timeout option and no default timeout; you pass an AbortSignal. AbortSignal.timeout(ms) aborts with a TimeoutError DOMException, a caller's AbortController aborts with whatever reason it was given, and AbortSignal.any combines several signals so whichever fires first wins. The signal covers connecting, waiting for headers and reading the body.

Complete program

Complete program. Starts a local server on a free port, so it runs offline.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import type { AddressInfo } from 'node:net';

// A local server: /fast answers at once, /slow never answers.
const server = createServer((request, response) => {
  if (request.url === '/fast') response.end('ok');
});
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const { port } = server.address() as AddressInfo;
const base = `http://127.0.0.1:${port}`;

// A per-request deadline. The signal covers connecting, the headers and reading the body.
const fast = await fetch(`${base}/fast`, { signal: AbortSignal.timeout(1_000) });
assert.equal(await fast.text(), 'ok');

try {
  await fetch(`${base}/slow`, { signal: AbortSignal.timeout(200) });
  assert.fail('expected a timeout');
} catch (error) {
  assert.ok(error instanceof DOMException);
  assert.equal(error.name, 'TimeoutError'); // a deadline, not a caller abort ('AbortError')
  console.log('slow request:', error.name);
}

// Caller cancellation plus a deadline: whichever fires first aborts the request.
const caller = new AbortController();
setTimeout(() => caller.abort(new Error('user navigated away')), 50);
try {
  await fetch(`${base}/slow`, {
    signal: AbortSignal.any([caller.signal, AbortSignal.timeout(5_000)])
  });
  assert.fail('expected an abort');
} catch (error) {
  assert.ok(error instanceof Error);
  console.log('cancelled request:', error.message); // the reason passed to abort()
}

server.closeAllConnections();
server.close();

In practice: give every outbound request a deadline, and combine it with the caller's signal (a request handler, a user action) using AbortSignal.any so the call stops when either the deadline passes or nobody needs the answer any more. Check error.name to tell a timeout from a cancellation.

AbortSignal.timeout needs Node 17.3+, AbortSignal.any Node 20.3+; both are in current browsers.

AbortSignal.timeout measures active time: it pauses in a suspended worker or while a page is in the back-forward cache.

An aborted fetch rejects with signal.reason. A plain abort() gives an AbortError DOMException; a timeout gives TimeoutError.

Undici (Node's fetch) also has its own headers and body timeouts of 300 seconds each; a signal is still the way to set a total deadline.

Serve a small JSON API with routes and path parameters: node:http, ServeMux patterns, axum, cpp-httplib

TypeScript

node:http gives you a request and a response and nothing else: no routing, no path parameters, no body parsing. A router is a list of (method, pattern) pairs matched against url.pathname. The body is a stream of Buffers: collect the bytes with a size limit and decode them once at the end, because a UTF-8 character can be split across two chunks. Map each failure to its status: 404 for an unknown path, 405 with an Allow header for the wrong method, 400 for a malformed path escape or invalid JSON, 413 for an oversized body and 500 for a bug.

Complete program

Complete program. Starts the API on a free port, calls it with fetch and exits.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import assert from 'node:assert/strict';
import { createServer, type IncomingMessage } from 'node:http';
import type { AddressInfo } from 'node:net';

type Item = { id: string; name: string };
type Params = Record<string, string>;
type Result = { status: number; body: unknown; headers?: Record<string, string> };
type Handler = (request: IncomingMessage, params: Params) => Result | Promise<Result>;

// A client mistake with its status code; anything else thrown is a 500.
class HttpError extends Error {
  status: number;
  constructor(status: number, message: string) {
    super(message);
    this.status = status;
  }
}

const items = new Map<string, Item>([['1', { id: '1', name: 'kettle' }]]);
let nextId = 2;

// A tiny router: a method plus a pattern whose ':name' segments become params.
const routes: { method: string; pattern: string[]; handler: Handler }[] = [];
function route(method: string, pattern: string, handler: Handler): void {
  routes.push({ method, pattern: pattern.split('/').filter(Boolean), handler });
}

function match(pattern: string[], pathname: string): Params | null {
  const parts = pathname.split('/').filter(Boolean);
  if (parts.length !== pattern.length) return null;
  const params: Params = {};
  for (const [i, segment] of pattern.entries()) {
    if (!segment.startsWith(':')) {
      if (segment !== parts[i]) return null;
    } else {
      try {
        params[segment.slice(1)] = decodeURIComponent(parts[i]);
      } catch {
        throw new HttpError(400, 'malformed escape in path'); // URIError, e.g. %E0%A4%A
      }
    }
  }
  return params;
}

// Collect raw bytes (a UTF-8 character can span two chunks), cap the size, then decode.
async function readJson(request: IncomingMessage, limit = 64 * 1024): Promise<unknown> {
  const chunks: Buffer[] = [];
  let size = 0;
  for await (const chunk of request) {
    size += chunk.length;
    if (size > limit) throw new HttpError(413, 'body too large');
    chunks.push(chunk);
  }
  try {
    // fatal: true rejects invalid UTF-8 instead of substituting U+FFFD.
    return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks)));
  } catch {
    throw new HttpError(400, 'body must be UTF-8 JSON');
  }
}

route('GET', '/items/:id', (_request, { id }) => {
  const item = items.get(id);
  return item ? { status: 200, body: item } : { status: 404, body: { error: 'not found' } };
});

route('POST', '/items', async (request) => {
  const input = await readJson(request);
  if (typeof input !== 'object' || input === null || !('name' in input) || typeof input.name !== 'string') {
    return { status: 400, body: { error: 'name must be a string' } };
  }
  const item = { id: String(nextId++), name: input.name };
  items.set(item.id, item);
  return { status: 201, body: item };
});

async function dispatch(request: IncomingMessage): Promise<Result> {
  // Accept only origin-form targets ("/path?query"); URL.parse returns null instead of throwing.
  const target = request.url ?? '';
  const url = target.startsWith('/') ? URL.parse(`http://localhost${target}`) : null;
  if (url === null) throw new HttpError(400, 'bad request target');
  const wanted = request.method === 'HEAD' ? 'GET' : request.method; // HEAD runs GET; Node drops the body
  const allowed: string[] = [];
  for (const { method, pattern, handler } of routes) {
    const params = match(pattern, url.pathname);
    if (params === null) continue;
    if (method === wanted) return handler(request, params);
    allowed.push(method === 'GET' ? 'GET, HEAD' : method);
  }
  if (allowed.length === 0) return { status: 404, body: { error: 'no route' } };
  return { status: 405, body: { error: 'method not allowed' }, headers: { allow: allowed.join(', ') } };
}

const server = createServer(async (request, response) => {
  let result: Result;
  try {
    result = await dispatch(request);
  } catch (error) {
    if ((error as NodeJS.ErrnoException).code === 'ECONNRESET') return; // the client went away
    if (!(error instanceof HttpError)) console.error(error);
    result = error instanceof HttpError
      ? { status: error.status, body: { error: error.message } }
      : { status: 500, body: { error: 'internal error' } };
  }
  response.writeHead(result.status, { 'content-type': 'application/json', ...result.headers });
  response.end(JSON.stringify(result.body));
});

await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;

const created = await fetch(`${base}/items`, {
  method: 'POST',
  headers: { 'content-type': 'application/json' },
  body: JSON.stringify({ name: 'mug' })
});
assert.equal(created.status, 201);
const item = (await created.json()) as Item;
assert.deepEqual(await (await fetch(`${base}/items/${item.id}`)).json(), { id: '2', name: 'mug' });

assert.equal((await fetch(`${base}/items/99`)).status, 404);
assert.equal((await fetch(`${base}/items/%E0%A4%A`)).status, 400);
assert.equal((await fetch(`${base}/items`, { method: 'POST', body: '{"name":' })).status, 400);
const wrongMethod = await fetch(`${base}/items/1`, { method: 'DELETE' });
assert.equal(wrongMethod.status, 405);
assert.equal(wrongMethod.headers.get('allow'), 'GET, HEAD');
assert.equal((await fetch(`${base}/items/1`, { method: 'HEAD' })).status, 200);
console.log('GET /items/2 ->', item);

server.close();

In practice: services usually use a framework (Hono 4, Express 5, Fastify) for routing, validation and middleware; the manual version is worth knowing for tiny services, tests and to understand what the framework does. Validate the parsed body before using it, because JSON.parse returns unknown data.

Hono 4.13.17: app.get("/items/:id", (c) => c.json(...)) with c.req.param("id"). Express 5.3.0: app.get("/items/:id", (req, res) => res.json(...)) with req.params.id; Express 5 forwards rejected promises from async handlers to the error handler.

decodeURIComponent throws a URIError for a malformed escape such as %E0%A4%A. Uncaught inside an async request handler, it becomes an unhandled rejection that crashes the process, so every throw must end in a response.

Always cap the body size and count bytes (chunk.length), not string length, which counts UTF-16 code units.

Stop a server cleanly: server.close, http.Server.Shutdown, with_graceful_shutdown, server.stop

TypeScript

Graceful shutdown means: stop accepting connections, let in-flight requests finish, then exit. server.close(callback) stops the listener and calls back once every connection has closed; closeIdleConnections drops idle keep-alive sockets so they do not hold it open, and closeAllConnections is the hard stop. process.once("SIGTERM") receives the signal that process managers and Kubernetes send before killing the process.

Complete program

Complete program. Sends itself SIGTERM during a request and exits when drained.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import type { AddressInfo } from 'node:net';
import { setTimeout as sleep } from 'node:timers/promises';

const server = createServer(async (_request, response) => {
  await sleep(300); // a request that is still running when the signal arrives
  response.end('finished');
});
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;

const stopped = new Promise<void>((resolve) => {
  process.once('SIGTERM', () => {
    console.log('SIGTERM: no new connections, waiting for in-flight requests');
    // close() stops accepting and calls back once every connection has ended.
    server.close(() => resolve());
    server.closeIdleConnections(); // drop idle keep-alive sockets now
    // Hard deadline: if a request hangs, cut the remaining connections.
    setTimeout(() => server.closeAllConnections(), 10_000).unref();
  });
});

const inFlight = fetch(`${base}/`).then((response) => response.text());
await sleep(50); // let the request reach the handler
process.kill(process.pid, 'SIGTERM'); // what a process manager or Kubernetes sends

assert.equal(await inFlight, 'finished'); // the in-flight request still completed
await stopped;
assert.equal(server.listening, false);
console.log('server closed; exiting');

In practice: on SIGTERM, close the server, close idle connections, set an unref'd timer that forces the rest closed, and exit when the close callback runs. Close database pools and other resources after the server, not before.

Since Node 19, server.close() also closes idle connections; closeIdleConnections is still useful on older versions and is harmless.

Windows has no real SIGTERM: process.kill(pid, "SIGTERM") terminates the process without running the handler. Ctrl-C (SIGINT) does work.

In Kubernetes, the pod is removed from Service endpoints concurrently with SIGTERM, so keep serving for a few seconds (or use a preStop hook) before closing, and finish within terminationGracePeriodSeconds (30 s by default).

Build URLs and query strings safely: URLSearchParams, url.Values, the url crate, Boost.URL

TypeScript

URL and URLSearchParams build URLs from parts and encode each part for its position: searchParams.set and append encode values (a space becomes +, & becomes %26), and encodeURIComponent encodes a single path segment (a / becomes %2F). Reading through searchParams decodes again, and getAll returns every value of a repeated key.

Complete program

Complete program.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import assert from 'node:assert/strict';

const userInput = { term: 'rock & roll', tags: ['a+b', 'c d'], page: 2 };
const userName = 'ann/marie';

// Start from a fixed base; put user text only into encoded slots.
const url = new URL('https://api.example.com/v1/');
url.pathname += `users/${encodeURIComponent(userName)}/search`; // '/' inside a segment becomes %2F
url.searchParams.set('q', userInput.term);
for (const tag of userInput.tags) url.searchParams.append('tag', tag); // repeated key
url.searchParams.set('page', String(userInput.page));

assert.equal(
  url.href,
  'https://api.example.com/v1/users/ann%2Fmarie/search?q=rock+%26+roll&tag=a%2Bb&tag=c+d&page=2'
);

// Reading decodes again; getAll returns every value of a repeated key.
assert.equal(url.searchParams.get('q'), 'rock & roll');
assert.deepEqual(url.searchParams.getAll('tag'), ['a+b', 'c d']);

// URLSearchParams uses form encoding (space -> '+'); encodeURIComponent uses %20.
assert.equal(new URLSearchParams({ q: 'c d' }).toString(), 'q=c+d');
assert.equal(encodeURIComponent('c d'), 'c%20d');

// Concatenation breaks: the '&' starts a new parameter.
const broken = new URL(`https://api.example.com/search?q=${userInput.term}`);
assert.equal(broken.searchParams.get('q'), 'rock ');

console.log(url.href);

In practice: start from a fixed base URL and put user text only into encoded slots; never build a URL by concatenating unencoded input, which lets a value add parameters or change the path. Use encodeURIComponent, not encodeURI, for components.

URLSearchParams uses application/x-www-form-urlencoded rules: space is +. Some APIs (for example OAuth 1 signatures) need %20 instead; encode with encodeURIComponent there.

encodeURIComponent leaves ! ' ( ) * unencoded; replace them yourself if a server treats them as special.

Assigning url.search or url.pathname re-encodes only characters that are invalid there; a ? or # in a pathname string you built is encoded, but an & in search is not.