agentleFS
TheDecipheristTheDecipherist/claude-code-mastery-project-starter-kit/.claude/skills/nodejs/SKILL.md

nodejs

Skill337 starsChanged 5 months agoMITView on GitHub

Node.js backend runtime and process-lifecycle rules that Claude reliably gets wrong. Use when writing a Node server or long-running script, an Express app, worker threads, or process signal handling, and when choosing packages. Covers correct graceful shutdown, crash-on-fault instead of swallowing errors, not blocking the event loop, loading instrumentation first, securing the session cookie, and replacing deprecated packages with built-ins. Defers MongoDB to mongodb-rules, schema/validation to schema-source-of-truth, and image/deploy to docker and docker-swarm.

7 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use grpc, gcp and 4 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • Sorcha-PlatformSkill

    grpc

    Build or review gRPC services and clients in .NET. USE FOR: ASP.NET Core gRPC, protobuf contracts, unary or streaming RPC, gRPC client factory, interceptors, deadlines, cancellation, channel reuse, backend service integration. DO NOT USE FOR: broad browser-facing APIs without gRPC-Web tradeoff review, SignalR realtime hubs, plain REST APIs. INVOKES: dotnet build/test and focused service or client smoke checks when code changes.

    Also in 3 projects that use this

  • ffsshhttiikkSkill

    gcp

    Google Cloud Platform services and best practices

    Also in 3 projects that use this

  • VercelSkill

    oauth

    Configure OAuth providers (Google, Apple, Microsoft, Facebook, GitHub, etc.) to work with portless local dev URLs. Use when setting up OAuth redirect URIs, fixing "redirect_uri_mismatch" or "invalid redirect" errors, configuring sign-in providers for local development, or when a provider rejects .localhost subdomains. Triggers include "OAuth not working with portless", "redirect URI mismatch", "Google/Apple/Microsoft sign-in fails locally", "configure OAuth for local dev", or any task involving OAuth callback URLs with portless domains.

    Also in 3 projects that use this

  • JetBrainsSkill

    vue

    Vue 3 Composition API, script setup macros, reactivity system, and built-in components. Use when writing Vue SFCs, defineProps/defineEmits/defineModel, watchers, or using Transition/Teleport/Suspense/KeepAlive.

    Also in 4 projects that use this

  • MicrosoftSkill

    github-actions

    Use when creating, editing, reviewing, or troubleshooting GitHub Actions workflows in Scope.

    Also in 4 projects that use this

  • VercelSkill

    react

    React renderer for json-render that turns JSON specs into React components. Use when working with @json-render/react, building React UIs from JSON, creating component catalogs, or rendering AI-generated specs.

    Also in 3 projects that use this

The file

We split this skill into the rules it gives an agent

2 rules. 0 are common, 0 are distinctive, and 2 are very specific to this project.

  • 0

    Common

    Most of the 6 edited versions we read keep these.

  • 0

    Distinctive

    This author's own choices. Worth a look.

  • 2

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    When Claude sets up sessions it usually sets httpOnly and stops.

    line 93
  2. Very specific:

    Use the node: prefix on built-in imports (require("node:fs")) so there's no ambiguity with a same-named package.

    line 112

“Common” is measured: kept by at least 6 in 10 of the 6 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Node.js: Process Lifecycle and Runtime Rules

Claude writes Node services that work in a demo and fall over in production, almost always around the process lifecycle. These are the parts to get right.

Graceful shutdown, done correctly

A server must shut down cleanly on SIGTERM (what docker stop, Swarm, and Kubernetes send) and SIGINT (Ctrl-C). Claude usually omits this entirely, so the orchestrator waits the grace period and then SIGKILLs, dropping in-flight requests. The correct sequence is: stop accepting new connections, drain in-flight ones, close dependencies, exit 0, with a hard timeout so a stuck connection can't block shutdown forever.

const server = app.listen(port);
let shuttingDown = false;

async function shutdown(signal) {
  if (shuttingDown) return;                 // ignore repeat signals
  shuttingDown = true;
  logger.info("shutting down", { signal });

  const force = setTimeout(() => {           // drain hung? force it
    logger.error("shutdown timed out, forcing exit");
    process.exit(1);
  }, 10_000);
  force.unref();

  try {
    await new Promise((r) => server.close(r)); // stop new conns, let in-flight finish
    await db.close();                          // then close DB, redis, change streams
    clearTimeout(force);
    process.exit(0);
  } catch (err) {
    logger.error("error during shutdown", { err });
    process.exit(1);
  }
}

