nodebestpractices README

The project's README from github.com/goldbergyoni/nodebestpractices. As one markdown file: README.md.

Node.js Best Practices

Node.js Best Practices


102 items Last update: January 3rd, 2024 Updated for Node 22.0.0

Follow us on Twitter! @nodepractices


Read in a different language: CNCN, FRFR, BRBR, RURU, PLPL, JAJA, EUEU (ESES, HEHE, KRKR and TRTR in progress! )


🎊 2026 edition is here!



Welcome! 3 Things You Ought To Know First

1. You are reading dozens of the best Node.js articles - this repository is a summary and curation of the top-ranked content on Node.js best practices, as well as content written here by collaborators

2. It is the largest compilation, and it is growing every week - currently, more than 80 best practices, style guides, and architectural tips are presented. New issues and pull requests are created every day to keep this live book updated. We'd love to see you contributing here, whether that is fixing code mistakes, helping with translations, or suggesting brilliant new ideas. See our writing guidelines here

3. Best practices have additional info - most bullets include a 🔗Read More link that expands on the practice with code examples, quotes from selected blogs, and more information



By Yoni Goldberg

Learn with me: As a consultant, I engage with worldwide teams on various activities like workshops and code reviews. 🎉AND... Hold on, I've just launched my beyond-the-basics testing course, which is on a 🎁 limited-time sale until August 7th



Table of Contents

1. Project Architecture Practices (6)

  1.1 Structure your solution by components #strategic #updated
  1.2 Layer your components, keep the web layer within its boundaries #strategic #updated
  1.3 Wrap common utilities as packages, consider publishing
  1.4 Use environment aware, secure and hierarchical config #updated
  1.5 Consider all the consequences when choosing the main framework #new
  1.6 Use TypeScript sparingly and thoughtfully #new

2. Error Handling Practices (12)

  2.1 Use Async-Await or promises for async error handling
  2.2 Extend the built-in Error object #strategic #updated
  2.3 Distinguish operational vs programmer errors #strategic #updated
  2.4 Handle errors centrally, not within a middleware #strategic
  2.5 Document API errors using OpenAPI or GraphQL
  2.6 Exit the process gracefully when a stranger comes to town #strategic
  2.7 Use a mature logger to increase errors visibility #updated
  2.8 Test error flows using your favorite test framework #updated
  2.9 Discover errors and downtime using APM products
  2.10 Catch unhandled promise rejections #updated
  2.11 Fail fast, validate arguments using a dedicated library
  2.12 Always await promises before returning to avoid a partial stacktrace #new
  2.13 Subscribe to event emitters 'error' event #new

3. Code Style Practices (12)

  3.1 Use ESLint #strategic
  3.2 Use Node.js eslint extension plugins #updated
  3.3 Start a Codeblock's Curly Braces on the Same Line
  3.4 Separate your statements properly
  3.5 Name your functions
  3.6 Use naming conventions for variables, constants, functions and classes
  3.7 Prefer const over let. Ditch the var
  3.8 Require modules first, not inside functions
  3.9 Set an explicit entry point to a module/folder #updated
  3.10 Use the === operator
  3.11 Use Async Await, avoid callbacks #strategic
  3.12 Use arrow function expressions (=>)
  3.13 Avoid effects outside of functions #new

4. Testing And Overall Quality Practices (13)

  4.1 At the very least, write API (component) testing #strategic
  4.2 Include 3 parts in each test name #new
  4.3 Structure tests by the AAA pattern #strategic
  4.4 Ensure Node version is unified #new
  4.5 Avoid global test fixtures and seeds, add data per-test #strategic
  4.6 Tag your tests #advanced
  4.7 Check your test coverage, it helps to identify wrong test patterns
  4.8 Use production-like environment for e2e testing
  4.9 Refactor regularly using static analysis tools
  4.10 Mock responses of external HTTP services #advanced #new #advanced
  4.11 Test your middlewares in isolation
  4.12 Specify a port in production, randomize in testing #new
  4.13 Test the five possible outcomes #strategic #new

