Node.js Application Security

Node.js Application Security

<strong>Nodejs is the popular server-side scripting language and its one of the widely used in the javascript world. Perhaps you might be using it in your projects.</strong>

Nodejs is the popular server-side scripting language and its one of the widely used in the javascript world. Perhaps you might be using it in your projects.

In this article, we will focus on some of the best practices of Nodejs, and how to make your app much more secured.

Here’s the quick rundown with some express/node js modules:


Schneier’s Law stated:

Anyone, from the most clueless amateur to the best cryptographer, can create an algorithm that he himself can’t break.
We might not know exactly what your secret algorithm is, and the fact that you yourself cannot break the cypher secret code is irrelevant. You should focus on generating or using the algorithm in such a way that others can’t break it.

An attacker may use common tools like substitution cyphers or polyalphabetic cyphers to recover the plaintext from the ciphertext. Do not use your own crypto, use standard one instead.

Bcrypt is one of the widely used and it has been around for quite some time and remains unbroken till date. It is a password hashing function.

Keep your dependencies up to date

Keeping third-party libraries up-to-date and keeping the track of it is quite important, as these libraries may risk your entire application.

HTTP response headers

helmet — It is an express module to set secure HTTP headers.

To install helmet-

 npm install --save helmet
const express = require('express'); 
const  helmet  = require('helmet');   
const  app     = express();


Use cookies securely

Install Express session: express-session stores session data on the server and id in the cookie itself, and not the session data

npm install --save express-session

var express = require('express');
var session = require('express-session');
app.use(session({secret: 'secret_'}));


