agentleFS
FranRomFranRom/pupila/.agents/skills/nodejs-best-practices/SKILL.md

nodejs-best-practices

Skill36 starsChanged 7 months agoMITView on GitHub

Node.js development principles and decision-making. Framework selection, async patterns, security, and architecture. Teaches thinking, not copying.

  • Reads credentials

11 other projects use a version of this, 9 of them edited.

Adopted by

Most recently taken up by

Used with

Projects with it also use 2d-games, 3d-games and 6 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.
  • tiendatworkSkill

    2d-games

    2D game development principles. Sprites, tilemaps, physics, camera.

    Also in 3 projects that use this

  • tiendatworkSkill

    3d-games

    3D game development principles. Rendering, shaders, physics, cameras.

    Also in 3 projects that use this

  • +6 more from tiendatwork

The file

We split this skill into the rules it gives an agent

7 rules. 2 are common, 4 are distinctive, and 1 is very specific to this project.

  • 2

    Common

    Most of the 11 edited versions we read keep these.

  • 4

    Distinctive

    This author's own choices. Worth a look.

  • 1

    Very specific

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

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    ASK user prefs when unclear

    line 23
  2. Common:

    Don't default same solution every time

    line 25
  3. Common:

    Ask: "will this grow?"

    line 141
  4. Very specific:

    Never sync methods in prod (fs.readFileSync etc.)

    line 206
  5. Distinctive:

    Use only when task matches scope.

    line 335
  6. Distinctive:

    Not substitute for env-specific validation, testing, or expert review.

    line 336
  7. Distinctive:

    Stop + ask if inputs, permissions, safety boundaries, or success criteria missing.

    line 337

“Common” is measured: kept by at least 6 in 10 of the 11 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 Best Practices

Principles + decision-making, Node.js 2025. THINK, don't memorize.

When to Use

Node.js architecture decisions, framework choice, async design, security, deployment.


How to Use

Teaches decision-making, not copy-paste code.

  • ASK user prefs when unclear
  • Pick framework/pattern by CONTEXT
  • Don't default same solution every time

1. Framework Selection (2025)

Decision Tree

What are you building?
│
├── Edge/Serverless (Cloudflare, Vercel)
│   └── Hono (zero-dependency, ultra-fast cold starts)
│
├── High Performance API
│   └── Fastify (2-3x faster than Express)
│
├── Enterprise/Team familiarity
│   └── NestJS (structured, DI, decorators)
│
├── Legacy/Stable/Maximum ecosystem
│   └── Express (mature, most middleware)
│
└── Full-stack with frontend
    └── Next.js API Routes or tRPC

Comparison Principles

FactorHonoFastifyExpress
Best forEdge, serverlessPerformanceLegacy, learning
Cold startFastestFastModerate
EcosystemGrowingGoodLargest
TypeScriptNativeExcellentGood
Learning curveLowMediumLow

Why these matter: Hono wins edge/serverless via zero deps + tiny runtime → fastest cold starts. Fastify wins perf via schema-based serialization → 2-3x Express throughput. Express wins on ecosystem maturity + middleware count. NestJS wins for teams needing DI/decorators/structure. Next.js/tRPC win when frontend colocated.

Selection Questions:

  1. Deployment target?
  2. Cold start critical?
  3. Team experience?
  4. Legacy code to maintain?

2. Runtime (2025)

Native TypeScript

Node.js 22+: --experimental-strip-types
├── Run .ts files directly
├── No build step needed for simple projects
└── Consider for: scripts, simple APIs

Module System

ESM (import/export)
├── Modern standard
├── Better tree-shaking
├── Async module loading
└── Use for: new projects

CommonJS (require)
├── Legacy compatibility
├── More npm packages support
└── Use for: existing codebases, some edge cases

Runtime Pick

RuntimeBest For
Node.jsGeneral purpose, largest ecosystem
BunPerformance, built-in bundler
DenoSecurity-first, built-in TypeScript

Why: Node = mature/biggest ecosystem. Bun = speed + bundler builtin. Deno = secure-by-default permissions + TS native.


3. Architecture

Layered Structure

Request Flow:
│
├── Controller/Route Layer
│   ├── Handles HTTP specifics
│   ├── Input validation at boundary
│   └── Calls service layer
│
├── Service Layer
│   ├── Business logic
│   ├── Framework-agnostic
│   └── Calls repository layer
│
└── Repository Layer
    ├── Data access only
    ├── Database queries
    └── ORM interactions

