Structure code in better way
Always try to work on modular approach or in the form of tiny independent chunks. Having this approach, we can avoid complexities by making the code easier for the other developer who will work on the app in future.
When we write code , we might think we know how it works but it might be a problem we come back to same code after some time.
User Async-Await or promises for error handling.
Handling async errors in callback style is probably the fastest way. We can also perform the similar kind of task with try catch block. The best gift you can give to your code is using a reputable promise library or async-await instead which enables a much more compact and familiar code syntax like try-catch
Always Use Asynchronous Code
When we work on Node, the synchronous code is limited to writing CLI commands or scripts which are not related to web apps. If we’re a Node developer, we’re probably building NodeJs sample application or web apps for the most part, so the async code is the best way to avoid blocking threads
Cluster to improve performance and reliability of the application
As we know, By default Node.js is run in a single process. Ideally, we want one process for each CPU core so that we can distribute the work load across all the cores available on the system. This improves scalability of web apps processing HTTP requests and performance in general. In addition to this, if one worker crashes, the others are still available to handle requests.
Set Security HTTP Headers and Use Helmet if you’re writing a web app
- XSS Protection
- Prevent Clickingjacking using X-Frame-Options
- Enforcing all connections to be HTTPS
- Setting a Context-Security-Policy header
- Disabling the X-Powered-By header so attackers can’t narrow down their attacks to specific software
Instead of remembering to configure all these headers, Helmet will set them all to sensible defaults for you, and allow you to tweak the ones that you need.
Always Avoid Blocking Require
Always place all your require statements at the top of the file. This is because our files in the app run synchronous, so it will block the execution.
Require works by importing a file or module that was exported. But require is cached, so there won’t be any major changes to the resolved filename, just the code from the module will be executed and loaded into the variable for that single process.