Node.js Best Practices To Follow In 2021

Node.js Best Practices To Follow In 2021

Even though only 12 years old, Node.js has emerged to be one of the most popular web development frameworks in the last decade. Built on Chrome’s V8 JavaScript engine, Node.js projects are easy to start. Being an asynchronous event-driven JavaScript-based runtime, Node.js is widely used for building lightweight and scalable network-driven applications. Node.js apps can be scaled-up easily in both directions- horizontal and vertical. Node.js apps are used for both client-side and server-side applications. It has an open-source JavaScript runtime environment/model which provides single module caching. Here we’ll see some of the best practices for Node.js development.

With these best practices, app automatically is able to minimize Javascript runtime errors and turn it to high performing, robust node.js apps and node processes. Knowing the important JavaScript concepts will help every Node.js programmer to develop a high performing Node.js app. You can know these javascript concepts at- 10 JavaScript concepts every Node.js programmer must master.

Node.js Best Practices To Follow In 2021-

1. Take A Layered Approach-

Node.js frameworks lets you to define route handlers as callback functions that are executed when a client request is received. With the amount of flexibility that these frameworks provide, it might be enticing to define all business logic directly inside those functions. If you start in this way, you’ll get to know that things can quickly escalate and before you know it,  your petite server routes file can turn into a clunky, unwieldy and messy blob of code that is difficult to read, maintain and unit test. Hence it is good to implement the ‘separation of concerns’ programming principle. According to this, we should have different modules to address different concerns pertinent to our app. For server side apps, different modules should take the responsibility of catering to different aspects of processing a response for client request. Usually, this is likely to unfold as-

Client request, business logic + some database manipulation- returning the response. These aspects can be handled by programming three layers as shown below-

Controller Layer-

In this module of code, API routes are defined. Here you define only your API routes. In route handler functions, you can deconstruct the request object, select the important data parts and send them to the service layer for processing.

Service Layer-

Here business logic lives. It contains a set of classes and methods that take singular responsibility and are reusable. Service layer allows you to effectively decouple the processing logic from where the routes are defined.

Data Access Layer –

This layer can take up the responsibility of talking to database-fetching from, writing to and updating it. All SQL queries, database connections, models, ORM should be defined here. 

Three layer setup serves as a reliable scaffolding for most Node.js apps, which makes your apps easy to code, maintain, debug and test. 

2. Use npm For A New Project-

Npm init will generate a package.json file for project which shows all the packages/node apps of npm install has the information of your project.

$ mkdir demo-node app
$ cd demo-node app
$ npm init –yes

Now, you have to specify an engine’s key with currently installed version of node (node -v): 

"engines": {
  "node": "10.3.16"
}

3. Use Linting Packages-

There linting tools available, ESLint is one that most popular linting package that is used to check possible errors in code and also check code styles to meet best practices standards. It detects issues to any code patterns that could lead to any security threats and possible app-breaking that could occur in the future. There are some tools available that automatically format code and put it in a more readable way. It also resolves minor syntax errors like adding semicolons at the end of each statement etc.

Know the best Node.js packages to improve developer productivity at- 15 Essential Node.js Packages To Improve Developer Productivity.

4. Proper Naming Conventions For Constants, Variables, Functions, And Classes-

You should use all constants, functions, variables and class names in lowercase when we declare them. Also, you should not use any short forms rather than using only full forms that easily understandable by everyone using it. You should use underscore between two words.

Code Example-

//for class name we use Uppercase
class MyClassExample {}
// Use the const keyword and lowercase
const conf = {
Key: ‘value’
};
// for variables and functions names use lowercase
let variableExample = ‘value’;
function foo() {}

5. Use Of Strict Equality Operator (===) –

Use strict equality operator === rather than weaker abstract equality operator = ==, == will convert two variables to a common type then compare them while === doesn’t type case variables, and ensures that both variables are of the same type and equal.

Example-

null == undefined //true
true == ‘true’ //false
False == undefined //false
“ == ‘0’    //false
False == ‘0’   //true
0 == ‘0’       //true
‘\t\r\n’ == 0  //true
0==”      //true
False == null    //false

Above statements will return false when === is used.

6. Wrap Common Utilities As npm Package-