5. Going To Production Practices (19)

  5.1. Monitoring #strategic
  5.2. Increase the observability using smart logging #strategic
  5.3. Delegate anything possible (e.g. gzip, SSL) to a reverse proxy #strategic
  5.4. Lock dependencies
  5.5. Guard process uptime using the right tool
  5.6. Utilize all CPU cores
  5.7. Create a ‘maintenance endpoint’
  5.8. Discover the unknowns using APM products #advanced #updated
  5.9. Make your code production-ready
  5.10. Measure and guard the memory usage #advanced
  5.11. Get your frontend assets out of Node
  5.12. Strive to be stateless #strategic
  5.13. Use tools that automatically detect vulnerabilities
  5.14. Assign a transaction id to each log statement #advanced
  5.15. Set NODE_ENV=production
  5.16. Design automated, atomic and zero-downtime deployments #advanced
  5.17. Use an LTS release of Node.js
  5.18. Log to stdout, avoid specifying log destination within the app #updated
  5.19. Install your packages with npm ci #new

6. Security Practices (25)

  6.1. Embrace linter security rules
  6.2. Limit concurrent requests using a middleware
  6.3 Extract secrets from config files or use packages to encrypt them #strategic
  6.4. Prevent query injection vulnerabilities with ORM/ODM libraries #strategic
  6.5. Collection of generic security best practices
  6.6. Adjust the HTTP response headers for enhanced security
  6.7. Constantly and automatically inspect for vulnerable dependencies #strategic
  6.8. Protect Users' Passwords/Secrets using bcrypt or scrypt #strategic
  6.9. Escape HTML, JS and CSS output
  6.10. Validate incoming JSON schemas #strategic
  6.11. Support blocklisting JWTs
  6.12. Prevent brute-force attacks against authorization #advanced
  6.13. Run Node.js as non-root user
  6.14. Limit payload size using a reverse-proxy or a middleware
  6.15. Avoid JavaScript eval statements
  6.16. Prevent evil RegEx from overloading your single thread execution
  6.17. Avoid module loading using a variable
  6.18. Run unsafe code in a sandbox
  6.19. Take extra care when working with child processes #advanced
  6.20. Hide error details from clients
  6.21. Configure 2FA for npm or Yarn #strategic
  6.22. Modify session middleware settings
  6.23. Avoid DOS attacks by explicitly setting when a process should crash #advanced
  6.24. Prevent unsafe redirects
  6.25. Avoid publishing secrets to the npm registry
  6.26. 6.26 Inspect for outdated packages
  6.27. Import built-in modules using the 'node:' protocol #new

7. Performance Practices (2) (Work In Progress️ ✍️)

  7.1. Don't block the event loop
  7.2. Prefer native JS methods over user-land utils like Lodash

8. Docker Practices (15)

  8.1 Use multi-stage builds for leaner and more secure Docker images #strategic
  8.2. Bootstrap using node command, avoid npm start
  8.3. Let the Docker runtime handle replication and uptime #strategic
  8.4. Use .dockerignore to prevent leaking secrets
  8.5. Clean-up dependencies before production
  8.6. Shutdown smartly and gracefully #advanced
  8.7. Set memory limits using both Docker and v8 #advanced #strategic
  8.8. Plan for efficient caching
  8.9. Use explicit image reference, avoid latest tag
  8.10. Prefer smaller Docker base images
  8.11. Clean-out build-time secrets, avoid secrets in args #strategic #new
  8.12. Scan images for multi layers of vulnerabilities #advanced
  8.13 Clean NODE_MODULE cache
  8.14. Generic Docker practices
  8.15. Lint your Dockerfile #new



1. Project Architecture Practices

✔ 1.1 Structure your solution by business components

📝 #updated

