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
- VoDaiLocz/kilo-kit-mcpedited, first seen Aug 21, 2026
- TheHiddenDeveloper/jarvis-skillsedited, first seen Aug 19, 2026
- ever-works/ever-worksedited, first seen Jul 19, 2026
- joabgonzalez/ai-agents-skillstheir own version, first seen Jun 8, 2026
- jornalistainclusivo/jinc-skillsedited, first seen Apr 22, 2026
- SKB3002/agenthubedited, first seen Apr 20, 2026
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.
tiendatworkSkill2d-games
2D game development principles. Sprites, tilemaps, physics, camera.
Also in 3 projects that use this
tiendatworkSkill3d-games
3D game development principles. Rendering, shaders, physics, cameras.
Also in 3 projects that use this
- +6 more from tiendatwork
Other versions11 projects use a version of this.
Word for word · 0
None found.
Edited · 9
- ever-works/ever-works★ 15755% same
- VoDaiLocz/kilo-kit-mcp★ 2755% same
- xfstudio/skills★ 955% same
- SKB3002/agenthub★ 455% same
- ai4brands-design/claude-skills★ 255% same
- jornalistainclusivo/jinc-skills★ 155% same
- tiendatwork/claude-skills★ 155% same
- HaiTrieu0902/agent-skills-kit★ 055% same
- TheHiddenDeveloper/jarvis-skills★ 054% same
Wrote their own version · 2
- mduongvandinh/ai-best-practices-skills★ 18same name
- joabgonzalez/ai-agents-skills★ 9same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository18 other files it gives its agents.
- AGENTS.mdAGENTS.md
- .agents/skills/composition-patterns/AGENTS.mdAGENTS.md
- .agents/skills/react-best-practices/AGENTS.mdAGENTS.md
- ui/AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- ui/CLAUDE.mdCLAUDE.md
- accessibilitySkill
- vercel-composition-patternsSkill
- frontend-designSkill
- nodejs-backend-patternsSkill
- vercel-react-best-practicesSkill
- seoSkill
- typescript-advanced-typesSkill
- viteSkill
- vitestSkill
- pupila-ai-reviewSkill
- pupila-fetchersSkill
- pupila-filtersSkill
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
- Distinctive: line 23
ASK user prefs when unclear
- Common: line 25
Don't default same solution every time
- Common: line 141
Ask: "will this grow?"
- Very specific: line 206
Never sync methods in prod (fs.readFileSync etc.)
- Distinctive: line 335
Use only when task matches scope.
- Distinctive: line 336
Not substitute for env-specific validation, testing, or expert review.
- Distinctive: line 337
Stop + ask if inputs, permissions, safety boundaries, or success criteria missing.
“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.
Files
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 tRPCComparison Principles
| Factor | Hono | Fastify | Express |
| Best for | Edge, serverless | Performance | Legacy, learning |
| Cold start | Fastest | Fast | Moderate |
| Ecosystem | Growing | Good | Largest |
| TypeScript | Native | Excellent | Good |
| Learning curve | Low | Medium | Low |
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:
- Deployment target?
- Cold start critical?
- Team experience?
- 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 APIsModule 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 casesRuntime Pick
| Runtime | Best For |
| Node.js | General purpose, largest ecosystem |
| Bun | Performance, built-in bundler |
| Deno | Security-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 interactionsWhy:
- 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 responseResponse 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
| Situation | Status | When |
| Bad input | 400 | Client sent invalid data |
| No auth | 401 | Missing or invalid credentials |
| No permission | 403 | Valid auth, but not allowed |
| Not found | 404 | Resource doesn't exist |
| Conflict | 409 | Duplicate or state conflict |
| Validation | 422 | Schema valid but business rules fail |
| Server error | 500 | Our fault, log everything |
5. Async Patterns
Pick
| Pattern | Use When |
async/await | Sequential async operations |
Promise.all | Parallel independent operations |
Promise.allSettled | Parallel where some can fail |
Promise.race | Timeout 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 offloadDon't Block Loop
- Never sync methods in prod (
fs.readFileSyncetc.) - 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
| Library | Best For |
| Zod | TypeScript first, inference |
| Valibot | Smaller bundle (tree-shakeable) |
| ArkType | Performance critical |
| Yup | Existing 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 response8. Testing
Strategy
| Type | Purpose | Tools |
| Unit | Business logic | node:test, Vitest |
| Integration | API endpoints | Supertest |
| E2E | Full flows | Playwright |
Priorities
- Critical paths: auth, payments, core business
- Edge cases: empty inputs, boundaries
- Error handling: failure modes
- Skip: framework code, trivial getters
Built-in Runner (Node.js 22+)
node --test src/**/*.test.ts
├── No external dependency
├── Good coverage reporting
└── Watch mode available9. 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.
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
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.