process.on("SIGTERM", () => shutdown("SIGTERM"));
process.on("SIGINT",  () => shutdown("SIGINT"));

Two things that look fine but are bugs: do not put async cleanup in a process.on("exit", ...) handler, the event loop is already stopped so nothing async runs, exit is for synchronous work only. And do not trap SIGUSR1, Node uses it for the debugger. This only works if the process actually receives the signal, which means an exec-form ENTRYPOINT so Node is PID 1 (see the docker skill) and init: true so signals are forwarded (see docker-swarm).

Let it crash, never swallow a fault

On uncaughtException or unhandledRejection the process is in an unknown, possibly corrupt state. Log it and exit non-zero, let the orchestrator restart a clean process. Do not catch-and-continue. Modern Node already terminates on an unhandled rejection by default, so code that relies on swallowing one is both wrong and fragile.

process.on("uncaughtException", (err) => {
  logger.error("uncaught exception", { err });
  process.exit(1);            // exit non-zero so restart_policy: on-failure restarts
});
process.on("unhandledRejection", (reason) => {
  logger.error("unhandled rejection", { reason });
  process.exit(1);
});

The non-zero exit is what makes Swarm/K8s self-healing fire, an exit(0) on a crash reads as success and the dead service is never restarted (see docker-swarm). You can route these through shutdown() to drain first, but never let the process keep serving after one.

Don't block the event loop

Node runs your JavaScript on a single thread. A CPU-bound stretch, parsing a huge payload, hashing, image work, a tight loop over a large array, freezes every concurrent request until it finishes. I/O is already async and is not the problem. For real CPU work, offload to worker_threads, not child_process (for in-process JS) and not "just make it async" (await doesn't yield during a synchronous loop).

const { Worker } = require("node:worker_threads");
new Worker("./workers/process.js", {
  workerData,
  resourceLimits: { maxOldGenerationSizeMb: 512 },  // cap so one worker can't OOM the host
});

Load instrumentation before anything else

APM and tracing libraries (dd-trace, the OpenTelemetry SDK) work by monkey-patching http, express, and your DB driver. They can only patch modules loaded after them, so the init call must be the very first thing in the entry file, before any require("express"). Required late, it silently instruments nothing.

// server.js, line 1
require("dd-trace").init({ /* ... */ });
const express = require("express");   // now traced

Lock down the session cookie

When Claude sets up sessions it usually sets httpOnly and stops. Set all three: httpOnly (no JS access), secure in production (HTTPS only), and sameSite (CSRF defense), which is the one that gets missed.

cookie: { httpOnly: true, secure: isProd, sameSite: "lax", maxAge: 86_400_000 }

Related CORS gotcha: credentials: true cannot be combined with origin: "*", the browser rejects it. Echo a specific allowed origin instead.

Reach for built-ins, replace deprecated packages

Claude's training pulls in libraries that are now deprecated or unnecessary. Prefer the platform:

  • crypto.randomUUID() over the uuid package for a v4 id, and uuid over node-uuid
  • native fetch (Node 18+) or axios over request (unmaintained since 2020)
  • node:test + node:assert for simple suites, structuredClone() over a deep-clone dep
  • the Intl APIs or date-fns/Temporal over moment (in maintenance mode)
  • @aws-sdk/client-* v3 (modular) over the monolithic aws-sdk v2
  • sass (dart-sass) over the deprecated node-sass

Use the node: prefix on built-in imports (require("node:fs")) so there's no ambiguity with a same-named package.

Two smaller ones

  • Logging: a structured logger (pino or winston) emitting JSON to stdout in production, never console.log in a hot path. stdout because the container's logging driver collects it (see docker).
  • PM2: cluster mode is for using all cores on a VM or bare-metal host. Inside a Swarm or K8s container, run one Node process and scale with replicas plus init: true, don't stack two process managers that both try to own restarts.

This skill is built to grow. Add a rule when a real Node production failure has a stable, defensible fix.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.