Blog

  • NodeJS Best Practices Guide

    Posted by Hotam Singh | Last Updated: 15-Jan-19

    In this article, we will go through some common coding styles which will make our application pretty good in terms of readability, performance, security etc. 
    Today I will be discussing the most important NodeJS best practices for 2018. Let’s start!

    NodeJS Best Practices for 2018


    1. Use ES6


    ES2015 was the last release which had many new things but now ES6 released. It provides support for all ES2015 features 
    and most importantly tt is TypeScritp.however, a lot has changed since.

    If you are using the latest NodeJS LTS version you do not need to use the whole feature set of ES2015.

    2. Use Promises


    The concept of promises is not new to web development. Promises are a concurrency primitive, first described in the 80s.
    Many of us have already used promises in the form of libraries such as q, bluebird etc.
    Now Promises are part of most modern programming languages to make your programming readible and easier.

    Just take a look on the following example. It reads a file, parses that file and then prints name of the package.

    fs.readFile('./package.json', 'utf-8', function (err, data) {
      if (err) {
        return console.log(err)
      }
    
      try {
        JSON.parse(data)
      } catch (ex) {
        return console.log(ex)
      }
      console.log(data.name)
    })
    
    


    Its a quite long code and sometimes not more readable? Promises help you with that:

    fs.readFileAsync('./package.json').then(JSON.parse).then((data) => {
      console.log(data.name)
    })
    .catch((e) => {
      console.error('error reading/parsing file', e)
    })
    

     

    As we know, fs does not supprt Promises but make it work, you need to promisifyAll. 

    For example:

    var Promise = require('bluebird');
    var fs = Promise.promisifyAll(require("fs"));
    fs.readFileAsync('./package.json').then(JSON.parse).then((data) => {
      console.log(data.name)
    })
    .catch((e) => {
      console.error('error reading/parsing file', e)
    })
    

     

    3. Use Async/Await


    Async/Await is another most popular way to handle callback hell probles. Just see below example:

    Example of a Callback:

    app.get('/', function(){
        function1(arg1, function(){
            ...
        })
    });
    

     

    It is a simple function and suppose there are many functions one inside another. This situation is commonly known as a callback hell.
    Problem with this kind of code is that this code can get messy and can cause a lot of trouble. 

    Example: Before async/await

    function function1(req, res){
      return request.get('http://localhost:3000')
       .catch((err) =>{
         console.log('found error');
    }).then((res) =>{
       console.log('get request returned.');
    });
    

     

    Example: After async/await

    async function fun1(req, res){
      let response = await request.get('http://localhost:3000');
        if (response.err) { console.log('error');}
        else { console.log('fetched response');
    }
    

     

    4. Use the JavaScript Standard Style


    Use javascript Standards while writing JS code.

    5. Use Docker - Containers are Production Ready.


    You can use of Docker images as deployment artifacts - Docker containers wrap up a piece of software(or an application) in a complete filesystem.
    It contains everything an application needs to be run: code, system tools, runtime, system libraries.

    But why should you start using Docker?

    • It enables your applications to run in isolation,
    • It makes deployments more secure,
    • Docker images are lightweight,
    • You can mirror production environments locally.

    6. Monitor your Application


    Its a general scenario when something breaks in your NodeJS application. You shold have awareness about your application.
    you should be the first one to know about your app rather than your customers.

    Prometheus is one of the open-source solution. You can monitor your application with Prometheus. Prometheus is an open-source systems monitoring and alerting tool.

    7. Use Messaging for Background Processes


    We use messaging for background processes. Suppose, you are using HTTP for sending messages, and receiver party is down. 
    All your messages will be lost. We use messaging queues for this purpose. If the receiving service is down, the messages will be kept, and will be processed later when receiver service is up. 

    You have lots of options for messaging queues:

    • RabbitMQ
    • Kafka
    • NSQ
    • AWS SQS

    8. Secure Your Applications


    Most and important part for any kind of application is to secure application. Securing your users and its data should be one 
    of your top priorities.

    We should take care of below points in terms of security like:

    • Session Management
    • Security HTTP Headers
    • Brute Force Protection
    • Insecure Dependencies
    • Data Validation

     

     

     

     

     

     

     

     

     

     

     

     

     

Tags: nodejs