[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6D1QCKBP1RK5DN67RAS9D88":3,"skill-same:01M6D1QCKBP1RK5DN67RAS9D88":67},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":39,"linkOnly":40,"markdownContent":41,"markdownBody":42,"frontMatter":43,"refName":44,"commitSha":45,"skillDirectory":46,"forksCount":47,"repositoryHtmlUrl":48,"repositoryHomepageUrl":49,"ownerHtmlUrl":50,"ownerBlogUrl":49,"ownerDescription":51,"updatedAt":52,"install":53,"resources":66},"01M6D1QCKBP1RK5DN67RAS9D88","backend-stack-node",null,"A Node.js API in TypeScript: the Node version, strict ESM setup, Hono, Fastify, Express or NestJS, validation with zod, problem-details errors, config at start, Drizzle, Prisma or Kysely, pino with request ids, graceful shutdown, the event loop with worker threads and streams, outbound timeouts, BullMQ jobs, OpenTelemetry, tests with Vitest. Read when building or changing a Node.js backend.","enowdev\u002Fenowxcli","enowdev","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F179420349?v=4","01M6D1MVX2KC0X3Z9NESE7P22K","Enow Dev.","01M6D1MW1FMZGBDKWAJY4GQX81",67,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fbackend-stack-node\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38],"node","backend stack node","backend","stack","ids","api","hono","loop","OpenTelemetry","zod","typescript","read","start","shutdown","kysely","outbound","worker","express","prisma","config","2026-11-10 10:12:30",false,"---\nname: backend-stack-node\ndescription: \"A Node.js API in TypeScript: the Node version, strict ESM setup, Hono, Fastify, Express or NestJS, validation with zod, problem-details errors, config at start, Drizzle, Prisma or Kysely, pino with request ids, graceful shutdown, the event loop with worker threads and streams, outbound timeouts, BullMQ jobs, OpenTelemetry, tests with Vitest. Read when building or changing a Node.js backend.\"\n---\n\n# Node.js with TypeScript\n\nThe generated Node API: Express 4 with `any` bodies, a `try\u002Fcatch` in every\nhandler answering `res.status(500).send(err.message)`, `process.env` read in\ntwenty files, `console.log`, a database client per request, a CPU-heavy loop\nthat stalls every other request, and no shutdown, so each deploy drops\nrequests. The backend rules are in the `backend` skill; these are Node's own.\n\n## 1. Setup\n\n- Node: the active LTS for a new service, 24 in 2026 (22 is maintained until\n  April 2027, 20 is end of life, 26 becomes LTS in October 2026); never an\n  odd-numbered release in production. The same major in `package.json`\n  `engines`, `.nvmrc` and the Docker base image.\n- TypeScript with `strict` on, ES modules (`\"type\": \"module\"`). The\n  project's package manager (pnpm, npm, yarn, bun), one lock file.\n- `tsconfig.json`: `\"module\": \"nodenext\"`, `\"target\": \"es2024\"`, `\"strict\"`,\n  `\"noUncheckedIndexedAccess\"`, `\"verbatimModuleSyntax\"`, `\"outDir\": \"dist\"`\n  and `\"types\": [\"node\"]` (a recent `tsc --init` writes `\"types\": []`,\n  which hides Node's globals). Relative imports end in `.js`.\n- Development with `tsx watch src\u002Findex.ts`; production runs the compiled\n  output (`tsc` or `tsup` to `dist\u002F`), not `ts-node` or tsx. Node 22.18+ and\n  24 also run TypeScript directly (`node src\u002Findex.ts`) when it is erasable\n  only (`erasableSyntaxOnly`: no enums, namespaces or constructor parameter\n  properties) with `.ts` import paths: good for scripts; compile the service.\n- `node --env-file-if-exists=.env` loads a local `.env` (Node 22.9+) without\n  dotenv; production gets real variables from the platform.\n\nFramework: the project's; for a new API, by this table.\n\n| Framework | Choose it when |\n|---|---|\n| Hono | a new API of any size: web-standard `Request` and `Response`, typed routes, runs on Node, Bun, Deno and Workers |\n| Fastify | plugins, schema-validated routes and response serialisation, pino built in |\n| Express 5 | the project already uses Express; v5 sends rejected promises to the error handler (v4 needs a wrapper) |\n| NestJS | a large team that wants modules, dependency injection and decorators, and accepts the ceremony |\n\n## 2. Layout\n\n```\nsrc\u002F\n  index.ts          start: config, app, server, shutdown\n  app.ts            the app and its routes, exported for tests\n  config.ts         env parsed with zod\n  instrumentation.ts  OpenTelemetry, loaded before everything (section 11)\n  worker.ts         the job worker's own entry point\n  lib\u002F              db, logger, errors\n  orders\u002F\n    routes.ts       HTTP: parse, call the service, respond\n    service.ts      rules and transactions\n    repository.ts   queries\n    schemas.ts      zod schemas and the types inferred from them\n    orders.test.ts\n```\n\n## 3. Config at start\n\n`config.ts` parses `process.env` with a zod schema (`z.coerce.number()` for\nports, `z.url()` for URLs, no default for secrets); on failure it prints the\nvariable names, never the values, and exits `1` (`backend-observability`).\nNothing else reads `process.env`.\n\n## 4. Validation and errors\n\n- zod schemas at the edge (`@hono\u002Fzod-validator`; for Fastify,\n  `fastify-type-provider-zod` with `setValidatorCompiler(validatorCompiler)`\n  and response schemas that drop undeclared fields; `schema.parse` in\n  Express), with `z.infer` for the types, shared with a TypeScript client\n  when there is one.\n- `z.coerce` for query strings and path parameters, `z.strictObject()` (zod\n  4; `.strict()` in 3) or copying fields to refuse extra keys (`backend-api`).\n- An `AppError` class with a `code` and a status, thrown from services; one\n  error handler (`app.onError` in Hono, `setErrorHandler` in Fastify, the\n  final middleware in Express, an exception filter in NestJS) maps it, zod\n  errors and the unexpected into the format in `backend-errors`. No\n  `try\u002Fcatch` around each handler.\n\n```ts\nexport class AppError extends Error { \u002F\u002F plain fields: erasable, works with type stripping\n  readonly status: number; readonly code: string; readonly errors: FieldError[];\n  constructor(status: number, code: string, errors: FieldError[] = []) {\n    super(code); this.status = status; this.code = code; this.errors = errors;\n  }\n}\n\u002F\u002F [\"lines\", 0, \"quantity\"] -> \"lines[0].quantity\"\nconst fieldPath = (path: PropertyKey[]) => path.reduce\u003Cstring>((acc, p) =>\n  typeof p === \"number\" ? `${acc}[${p}]` : acc ? `${acc}.${String(p)}` : String(p), \"\");\nexport const fromZod = (error: z.core.$ZodError) =>\n  new AppError(400, \"validation_failed\", error.issues.flatMap((i) =>\n    i.code === \"unrecognized_keys\"\n      ? i.keys.map((k) => ({ field: fieldPath([...i.path, k]), code: \"unknown_field\" }))\n      : [{ field: fieldPath(i.path), code: i.code }]));\n\napp.post(\"\u002Forders\",\n  zValidator(\"json\", PlaceOrder, (r) => { if (!r.success) throw fromZod(r.error); }),\n  async (c) => {\n    const order = await orders.place(c.get(\"user\"), c.req.valid(\"json\"));\n    return c.json(order, 201, { Location: `\u002Forders\u002F${order.id}` });\n  });\n\napp.onError((err, c) => {\n  const e = err instanceof AppError ? err\n    : err instanceof HTTPException ? new AppError(err.status, \"http_error\") \u002F\u002F e.g. 413 from bodyLimit\n    : new AppError(500, \"internal\");\n  const requestId = c.get(\"requestId\");\n  if (e.status >= 500) logger.error({ err, requestId }, \"request failed\"); \u002F\u002F the one log line\n  const body = { type: `https:\u002F\u002Fexample.com\u002Ferrors\u002F${e.code.replaceAll(\"_\", \"-\")}`, status: e.status,\n    code: e.code, ...(e.errors.length && { errors: e.errors }), ...(e.status >= 500 && { requestId }) };\n  return c.body(JSON.stringify(body), e.status as ContentfulStatusCode,\n    { \"Content-Type\": \"application\u002Fproblem+json\" });\n});\n```\n\n## 5. Data\n\n- Drizzle (SQL-shaped and light, `drizzle-kit` migrations), Prisma\n  (schema-first; Prisma 7 needs a driver adapter such as `@prisma\u002Fadapter-pg`\n  and a `prisma.config.ts`) or Kysely (a typed query builder, types from\n  `kysely-codegen`): the project's choice, one client from `lib\u002Fdb.ts`;\n  `backend-data` for the rest.\n- Inside `db.transaction(async (tx) => ...)` every query uses `tx`; one\n  written against `db` runs outside the transaction and is not rolled back.\n- node-postgres returns `bigint` and `numeric` columns as strings: Drizzle's\n  `bigint({ mode: \"number\" })` only while values stay under 2^53; money as\n  integer minor units. Times as `timestamp({ withTimezone: true })`.\n- One `pg.Pool` per process (`max: 10`, `connectionTimeoutMillis: 5_000` so\n  a starved pool fails fast), sized against the database's limit across all\n  instances. Migrations: `drizzle-kit generate` then `migrate`, or `prisma\n  migrate deploy` at release; `drizzle-kit push` only on a scratch database.\n\n```ts\n\u002F\u002F Race-free: the check and the write are one statement; 0 rows means not enough stock.\nconst rows = await tx.update(products)\n  .set({ stock: sql`${products.stock} - ${qty}` })\n  .where(and(eq(products.id, productId), gte(products.stock, qty)))\n  .returning({ id: products.id });\nif (rows.length === 0) throw new AppError(409, \"out_of_stock\");\n```\n\n## 6. Logging\n\n- pino as the logger (Fastify's built-in one, or `hono-pino`), with a\n  request id and a child logger per request; `pino-pretty` only in\n  development. Hono's `requestId()` (`hono\u002Frequest-id`) reuses a valid\n  incoming `X-Request-Id` and returns it; Fastify 5 ignores incoming ids\n  unless `requestIdHeader` is set, and generates them with `genReqId`.\n- `AsyncLocalStorage` puts the id on every line written during the request,\n  with no logger passed around; `redact` keeps secrets out:\n\n```ts\nexport const requestContext = new AsyncLocalStorage\u003C{ requestId: string; userId?: string }>();\nexport const logger = pino({\n  level: config.LOG_LEVEL,\n  mixin: () => requestContext.getStore() ?? {},\n  redact: [\"req.headers.authorization\", \"req.headers.cookie\", \"*.password\", \"*.token\"],\n});\napp.use(async (c, next) => {\n  const started = performance.now();\n  await requestContext.run({ requestId: c.get(\"requestId\") }, next);\n  logger.info({ method: c.req.method, route: c.req.routePath, status: c.res.status,\n    ms: Math.round(performance.now() - started) }, \"request\");\n});\n```\n\n## 7. Shutdown\n\n```ts\nimport { setTimeout as sleep } from \"node:timers\u002Fpromises\";\n\nconst server = serve({\n  fetch: app.fetch,\n  port: config.PORT,\n  \u002F\u002F Longer than the load balancer's idle timeout (60s on an AWS ALB), or it sees 502s.\n  serverOptions: { keepAliveTimeout: 65_000, headersTimeout: 66_000 },\n});\nasync function shutdown(signal: string) {\n  logger.info({ signal }, \"shutting down\");\n  ready = false;                                   \u002F\u002F \u002Freadyz answers 503\n  setTimeout(() => process.exit(1), 20_000).unref(); \u002F\u002F the hard limit\n  await sleep(5_000);                               \u002F\u002F let the load balancer notice\n  server.close(async () => {                        \u002F\u002F in-flight requests finish first\n    await worker?.close(); await sdk.shutdown(); await pool.end();\n    process.exit(0);\n  });\n}\nfor (const signal of [\"SIGINT\", \"SIGTERM\"]) process.once(signal, () => void shutdown(signal));\n```\n\n- `server.close()` stops accepting, and since Node 19 closes idle keep-alive\n  connections too. `headersTimeout` must not exceed `requestTimeout` (default\n  300 seconds; Node refuses to start otherwise), and `requestTimeout` limits\n  receiving the request, not the handler's time. Fastify: `await app.close()`\n  answers `503` meanwhile; its `keepAliveTimeout` is already 72 seconds.\n- And `process.on(\"unhandledRejection\")` logs and exits, so a bug is not left\n  running in a broken state. Run as `node dist\u002Findex.js` in exec form, not\n  through `npm start`: an npm or shell parent may not pass `SIGTERM` on.\n\n## 8. The event loop\n\n- One thread runs every request's JavaScript: 100 ms of CPU in one handler\n  delays every request waiting behind it. Watch the p99 of\n  `monitorEventLoopDelay()`; above about 100 ms something blocks.\n- No `*Sync` calls (`readFileSync`, `pbkdf2Sync`, `gzipSync`) in handlers;\n  password hashing through the async API of `argon2` or `bcrypt`.\n- CPU-bound work (a report, parsing a big file) in worker threads through a\n  Piscina pool (`maxThreads` about the cores minus one, `pool.run(data, {\n  signal })`), or in a job.\n- The libuv pool (file system, `dns.lookup`, crypto, zlib) has 4 threads by\n  default; `UV_THREADPOOL_SIZE=8` to 16 for crypto- or file-heavy services.\n- Large payloads as streams, never buffered: `pipeline()` from\n  `node:stream\u002Fpromises`, a database cursor streamed out as CSV, uploads\n  sent straight to object storage (`backend-files`). Body limits before\n  parsing: Hono `bodyLimit({ maxSize: 1024 * 1024 })`, Fastify's `bodyLimit`\n  (1 MiB by default), `express.json({ limit: \"1mb\" })` (100 kB by default).\n\n## 9. Outbound calls\n\n- `fetch` with a deadline, joined to the request's own signal so the call\n  stops when the client leaves: `signal: AbortSignal.any([c.req.raw.signal,\n  AbortSignal.timeout(5_000)])`. `TimeoutError` and `AbortError` are\n  different failures (`backend-errors`). One client module per provider,\n  retries only for idempotent calls (`backend-integrations`).\n\n## 10. Jobs\n\n- BullMQ on Redis, the worker in its own process (`src\u002Fworker.ts`) scaled\n  apart from the API; pg-boss or graphile-worker when PostgreSQL is all there\n  is (`backend-jobs`). Its connection needs `maxRetriesPerRequest: null`,\n  Redis runs with `maxmemory-policy noeviction`, and job ids never hold `:`.\n\n```ts\nconst connection = new Redis(config.REDIS_URL, { maxRetriesPerRequest: null });\nexport const emails = new Queue\u003C{ orderId: string }>(\"emails\", {\n  connection,\n  defaultJobOptions: { attempts: 5, backoff: { type: \"exponential\", delay: 1_000 },\n    removeOnComplete: { count: 1_000 }, removeOnFail: { age: 7 * 24 * 3600 } },\n});\n\u002F\u002F A second add with the same id is ignored while the first is stored.\nawait emails.add(\"receipt\", { orderId }, { jobId: `receipt-${orderId}` });\n```\n\n## 11. OpenTelemetry\n\n`src\u002Finstrumentation.ts` starts `NodeSDK` with the auto-instrumentations and\nregisters the ESM loader hook; run `node --import .\u002Fdist\u002Finstrumentation.js\ndist\u002Findex.js` (code in `backend-observability`). Route names come from\n`@hono\u002Fotel` or `@fastify\u002Fotel`; Express and pg are covered by the defaults.\n\n## 12. Tests\n\nVitest; the app exported from `app.ts` and called without a port\n(`app.request(\"\u002Forders\")` in Hono, `app.inject()` in Fastify, supertest for\nExpress); a real database per `backend-testing`; MSW for other services.\nA validation test sends several faults at once and asserts the whole\n`errors` list (`lines[0].quantity` `too_small`, `role` `unknown_field`), not\nonly the `400`.\n\n## Check it\n\n`tsc --noEmit`, the linter (ESLint or Biome), the tests, then start it and\ncall the endpoints with `curl`: a bad body gives a `400` listing every field,\na 2 MB body a `413`, and `kill -TERM` during a slow request lets it finish\nand exits `0`. `npm audit --omit=dev` (or `pnpm audit --prod`) for known\nvulnerabilities.\n\n## Avoid\n\n`any` for request bodies; a `try\u002Fcatch` in every handler; `process.env` read\noutside `config.ts`; `console.log` as the logger; `ts-node` in production;\nExpress 4 async handlers without error handling; a floating promise for work\nthat must finish; queries on `db` inside a transaction; `*Sync` calls or CPU\nloops in handlers; `fetch` without a timeout; a server with no shutdown\nhandler; `npm start` as the container command; BullMQ job ids with `:`.\n","# Node.js with TypeScript\n\nThe generated Node API: Express 4 with `any` bodies, a `try\u002Fcatch` in every\nhandler answering `res.status(500).send(err.message)`, `process.env` read in\ntwenty files, `console.log`, a database client per request, a CPU-heavy loop\nthat stalls every other request, and no shutdown, so each deploy drops\nrequests. The backend rules are in the `backend` skill; these are Node's own.\n\n## 1. Setup\n\n- Node: the active LTS for a new service, 24 in 2026 (22 is maintained until\n  April 2027, 20 is end of life, 26 becomes LTS in October 2026); never an\n  odd-numbered release in production. The same major in `package.json`\n  `engines`, `.nvmrc` and the Docker base image.\n- TypeScript with `strict` on, ES modules (`\"type\": \"module\"`). The\n  project's package manager (pnpm, npm, yarn, bun), one lock file.\n- `tsconfig.json`: `\"module\": \"nodenext\"`, `\"target\": \"es2024\"`, `\"strict\"`,\n  `\"noUncheckedIndexedAccess\"`, `\"verbatimModuleSyntax\"`, `\"outDir\": \"dist\"`\n  and `\"types\": [\"node\"]` (a recent `tsc --init` writes `\"types\": []`,\n  which hides Node's globals). Relative imports end in `.js`.\n- Development with `tsx watch src\u002Findex.ts`; production runs the compiled\n  output (`tsc` or `tsup` to `dist\u002F`), not `ts-node` or tsx. Node 22.18+ and\n  24 also run TypeScript directly (`node src\u002Findex.ts`) when it is erasable\n  only (`erasableSyntaxOnly`: no enums, namespaces or constructor parameter\n  properties) with `.ts` import paths: good for scripts; compile the service.\n- `node --env-file-if-exists=.env` loads a local `.env` (Node 22.9+) without\n  dotenv; production gets real variables from the platform.\n\nFramework: the project's; for a new API, by this table.\n\n| Framework | Choose it when |\n|---|---|\n| Hono | a new API of any size: web-standard `Request` and `Response`, typed routes, runs on Node, Bun, Deno and Workers |\n| Fastify | plugins, schema-validated routes and response serialisation, pino built in |\n| Express 5 | the project already uses Express; v5 sends rejected promises to the error handler (v4 needs a wrapper) |\n| NestJS | a large team that wants modules, dependency injection and decorators, and accepts the ceremony |\n\n## 2. Layout\n\n```\nsrc\u002F\n  index.ts          start: config, app, server, shutdown\n  app.ts            the app and its routes, exported for tests\n  config.ts         env parsed with zod\n  instrumentation.ts  OpenTelemetry, loaded before everything (section 11)\n  worker.ts         the job worker's own entry point\n  lib\u002F              db, logger, errors\n  orders\u002F\n    routes.ts       HTTP: parse, call the service, respond\n    service.ts      rules and transactions\n    repository.ts   queries\n    schemas.ts      zod schemas and the types inferred from them\n    orders.test.ts\n```\n\n## 3. Config at start\n\n`config.ts` parses `process.env` with a zod schema (`z.coerce.number()` for\nports, `z.url()` for URLs, no default for secrets); on failure it prints the\nvariable names, never the values, and exits `1` (`backend-observability`).\nNothing else reads `process.env`.\n\n## 4. Validation and errors\n\n- zod schemas at the edge (`@hono\u002Fzod-validator`; for Fastify,\n  `fastify-type-provider-zod` with `setValidatorCompiler(validatorCompiler)`\n  and response schemas that drop undeclared fields; `schema.parse` in\n  Express), with `z.infer` for the types, shared with a TypeScript client\n  when there is one.\n- `z.coerce` for query strings and path parameters, `z.strictObject()` (zod\n  4; `.strict()` in 3) or copying fields to refuse extra keys (`backend-api`).\n- An `AppError` class with a `code` and a status, thrown from services; one\n  error handler (`app.onError` in Hono, `setErrorHandler` in Fastify, the\n  final middleware in Express, an exception filter in NestJS) maps it, zod\n  errors and the unexpected into the format in `backend-errors`. No\n  `try\u002Fcatch` around each handler.\n\n```ts\nexport class AppError extends Error { \u002F\u002F plain fields: erasable, works with type stripping\n  readonly status: number; readonly code: string; readonly errors: FieldError[];\n  constructor(status: number, code: string, errors: FieldError[] = []) {\n    super(code); this.status = status; this.code = code; this.errors = errors;\n  }\n}\n\u002F\u002F [\"lines\", 0, \"quantity\"] -> \"lines[0].quantity\"\nconst fieldPath = (path: PropertyKey[]) => path.reduce\u003Cstring>((acc, p) =>\n  typeof p === \"number\" ? `${acc}[${p}]` : acc ? `${acc}.${String(p)}` : String(p), \"\");\nexport const fromZod = (error: z.core.$ZodError) =>\n  new AppError(400, \"validation_failed\", error.issues.flatMap((i) =>\n    i.code === \"unrecognized_keys\"\n      ? i.keys.map((k) => ({ field: fieldPath([...i.path, k]), code: \"unknown_field\" }))\n      : [{ field: fieldPath(i.path), code: i.code }]));\n\napp.post(\"\u002Forders\",\n  zValidator(\"json\", PlaceOrder, (r) => { if (!r.success) throw fromZod(r.error); }),\n  async (c) => {\n    const order = await orders.place(c.get(\"user\"), c.req.valid(\"json\"));\n    return c.json(order, 201, { Location: `\u002Forders\u002F${order.id}` });\n  });\n\napp.onError((err, c) => {\n  const e = err instanceof AppError ? err\n    : err instanceof HTTPException ? new AppError(err.status, \"http_error\") \u002F\u002F e.g. 413 from bodyLimit\n    : new AppError(500, \"internal\");\n  const requestId = c.get(\"requestId\");\n  if (e.status >= 500) logger.error({ err, requestId }, \"request failed\"); \u002F\u002F the one log line\n  const body = { type: `https:\u002F\u002Fexample.com\u002Ferrors\u002F${e.code.replaceAll(\"_\", \"-\")}`, status: e.status,\n    code: e.code, ...(e.errors.length && { errors: e.errors }), ...(e.status >= 500 && { requestId }) };\n  return c.body(JSON.stringify(body), e.status as ContentfulStatusCode,\n    { \"Content-Type\": \"application\u002Fproblem+json\" });\n});\n```\n\n## 5. Data\n\n- Drizzle (SQL-shaped and light, `drizzle-kit` migrations), Prisma\n  (schema-first; Prisma 7 needs a driver adapter such as `@prisma\u002Fadapter-pg`\n  and a `prisma.config.ts`) or Kysely (a typed query builder, types from\n  `kysely-codegen`): the project's choice, one client from `lib\u002Fdb.ts`;\n  `backend-data` for the rest.\n- Inside `db.transaction(async (tx) => ...)` every query uses `tx`; one\n  written against `db` runs outside the transaction and is not rolled back.\n- node-postgres returns `bigint` and `numeric` columns as strings: Drizzle's\n  `bigint({ mode: \"number\" })` only while values stay under 2^53; money as\n  integer minor units. Times as `timestamp({ withTimezone: true })`.\n- One `pg.Pool` per process (`max: 10`, `connectionTimeoutMillis: 5_000` so\n  a starved pool fails fast), sized against the database's limit across all\n  instances. Migrations: `drizzle-kit generate` then `migrate`, or `prisma\n  migrate deploy` at release; `drizzle-kit push` only on a scratch database.\n\n```ts\n\u002F\u002F Race-free: the check and the write are one statement; 0 rows means not enough stock.\nconst rows = await tx.update(products)\n  .set({ stock: sql`${products.stock} - ${qty}` })\n  .where(and(eq(products.id, productId), gte(products.stock, qty)))\n  .returning({ id: products.id });\nif (rows.length === 0) throw new AppError(409, \"out_of_stock\");\n```\n\n## 6. Logging\n\n- pino as the logger (Fastify's built-in one, or `hono-pino`), with a\n  request id and a child logger per request; `pino-pretty` only in\n  development. Hono's `requestId()` (`hono\u002Frequest-id`) reuses a valid\n  incoming `X-Request-Id` and returns it; Fastify 5 ignores incoming ids\n  unless `requestIdHeader` is set, and generates them with `genReqId`.\n- `AsyncLocalStorage` puts the id on every line written during the request,\n  with no logger passed around; `redact` keeps secrets out:\n\n```ts\nexport const requestContext = new AsyncLocalStorage\u003C{ requestId: string; userId?: string }>();\nexport const logger = pino({\n  level: config.LOG_LEVEL,\n  mixin: () => requestContext.getStore() ?? {},\n  redact: [\"req.headers.authorization\", \"req.headers.cookie\", \"*.password\", \"*.token\"],\n});\napp.use(async (c, next) => {\n  const started = performance.now();\n  await requestContext.run({ requestId: c.get(\"requestId\") }, next);\n  logger.info({ method: c.req.method, route: c.req.routePath, status: c.res.status,\n    ms: Math.round(performance.now() - started) }, \"request\");\n});\n```\n\n## 7. Shutdown\n\n```ts\nimport { setTimeout as sleep } from \"node:timers\u002Fpromises\";\n\nconst server = serve({\n  fetch: app.fetch,\n  port: config.PORT,\n  \u002F\u002F Longer than the load balancer's idle timeout (60s on an AWS ALB), or it sees 502s.\n  serverOptions: { keepAliveTimeout: 65_000, headersTimeout: 66_000 },\n});\nasync function shutdown(signal: string) {\n  logger.info({ signal }, \"shutting down\");\n  ready = false;                                   \u002F\u002F \u002Freadyz answers 503\n  setTimeout(() => process.exit(1), 20_000).unref(); \u002F\u002F the hard limit\n  await sleep(5_000);                               \u002F\u002F let the load balancer notice\n  server.close(async () => {                        \u002F\u002F in-flight requests finish first\n    await worker?.close(); await sdk.shutdown(); await pool.end();\n    process.exit(0);\n  });\n}\nfor (const signal of [\"SIGINT\", \"SIGTERM\"]) process.once(signal, () => void shutdown(signal));\n```\n\n- `server.close()` stops accepting, and since Node 19 closes idle keep-alive\n  connections too. `headersTimeout` must not exceed `requestTimeout` (default\n  300 seconds; Node refuses to start otherwise), and `requestTimeout` limits\n  receiving the request, not the handler's time. Fastify: `await app.close()`\n  answers `503` meanwhile; its `keepAliveTimeout` is already 72 seconds.\n- And `process.on(\"unhandledRejection\")` logs and exits, so a bug is not left\n  running in a broken state. Run as `node dist\u002Findex.js` in exec form, not\n  through `npm start`: an npm or shell parent may not pass `SIGTERM` on.\n\n## 8. The event loop\n\n- One thread runs every request's JavaScript: 100 ms of CPU in one handler\n  delays every request waiting behind it. Watch the p99 of\n  `monitorEventLoopDelay()`; above about 100 ms something blocks.\n- No `*Sync` calls (`readFileSync`, `pbkdf2Sync`, `gzipSync`) in handlers;\n  password hashing through the async API of `argon2` or `bcrypt`.\n- CPU-bound work (a report, parsing a big file) in worker threads through a\n  Piscina pool (`maxThreads` about the cores minus one, `pool.run(data, {\n  signal })`), or in a job.\n- The libuv pool (file system, `dns.lookup`, crypto, zlib) has 4 threads by\n  default; `UV_THREADPOOL_SIZE=8` to 16 for crypto- or file-heavy services.\n- Large payloads as streams, never buffered: `pipeline()` from\n  `node:stream\u002Fpromises`, a database cursor streamed out as CSV, uploads\n  sent straight to object storage (`backend-files`). Body limits before\n  parsing: Hono `bodyLimit({ maxSize: 1024 * 1024 })`, Fastify's `bodyLimit`\n  (1 MiB by default), `express.json({ limit: \"1mb\" })` (100 kB by default).\n\n## 9. Outbound calls\n\n- `fetch` with a deadline, joined to the request's own signal so the call\n  stops when the client leaves: `signal: AbortSignal.any([c.req.raw.signal,\n  AbortSignal.timeout(5_000)])`. `TimeoutError` and `AbortError` are\n  different failures (`backend-errors`). One client module per provider,\n  retries only for idempotent calls (`backend-integrations`).\n\n## 10. Jobs\n\n- BullMQ on Redis, the worker in its own process (`src\u002Fworker.ts`) scaled\n  apart from the API; pg-boss or graphile-worker when PostgreSQL is all there\n  is (`backend-jobs`). Its connection needs `maxRetriesPerRequest: null`,\n  Redis runs with `maxmemory-policy noeviction`, and job ids never hold `:`.\n\n```ts\nconst connection = new Redis(config.REDIS_URL, { maxRetriesPerRequest: null });\nexport const emails = new Queue\u003C{ orderId: string }>(\"emails\", {\n  connection,\n  defaultJobOptions: { attempts: 5, backoff: { type: \"exponential\", delay: 1_000 },\n    removeOnComplete: { count: 1_000 }, removeOnFail: { age: 7 * 24 * 3600 } },\n});\n\u002F\u002F A second add with the same id is ignored while the first is stored.\nawait emails.add(\"receipt\", { orderId }, { jobId: `receipt-${orderId}` });\n```\n\n## 11. OpenTelemetry\n\n`src\u002Finstrumentation.ts` starts `NodeSDK` with the auto-instrumentations and\nregisters the ESM loader hook; run `node --import .\u002Fdist\u002Finstrumentation.js\ndist\u002Findex.js` (code in `backend-observability`). Route names come from\n`@hono\u002Fotel` or `@fastify\u002Fotel`; Express and pg are covered by the defaults.\n\n## 12. Tests\n\nVitest; the app exported from `app.ts` and called without a port\n(`app.request(\"\u002Forders\")` in Hono, `app.inject()` in Fastify, supertest for\nExpress); a real database per `backend-testing`; MSW for other services.\nA validation test sends several faults at once and asserts the whole\n`errors` list (`lines[0].quantity` `too_small`, `role` `unknown_field`), not\nonly the `400`.\n\n## Check it\n\n`tsc --noEmit`, the linter (ESLint or Biome), the tests, then start it and\ncall the endpoints with `curl`: a bad body gives a `400` listing every field,\na 2 MB body a `413`, and `kill -TERM` during a slow request lets it finish\nand exits `0`. `npm audit --omit=dev` (or `pnpm audit --prod`) for known\nvulnerabilities.\n\n## Avoid\n\n`any` for request bodies; a `try\u002Fcatch` in every handler; `process.env` read\noutside `config.ts`; `console.log` as the logger; `ts-node` in production;\nExpress 4 async handlers without error handling; a floating promise for work\nthat must finish; queries on `db` inside a transaction; `*Sync` calls or CPU\nloops in handlers; `fetch` without a timeout; a server with no shutdown\nhandler; `npm start` as the container command; BullMQ job ids with `:`.\n",{"name":5,"description":7},"main","38293fe1b096e6bf3646c7344c38786ed688f464","crates\u002Fenowx-core\u002Fskills\u002Fbackend-stack-node",21,"https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli","https:\u002F\u002Fenowx.ai","https:\u002F\u002Fgithub.com\u002Fenowdev","Pretending to be a Developer","2026-10-06 02:05:35",{"source":8,"skillName":5,"commands":54,"prompt":64,"zipAvailable":65},[55,58,61],{"tool":56,"command":57},"npx","npx skills add enowdev\u002Fenowxcli --skill backend-stack-node",{"tool":59,"command":60},"bunx","bunx skills add enowdev\u002Fenowxcli --skill backend-stack-node",{"tool":62,"command":63},"pnpm","pnpm dlx skills add enowdev\u002Fenowxcli --skill backend-stack-node","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fbackend-stack-node\u002FSKILL.md",true,[],[68,79,96,109,130,149],{"skillNo":69,"name":70,"nameZh":6,"description":71,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":72,"categories":73,"keywords":74,"publishedAt":39},"01M6D2HQYSQD9N7MTNDT4A7CBM","demo-skill","Project-scope demo skill for tests.","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fworkspace\u002F.agents\u002Fskills\u002Fdemo-skill\u002FSKILL.md",[],[75,76,77,78,30],"demo skill","demo","tests","project",{"skillNo":80,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":39},"01M6D2HM0GCPM0TM2HPG9HHR2R","writing","Writing words people read: the specific thing instead of claims, words to drop, sentences, interface copy (buttons, labels, errors, empty states, confirmations), page copy, notifications and emails, alt text and link text, numbers and dates, words that translate well, documentation and voice. Read before writing a page's copy, an interface's text or a document.","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fwriting\u002FSKILL.md",[],[81,86,87,88,89,90,30,91,92,93,94,95],"text","emails","empty","drop","document","page","voice","notifications","documentation","translate",{"skillNo":97,"name":98,"nameZh":6,"description":99,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":100,"categories":101,"keywords":102,"publishedAt":39},"01M6D2HG07YS49NM196Q0R3AZ8","ui","Designing or restyling an interface: direction, layout, type, colour, icons, components, states, responsive behaviour. Read before building a page, a screen or a set of components.","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fui\u002FSKILL.md",[],[98,103,104,105,106,91,107,30,108],"icons","components","SET","responsive","layout","before building",{"skillNo":110,"name":111,"nameZh":6,"description":112,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":113,"categories":114,"keywords":115,"publishedAt":39},"01M6D2HB59HZHWG1RYZDV4SJ91","ui-themes","Light and dark themes, and colour that holds in both: tokens with a value per theme, and what each kind of content needs to stay visible (icons, SVG drawings and line art, logos, photos, screenshots, charts, code, maps, borders, shadows, focus, form controls), switching without a flash, and checking both. Read before building a second theme or a theme toggle, and before any drawing, logo or chart on a page that has two themes.","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fui-themes\u002FSKILL.md",[],[98,116,117,118,119,120,121,122,123,30,108,124,91,125,126,127,103,128,129],"ui themes","switching","photos","tokens","drawing","focus","maps","Art","flash","code","Charts","content","screenshots","logo",{"skillNo":131,"name":132,"nameZh":6,"description":133,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":134,"categories":135,"keywords":136,"publishedAt":39},"01M6D2H5R5KRAE524C8QX0T7Q0","ui-structure","Structure before styling: the blueprint written before any interface code (the screen's job, the regions its kind of page needs, their order and why, the layout skeleton in numbers, the components and their states), the anatomy and order of a homepage, a dashboard, a list, a detail page, settings, a form, sign-in, pricing, docs, an article and a checkout, and how to turn the blueprint into code (tokens, layout primitives, components, sections, page). Read first, before building or rebuilding any page or screen.","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fui-structure\u002FSKILL.md",[],[137,98,138,104,139,140,125,141,142,143,107,119,144,145,146,30,108,91,147,148],"structure","ui structure","pricing","dashboard","Blueprint","article","anatomy","styling","primitives","list","why","how",{"skillNo":150,"name":151,"nameZh":6,"description":152,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":153,"categories":154,"keywords":155,"publishedAt":39},"01M6D2H0ZZBJG77MBGPZHA6MWD","ui-stack-vue","Building interfaces in Vue 3 and Nuxt: project layout, script setup with typed defineProps, defineEmits and defineModel, attribute fallthrough, slots and scoped slots, template refs, ref, reactive and computed, watch versus watchEffect, composables and VueUse, provide and inject, Pinia, keyed v-for, transitions, Nuxt 4 (app directory, pages, layouts, useFetch and useAsyncData keys, $fetch in handlers, server routes, runtime config, useSeoMeta, NuxtImg, middleware), VeeValidate forms, Reka UI and Nuxt UI, testing, vue-tsc, and the traps. Read when the project uses Vue or Nuxt.","https:\u002F\u002Fgithub.com\u002Fenowdev\u002Fenowxcli\u002Fblob\u002Fmain\u002Fcrates\u002Fenowx-core\u002Fskills\u002Fui-stack-vue\u002FSKILL.md",[],[98,156,22,157,158,159,160,161,107,78,162,163,30,164,165,166,167,38,168,169],"vue","ui stack vue","forms","pages","watch","runtime","transitions","fetch","pinia","nuxt","template","server","directory","testing"]