TL;DR: The root of a system should contain folders or repositories that represent reasonably sized business modules. Each component represents a product domain (i.e., bounded context), like 'user-component', 'order-component', etc. Each component has its own API, logic, and logical database. What is the significant merit? With an autonomous component, every change is performed over a granular and smaller scope - the mental overload, development friction, and deployment fear are much smaller and better. As a result, developers can move much faster. This does not necessarily demand physical separation and can be achieved using a Monorepo or with a multi-repo

my-system
├─ apps (components)
│  ├─ orders
│  ├─ users
│  ├─ payments
├─ libraries (generic cross-component functionality)
│  ├─ logger
│  ├─ authenticator

Otherwise: when artifacts from various modules/topics are mixed together, there are great chances of a tightly-coupled 'spaghetti' system. For example, in an architecture where 'module-a controller' might call 'module-b service', there are no clear modularity borders - every code change might affect anything else. With this approach, developers who code new features struggle to realize the scope and impact of their change. Consequently, they fear breaking other modules, and each deployment becomes slower and riskier

🔗 Read More: structure by components



✔ 1.2 Layer your components with 3-tiers, keep the web layer within its boundaries

📝 #updated

TL;DR: Each component should contain 'layers' - a dedicated folder for common concerns: 'entry-point' where controller lives, 'domain' where the logic lives, and 'data-access'. The primary principle of the most popular architectures is to separate the technical concerns (e.g., HTTP, DB, etc) from the pure logic of the app so a developer can code more features without worrying about infrastructural concerns. Putting each concern in a dedicated folder, also known as the 3-Tier pattern, is the simplest way to meet this goal

my-system
├─ apps (components)
│  ├─ component-a
   │  ├─ entry-points
   │  │  ├─ api # controller comes here
   │  │  ├─ message-queue # message consumer comes here
   │  ├─ domain # features and flows: DTO, services, logic

nodebestpractices (goldbergyoni/nodebestpractices)

Searching Database…

这是什么?这是一份由社区维护、精心整理的清单,汇总了最重要的 Node.js 最佳实践、代码风格指南和架构建议,内容分章节组织,涵盖架构、错误处理、代码风格、测试、上线生产准备、安全、性能和 Docker。
这是可以直接动手用的库,还是只是参考文档?它是一份篇幅很长的 markdown 参考文档(作者称之为“活手册”),不是可以直接运行的库或工具。每一条都是清单项,附有简短说明,并可选择性地附上一篇深入文章的链接。
这份清单是怎么组织的?我该从哪里开始?内容分为 8 个编号章节(项目架构、错误处理、代码风格、测试、上线生产、安全、性能、Docker),每章都有带编号子实践的目录。你可以从第 1 章开始,也可以直接跳到与你当前工作相关的章节。
这份清单已经完成了吗,还是仍在编写中?大多数章节已经成熟,并每年更新(当前版本标注日期为 2026 年 7 月),但性能章节明确标注仍在编写中,因此各部分的完成度并不一致。
这份清单有其他语言的翻译吗?有。社区已提供中文、法语、巴西葡萄牙语、俄语、波兰语、日语和巴斯克语的翻译,西班牙语、希伯来语、韩语和土耳其语的翻译正在进行中。
有没有配套项目能用真实代码展示这些实践?有。作者开发了 Practica.js,这是一个独立的示例应用和脚手架模板,用真实可运行的代码演示了清单中的许多实践。
我怎么知道哪些实践最重要?重要条目会标记 #strategic 标签,用来突出影响最大的实践,例如按组件组织代码、集中处理错误以及使用 ESLint。
为什么 Node.js 最佳实践清单里会有 Docker 章节?因为 Node 应用通常以容器形式交付,所以这一包含 15 条内容的章节涵盖了容器相关的问题,例如多阶段构建、.dockerignore、明确的镜像标签,以及同时为 Docker 和 v8 设置内存限制。
Size
68 MB
Stars
105.7K
Updated
CommitJun 15
Age
9y
Commits · 90 Days