DEV Community

Cover image for Best practices for Node.js
YogitaKadam14
YogitaKadam14

Posted on

Best practices for Node.js

In this article I will cover best practices for writing Node.js

NodeJS has become tremendously popular and is one of the most popular runtime environments for web servers. It is an open source, a cross-platform runtime environment for developing server-side applications, or more precisely, code that run on a server.
Node.js is an asynchronous event-driven JavaScript runtime and is the most effective when building scalable network applications. Node.js is free of locks, so there's no chance to deadlock any process.

Project structure
Everything has to have its place in our application, and a folder is the perfect place to group common elements. In particular, we want to define a very important separation
Image description

Use HTTP Methods & API Routes
Use HTTP Status Codes Correctly
If something goes wrong while serving a request, you must set the correct status code for that in the response:

  1. 2xx, if everything was okay,
  2. 3xx, if the resource was moved,
  3. 4xx, if the request cannot be fulfilled because of a client error (like requesting a resource that does not exist),
  4. 5xx, if something went wrong on the API side (like an exception happened). If you are using Express, setting the status code is as easy as res.status(500).send({error: 'Internal server error happened'}). Similarly with Restify: res.status(201)

Use camelCase
It is recommended to use lowerCamelCase when naming constants, variables, and functions and UpperCamelCase (capital first letter as well) when naming classes.
This is universally accepted conventions and developers across the globe can easily identify and differentiate objects and classes when using this naming convention.

Use Environment Variables
A .env file is a plain text document. It should be placed in the root of your project. You specify key value pairs, and you can write single line comments using #. Here is an example how a .env file looks like:
Image description

Avoid callbacks - Use async-await
We can avoid the callback hell with the help of Promises. Promises in javascript are a way to handle asynchronous operations in Node.js. It allows us to return a value from an asynchronous function like synchronous functions. When we return something from an asynchronous method it returns a promise which can be used to consume the final value when it is available in the future with the help of then() method or await inside of async functions

Avoid Anonymous Functions

  1. Named function can be re-used over an order again in other parts of the project as well and this reduces code redundancy.
  2. If you find a bug in the code that creates an order, you fix that bug only in once place i.e. postOrderTasks() method and it will reflect in all places - saves time.

Use Refactoring of API calls
Refer Link: Refactoring of API calls

Confirm that your app restarts automatically
A dependency mistake can bring down your app even if you use the best error handling standards in development. Instead, use a process manager to ensure that the app recovers gracefully from a runtime fault or when the server fails.
Aside from that, there is another case in which you must restart your program. And that situation is if the entire service that you are running fails. In this instance, you want your program to continue as soon as possible. You can also utilize PM2 Keymetrics to manage your process.Ref. PM2 Keymetrics

Make use of Gzip compression
The server can use Gzip compression to compress the response before transmitting it to a web browser, reducing time lag and latency. This is one of the top NodeJS best practices in 2022-23.

Making the Server Restart Automatically After Updating a File
Every time when we make changes to the code, we have to restart the server to reflect those changes.
To avoid having to restart the server manually, let's install nodemon, an npm package that automatically restarts the server when changes are made to a file.
npm install -g nodemon

Use Const Over Let, Do Not Use Var
Before ES6, the var keyword was used to declare a variable in JavaScript
Variables declared using the var keyword are either globally or functionally scoped, they do not support block-level scope. This means that if a variable is defined in a loop or in an if statement it can be accessed outside the block and accidentally redefined leading to a buggy program. As a general rule, you should avoid using the var keyword.

Error Handling
To handle error in node.js we should know some key concepts like callback functions, Asynchronous functions like a promise, and async-await, try.. catch block, throw keyword, error object.

Add comments
A comment is a description of a program about how it works in a simple readable format. These are usually used at places where some additional clarity needs to be provided to the developer who is reading through the code.

Application testing
Implementing code quality testing at any project stage is never too late. Begin small and straightforward.

Create a Proper API Documentation
The following open-source projects can help you with creating documentation for your APIs:
APIBluePrint
Swagger

In this article, I have listed the best practices for Node.js development. These practices helps you to write better code for the Node.js app. You can use a combination of best Node.js practices.

Top comments (1)

Collapse
 
fruntend profile image
fruntend

Đ¡ongratulations đŸ¥³! Your article hit the top posts for the week - dev.to/fruntend/top-10-posts-for-f...
Keep it up đŸ«°