Generally, large app/ project has the same code used repeatedly multiple times at different locations. We can combine them into a single private package and use that package at various places within our application.

Npm install eliminates code duplication and makes code more manageable.

7.Separate Express ‘app’ And ‘server’-

One of the common mistake of developers is defining the entire express application on a single huge file. Rather than doing such, we should separate the ‘Express’ definition into minimum two different files.  One for API declaration (app.js) and another one for network concerns. You can also locate our API declaration within multiple components.

8. Avoiding Garbage In-App-

Node.js has a default limit of 1.5 GB but still it uses greedy and lazy garbage collector. It holds up until the entire memory is utilized and gets recovered on its own. If you want more control over the garbage collector then we can set the flags on V8.

Web: node --optimize_for_size --max_old_space_size=920 --gc_interval=100 server.js

Also, you can try to run the app using Docker image. This is important if the app is running in an environment with less than 1.5 GB of available memory. For instance, if you’d like to tailor a node.js to 512 MB container, go with-

Web: node --optimize_for_size --max_old_space_size=460 --gc_interval=100 server.js

9. Using Async-Await Or Promises-

Using javascript ‘synchronous function’ for multiple callbacks inside promises is good practice to handle async errors results in a callback hell problem. We can take a look at the available libraries or async and await of javascript to beat this issue. Process manager will use the promise function to catch code errors. It reduces code complexity and makes code more readable.

Code Example –

return A()
 .then((a) => B(a))
 .then((b) => C(b))
 .then((c) => D(c))
 .catch((error) => logger.error(error))
 .then(E())
Code Example - using async/await to catch errors
async function E() {
 try {
 const a= await A();
 const b= await B(a);
 const c= await C(c);
 return await D(c);
}
catch(error) {
logger.error(error);
}
}

10. Validating Request Body-

Developers can use available open-source packages like Joi to ensure the request body is proper and does not contain any malicious content. We can validate all the request parameters and body parameters to meet the expected schema prior to executing actual logic. By following this we can throw an error to the user input that the requested body is not valid before executing actual logic.

11. Error Catching –

Errors allows developers to understand the inaccuracies and vulnerabilities in their code by alerting them when their code breaks. They also provide relevant data about what went wrong, where, and what should be done to make amends. Rather than letting Node.js throw errors, interrupt code execution, even fail at times, we’d take charge of our application’s control flow by handling these error conditions. We can accomplish this through exception handling with try/catch blocks. By allowing developers to programmatically oversee such exceptions, it keeps things stable, encourages simpler debugging, and also prevents a poor end-user experience. 

Basic try/catch block example in Node.js-

try{
    If (xyzHappens) {
      throw “my error message “; //
}
}
catch (e) {
console.log(e); //
}
finally  {
console.log(“Finally executed!”);
}

12. Follow Good Generic Coding Practices-

  • DRY (Don’t Repeat Yourself)
  • Single Responsibility Principle (SRP)
  • “Keep it simple, stupid” (KISS)
  • Separation of Concerns
  • YAGNI (You ain’t gonna need it)
  • Avoid premature optimization
  • S.O.L.I.D programming principles
  • Dependency injection

13. Use Application Monitoring Tools-

For large-scale apps development, main goal is to understand how users interact with application: about which routes or features are commonly used, about commonly performed operations etc. Also, there is a focus to evaluate performance metrics, quality issues, bottlenecks, common errors etc and using that data to make the necessary changes and improvements. Here comes the web app monitoring tools. ScoutAPM tool allows you to constructively analyze and optimize performance of your web application. It shows real-time insight and hence you can rapidly detect and solve issues before the customer ever sees them.

Final Words-

These are some of the Node.js best practices that will help you for effective Node.js development. There can be few others too. Beginners can adopt them from the beginning of their development journey to produce high-quality production applications. These best practices can also be equally valuable for experienced developers to improve app performance. 

Are you thinking of using Node.js for your next project? Then, you must know these best practices before you start development. You can also consult with Solace experts for an effective Node.js development. Hire Node.js developers of Solace team for optimized and secured node.js app development. Connect with Solace and get a free quote for an node.js development with improved performance. We will be happy to help you.

Related Post