Why:

  • Testability: mock layers independently
  • Flexibility: swap DB without touching logic
  • Clarity: single responsibility per layer

Simplify when:

  • Small scripts → single file OK
  • Prototypes → less structure OK
  • Ask: "will this grow?"

4. Error Handling

Centralized

Pattern:
├── Create custom error classes
├── Throw from any layer
├── Catch at top level (middleware)
└── Format consistent response

Response Philosophy

Client response MUST include: HTTP status, error code (programmatic handling), user-friendly message. NEVER expose internal details, stack traces, DB errors, file paths, or library internals — these leak attack surface (security-critical).

Logs MUST capture: full stack trace, request context, user ID if available, timestamp.

Status Codes

SituationStatusWhen
Bad input400Client sent invalid data
No auth401Missing or invalid credentials
No permission403Valid auth, but not allowed
Not found404Resource doesn't exist
Conflict409Duplicate or state conflict
Validation422Schema valid but business rules fail
Server error500Our fault, log everything

5. Async Patterns

Pick

PatternUse When
async/awaitSequential async operations
Promise.allParallel independent operations
Promise.allSettledParallel where some can fail
Promise.raceTimeout or first response wins

Event Loop

I/O-bound (async helps):
├── Database queries
├── HTTP requests
├── File system
└── Network operations

CPU-bound (async doesn't help):
├── Crypto operations
├── Image processing
├── Complex calculations
└── → Use worker threads or offload

Don't Block Loop

  • Never sync methods in prod (fs.readFileSync etc.)
  • Offload CPU work
  • Stream large data

6. Validation

Validate at Boundaries

Where to validate:
├── API entry point (request body/params)
├── Before database operations
├── External data (API responses, file uploads)
└── Environment variables (startup)

Library Pick

LibraryBest For
ZodTypeScript first, inference
ValibotSmaller bundle (tree-shakeable)
ArkTypePerformance critical
YupExisting React Form usage

Philosophy

  • Fail fast: validate early
  • Specific: clear error messages
  • Trust nothing: even "internal" data

7. Security

Checklist

  • Input validation: all inputs validated
  • Parameterized queries: no string concatenation for SQL
  • Password hashing: bcrypt or argon2
  • JWT verification: always verify signature AND expiry
  • Rate limiting: protect from abuse
  • Security headers: Helmet.js or equivalent
  • HTTPS: everywhere in production
  • CORS: properly configured (explicit origin allowlist, never * with credentials)
  • Secrets: environment variables ONLY — never hardcode API keys, DB creds, JWT secrets, tokens; never commit .env; rotate any exposed secret immediately
  • Dependencies: regularly audited (npm audit, Dependabot)

Mindset

Trust nothing:
├── Query params → validate
├── Request body → validate
├── Headers → verify
├── Cookies → validate
├── File uploads → scan
└── External APIs → validate response

8. Testing

Strategy

TypePurposeTools
UnitBusiness logicnode:test, Vitest
IntegrationAPI endpointsSupertest
E2EFull flowsPlaywright

Priorities

  1. Critical paths: auth, payments, core business
  2. Edge cases: empty inputs, boundaries
  3. Error handling: failure modes
  4. Skip: framework code, trivial getters

Built-in Runner (Node.js 22+)

node --test src/**/*.test.ts
├── No external dependency
├── Good coverage reporting
└── Watch mode available

9. Anti-Patterns

DON'T:

  • Express for new edge projects (use Hono)
  • Sync methods in prod code
  • Business logic in controllers
  • Skip input validation
  • Hardcode secrets
  • Trust external data unvalidated
  • Block event loop w/ CPU work

DO:

  • Pick framework by context
  • Ask user prefs when unclear
  • Layered architecture for growing projects
  • Validate all inputs
  • Env vars for secrets
  • Profile before optimizing

10. Decision Checklist

Before implementing:

  • Asked user about stack pref?
  • Picked framework for THIS context? (not default)
  • Considered deploy target?
  • Planned error handling?
  • Identified validation points?
  • Considered security?

Remember: best practices = decision-making, not memorizing. Every project deserves fresh consideration.

Limitations

  • Use only when task matches scope.
  • Not substitute for env-specific validation, testing, or expert review.
  • Stop + ask if inputs, permissions, safety boundaries, or success criteria missing.

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.