Node.js Application Security

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: '', 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


Node.js Application Security
21.80 GEEK