const expressSession = require('cookie-session')

   var expiryDate = new Date( + 10 * 24 * 60 * 60 * 1000); // 10 days

    const session = expressSession({
      secret: sessionSecret,
      resave: false,
      saveUninitialized: true,
      cookie: {
        secureProxy: true,
        httpOnly: true,
        domain: '',
        expires: expiryDate



Cross-Origin Resource Sharing

The CORS mechanism describes new HTTP headers which provide browsers with a way to request remote URLs only when they have permission.

npm install cors --save
var cors = require('cors');

var app = express();


app.use(function(req, res, next) {
   res.header("Access-Control-Allow-Origin", "*");
   res.header('Access-Control-Allow-Methods', 'DELETE, PUT, GET, POST');
   res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");


Cross-Site Request Forgery

Install csurf:

npm install csurf
const cookieParser = require('cookie-parser');
const csrf = require('csurf');
const bodyParser = require('body-parser');
const express = require('express');

const csrfProtection = csrf({ cookie: true });
const parseForm = bodyParser.urlencoded({ extended: false });

const app = express();

// parse cookies
// we need this because "cookie" is true in csrfProtection

app.get('/form', csrfProtection, function (req, res) {
  // pass the csrfToken to the view
  res.render('send', { csrfToken: req.csrfToken() })
})'/process', parseForm, csrfProtection, function (req, res) {
  res.send('data is being processed')


Sending the token value back to the view

<form action="/process" method="POST">
  <input type="hidden" name="_csrf" value="{{csrfToken}}">
    <button type="submit">Submit</button>


Error Handling

Recommendations in the node.js community are that you pass errors around in callbacks (Because errors only occur for asynchronous operations) as the first argument

Using async/await you can now get asynchronous control flow as you want:

async function email(address) {
  try {
    // Do something asynchronous that may throw...
    await sendEmail({ to: address, from: '[email protected]', subject: 'Hello' });
  } catch(err) {
    if (err instanceof SomeCustomError) {
    } else {
      throw err


Nodejs API Authentication of JWT Tokens

REST(Representational state transfer) is the widely used web architecture as it is flexible and simple to use. Generating jwt tokens for authenticating users to obtain access to resources is one of the secured approaches.

This will enable the use of a token instead of username and password for accessing each resource

Tools to check the security risk of open-source dependencies

Sqreen** — **Itprotects your application from cross-site scripting, SQL injection, MongoDB injection, checks vulnerabilities against all broken files and 3rd party libraries, etc…

Snyk** — **It helps you find and fix known vulnerabilities in your dependencies

Acunetix — It helps in the vulnerability of web applications and frameworks like Angular, React, Vue, Ember.

OWASP provides the basis for testing the web application. To know more about it and more about web security, kindly visit -

If you liked it please leave some claps to show your support. Also, leave your responses below and reach out to me if you face any issues.

30s ad

Learn MEAN Stack By Building A ToDo App

ChatBots: Messenger ChatBot with API.AI and Node.JS

Master the MEAN Stack - Learn By Example

Build a Real Time web app in node.js , Angular.js, mongoDB

Supreme NodeJS Course - For Beginners

Top 7 Most Popular Node.js Frameworks You Should Know

Top 7 Most Popular Node.js Frameworks You Should Know

Node.js is an open-source, cross-platform, runtime environment that allows developers to run JavaScript outside of a browser. In this post, you'll see top 7 of the most popular Node frameworks at this point in time (ranked from high to low by GitHub stars).

Node.js is an open-source, cross-platform, runtime environment that allows developers to run JavaScript outside of a browser.

One of the main advantages of Node is that it enables developers to use JavaScript on both the front-end and the back-end of an application. This not only makes the source code of any app cleaner and more consistent, but it significantly speeds up app development too, as developers only need to use one language.

Node is fast, scalable, and easy to get started with. Its default package manager is npm, which means it also sports the largest ecosystem of open-source libraries. Node is used by companies such as NASA, Uber, Netflix, and Walmart.

But Node doesn't come alone. It comes with a plethora of frameworks. A Node framework can be pictured as the external scaffolding that you can build your app in. These frameworks are built on top of Node and extend the technology's functionality, mostly by making apps easier to prototype and develop, while also making them faster and more scalable.

Below are 7of the most popular Node frameworks at this point in time (ranked from high to low by GitHub stars).


With over 43,000 GitHub stars, Express is the most popular Node framework. It brands itself as a fast, unopinionated, and minimalist framework. Express acts as middleware: it helps set up and configure routes to send and receive requests between the front-end and the database of an app.

Express provides lightweight, powerful tools for HTTP servers. It's a great framework for single-page apps, websites, hybrids, or public HTTP APIs. It supports over fourteen different template engines, so developers aren't forced into any specific ORM.


Meteor is a full-stack JavaScript platform. It allows developers to build real-time web apps, i.e. apps where code changes are pushed to all browsers and devices in real-time. Additionally, servers send data over the wire, instead of HTML. The client renders the data.

The project has over 41,000 GitHub stars and is built to power large projects. Meteor is used by companies such as Mazda, Honeywell, Qualcomm, and IKEA. It has excellent documentation and a strong community behind it.


Koa is built by the same team that built Express. It uses ES6 methods that allow developers to work without callbacks. Developers also have more control over error-handling. Koa has no middleware within its core, which means that developers have more control over configuration, but which means that traditional Node middleware (e.g. req, res, next) won't work with Koa.

Koa already has over 26,000 GitHub stars. The Express developers built Koa because they wanted a lighter framework that was more expressive and more robust than Express. You can find out more about the differences between Koa and Express here.


Sails is a real-time, MVC framework for Node that's built on Express. It supports auto-generated REST APIs and comes with an easy WebSocket integration.

The project has over 20,000 stars on GitHub and is compatible with almost all databases (MySQL, MongoDB, PostgreSQL, Redis). It's also compatible with most front-end technologies (Angular, iOS, Android, React, and even Windows Phone).


Nest has over 15,000 GitHub stars. It uses progressive JavaScript and is built with TypeScript, which means it comes with strong typing. It combines elements of object-oriented programming, functional programming, and functional reactive programming.

Nest is packaged in such a way it serves as a complete development kit for writing enterprise-level apps. The framework uses Express, but is compatible with a wide range of other libraries.


LoopBack is a framework that allows developers to quickly create REST APIs. It has an easy-to-use CLI wizard and allows developers to create models either on their schema or dynamically. It also has a built-in API explorer.

LoopBack has over 12,000 GitHub stars and is used by companies such as GoDaddy, Symantec, and the Bank of America. It's compatible with many REST services and a wide variety of databases (MongoDB, Oracle, MySQL, PostgreSQL).


Similar to Express, hapi serves data by intermediating between server-side and client-side. As such, it's can serve as a substitute for Express. Hapi allows developers to focus on writing reusable app logic in a modular and prescriptive fashion.

The project has over 11,000 GitHub stars. It has built-in support for input validation, caching, authentication, and more. Hapi was originally developed to handle all of Walmart's mobile traffic during Black Friday.

Difference between AngularJS, React, Ember, Backbone, and Node.js.

The most common thing between all of them is that they are Single Page Apps. The SPA is a single page where much of the information remains the same and only some piece of data gets modified when you click on other categories/option.

Node.js Tutorial for Beginners | Node.js Crash Course | Node.js Certification Training

This courseis designed for professionals who aspire to be application developers and gain expertise in building real-time, highly-scalable applications in Node.js. The following professionals can go for this course :

Why learn Node.js?

Node.js uses JavaScript - a language known to millions of developers worldwide - thus giving it a much lower learning curve even for complete beginners. Using Node.js you can build simple Command Line programs or complex enterprise level web applications with equal ease. Node.js is an event-driven, server-side, asynchronous development platform with lightning speed execution. Node.js helps you to code the most complex functionalities in just a few lines of code...

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

The Complete Node.js Developer Course (3rd Edition)

Angular & NodeJS - The MEAN Stack Guide

NodeJS - The Complete Guide (incl. MVC, REST APIs, GraphQL)

Docker for Node.js Projects From a Docker Captain

Intro To MySQL With Node.js - Learn To Use MySQL with Node!

Node.js Absolute Beginners Guide - Learn Node From Scratch

React Node FullStack - Social Network from Scratch to Deploy

Selenium WebDriver - JavaScript nodeJS webdriver IO & more!

Complete Next.js with React & Node - Beautiful Portfolio App

Build a Blockchain & Cryptocurrency | Full-Stack Edition