A Node API you can actually run in production, without a framework
Gepubliceerd · 3 min leestijd
Most "hello world" Node servers fall over in the same five ways: they leak error messages, they have no way to trace one request through the logs, one noisy client can take them down, the load balancer can't tell whether they're healthy, and a deploy cuts requests in half. None of these needs a framework. They need about 70 lines.
This article builds a small orders API with node:http and a handful of small, dependency-free packages, then pokes at it to prove each problem is solved. Everything below was run; the output shown is real.
npm install @sandsoftwaresolutions/mini-router @sandsoftwaresolutions/request-id \
@sandsoftwaresolutions/log-kit @sandsoftwaresolutions/rate-limit \
@sandsoftwaresolutions/health @sandsoftwaresolutions/graceful \
@sandsoftwaresolutions/cursor-pagination
The whole thing
import { createServer } from "node:http";
import { createRouter, HttpError } from "@sandsoftwaresolutions/mini-router";
import { withRequestId, currentRequestId } from "@sandsoftwaresolutions/request-id";
import { createLogger, parseLevel } from "@sandsoftwaresolutions/log-kit";
import { rateLimit } from "@sandsoftwaresolutions/rate-limit";
import { createHealth } from "@sandsoftwaresolutions/health";
import { gracefulShutdown } from "@sandsoftwaresolutions/graceful";
import { paginate } from "@sandsoftwaresolutions/cursor-pagination";
const log = createLogger({
name: "orders-api",
level: parseLevel(process.env.LOG_LEVEL, "info"),
mixin: () => ({ requestId: currentRequestId() }),
});
// Fake data store, sorted by id.
const orders = Array.from({ length: 45 }, (_, i) => ({ id: i + 1, total: (i + 1) * 5 }));
const health = createHealth({
checks: { store: () => orders.length > 0 },
timeoutMs: 1000,
});
const limit = rateLimit({ limit: Number(process.env.RATE_LIMIT ?? 60), windowMs: 60_000 });
const app = createRouter({
maxBodyBytes: 10_000,
onError: (error) => log.error("unhandled error", { err: error }),
});
app.get("/orders", ({ query }) => {
const limitParam = Math.min(Number(query.limit ?? 10) || 10, 50);
try {
return paginate(orders, { limit: limitParam, after: query.after });
} catch (error) {
// A cursor that is garbage or no longer in the list is the client's problem, not a 500.
if (error instanceof TypeError || error instanceof RangeError) throw new HttpError(400, "Invalid cursor");
throw error;
}
});
app.get("/orders/:id", ({ params }) => {
const order = orders.find((o) => String(o.id) === params.id);
if (!order) throw new HttpError(404, "No such order");
return order;
});
app.get("/boom", () => {
throw new Error("database password is hunter2"); // must never reach the client
});
const server = createServer(
withRequestId((req, res) => {
const started = Date.now();
res.on("finish", () =>
log.info("request", { method: req.method, url: req.url, status: res.statusCode, ms: Date.now() - started })
);
if (req.url === "/live") return health.live(req, res);
if (req.url === "/ready") return g.isShuttingDown() ? g.readiness(req, res) : health.ready(req, res);
limit(req, res, () => app.handler(req, res));
})
);
const g = gracefulShutdown({
server,
timeoutMs: 8000,
hooks: [() => log.info("closing store")],
log: (m) => log.info(String(m)),
});
const port = Number(process.env.PORT ?? 3000);
server.listen(port, () => log.info("listening", { port }));
What each piece buys you
1. Errors that don't leak. /boom throws new Error("database password is hunter2"). The client gets:
HTTP/1.1 500 Internal Server Error
{"error":"Internal Server Error"}
Only HttpError messages reach the client ({"error":"No such order"} for a 404). Everything else becomes a generic 500 and goes to onError, which is your logger.
2. One id per request, on every log line. withRequestId puts an x-request-id header on the response and stores the id in AsyncLocalStorage. The logger's mixin reads it with currentRequestId(), so even a log call five awaits deep carries the id:
{"level":"error","name":"orders-api","msg":"unhandled error","requestId":"b0441917-074b-446e-8c2f-6c4875515407","err":{...}}
{"level":"info","name":"orders-api","msg":"request","requestId":"b0441917-074b-446e-8c2f-6c4875515407","method":"GET","url":"/boom","status":500,"ms":0}
A user reports "I got an error"; you ask for the x-request-id from the response and grep for it. If a client sends its own x-request-id, it is only used when it is 8–128 characters of letters, digits and . _ : -, so nobody can inject text into your logs through that header.
A caveat worth knowing: log-kit redacts by field name (password, token, authorization, …) and recognises Bearer … values and URL credentials inside strings. It does not understand free text. The log line for /boom still contains the message "database password is hunter2", because that's what the error said. Don't put secrets in error messages.
3. A limit on noisy clients. With RATE_LIMIT=5 and the sixth request in a minute:
HTTP/1.1 429 Too Many Requests
Retry-After: 25
Retry-After is computed from the sliding window, not a fixed guess. Two things to get right in production: the default key is the connection's IP address, which behind a proxy is the proxy itself, so pass a key function that reads a header only your own proxy sets; and the counters live in memory, so this protects one process, not a fleet.
4. Health checks that mean something. /live never runs checks (so a slow database doesn't get your container restarted); /ready does:
{"status":"ok","checks":{"store":{"status":"up","ms":0,"critical":true}},"at":"2026-11-05T13:40:47.246Z"}
Mark non-essential dependencies critical: false and a broken mail server shows up as degraded (still HTTP 200) instead of taking you out of the load balancer.
5. Deploys that don't drop requests. On SIGTERM, gracefulShutdown flips readiness to 503, stops accepting connections, closes idle keep-alive sockets, lets in-flight requests finish (up to timeoutMs), runs your hooks, and exits:
{"msg":"shutting down (SIGTERM)"}
{"msg":"closing store"}
{"msg":"stopped cleanly"}
Docker kills a container after 10 seconds by default, so keep timeoutMs below your stop_grace_period.
Pagination, briefly
/orders uses paginate and returns { data, pageInfo: { hasMore, nextCursor } }; you pass nextCursor back as ?after=. Two honest notes. First, paginate works on an array that's already in memory and finds the cursor row by scanning it, so it's for small result sets; for a real table see the pagination article. Second, it throws if the cursor is garbage or the row is gone, which is why the handler above turns that into a 400.
What this is not
It's not a framework replacement for a big app: no cookies, sessions, CORS or uploads (mini-router says so in its README), and the rate limiter and health cache are per-process. For a single service, a side project, or a Raspberry Pi in a closet, though, this is a sound base — and every line of it is something you can read in an afternoon.