Skip to main content




La seguridad es un tema de suma importancia en la actualidad, si has llegado a este práctico tutorial seguramente be porque te preocupa el nivel de seguridad y fiabilidad de tus programas. Sigue leyendo para que aprendas a aumentar la seguridad de tu propia App.

Let's get started and secure our app with Node.js using proper coding, tools, and trading habits!

1. Applying secure encryption forms

  • First: avoid using eval

You may not know this information, but eval puede abrir tu aplicación para ataques de inyección de código. Trata de no usarlo, pero si tienes que hacerlo, nunca inyectes entradas de Username no validadas en eval.

Eval isn't the only one to avoid for this: deep down, each of the following expressions uses eval:

setInterval (String, 2)
setTimeout (String, 2)
new Function (String)

  • Second: try to always use the instruction 'use strict'

With 'use strict' tu puedes optar por usar una «variable» restringida de JavaScript. Esta variable, elimina algunos errores silenciosos y los desecha todo el tiempo.

'use strict' delete Object.prototype // TypeError var obj = {a: 1, a: 2} // syntax error
  • Third: try to handle mistakes with extreme care

During different error scenarios, your application can lose sensitive data about the underlying infrastructure, such as: X-Powered-By: Express.

Stack traces are not treated as vulnerabilities by themselves, but they often reveal information that may be of interest to an attacker. Providing debugging information as a result of operations that fail is considered bad practice. You should always register them, but never show them to users.

  • Fourth: Try to make a static analysis from your database

Static analysis of your application's database code can detect many errors. For that we suggest using ESLint with the standard code style.

Running your services in production safely

Using the proper code style is not enough to efficiently protect Node.js applications, you also need to be careful how you run your services in production.

  • Fifth: avoid running your processes with superuser rights

Unfortunately, we see that this case happens a lot: developers are running their Node.js application with rights to Super useras they want it to be heard on port 80 or 443.

Esto está muy mal. En el caso de un error o bug, su proceso puede hacer caer todo el sistema, ya que tiene credenciales para hacer cualquier cosa.

En lugar de esto, lo que puedes hacer es configurar un server o proxy HTTP para reenviar las solicitudes. Puede ser nginx o Apache.

  • Sixth: configure the headers Required HTTP

There are some security-related HTTP headers that your site should set. These headers are:

  • Strict-Transport-Security: este refuerza las conexiones seguras (HTTP sobre SSL/TLS) al servidor.
  • X-Frame-Options: provides you with clickjacking protection
  • X-XSS-Protection: puede habilitar el filtro XSS (cross-site scripting) integrado en los browsers Web más recientes.
  • X-Content-Type-Options: este evita que los navegadores olfateen una respuesta alejada del type of content declarado.
  • La política de seguridad de contents previene una amplia gama de ataques, incluyendo secuencias de comandos entre sitios y otras inyecciones entre sitios.

In Node.js it is easy to configure them using the Helmet module:

var express = require ('express') var helmet = require ('helmet') var app = express () app.use (helmet ())

Helmet is also available for Koa: koa-helmet.

  • Seventh: carry out a proper session management

La siguiente lista de marcas debe ser establecida para cada cookie:

  1. secure:  East attribute le dice al browser que sólo envíe la cookie si la petición se está enviando a través de HTTPS.
  2. HttpOnlyly: este atributo se utiliza para ayudar a prevenir ataques tales como scripts cruzados, ya que no permite el acceso a la cookie a través de JavaScript.
  • Eighth: Establishment of cookie application environment

  1. domain: este atributo se utiliza para comparar con el domain del servidor en el que se está solicitando la Url. Si el dominio coincide o es un subdomain, el atributo de ruta se comprobará a continuación.
  2. path: In addition to the domain, you can specify the URL path for which the cookie is valid. If the domain and path match, then the cookie will be sent on request.
  3. expires: This attribute is used to set persistent cookies since the cookie does not expire until the set date is exceeded.

In Node.js you can easily create this cookie using the cookie package. Again, this is pretty low so you'll probably end up using a wrap, like the cookie session.

var cookieSession = require ('cookie-session') var express = require ('express') var app = express () app.use (cookieSession ({name: 'session', keys: [process.env.COOKIE_KEY1, process. env.COOKIE_KEY2]})) app.use (function (req, res, next) {var n = req.session.views || 0 req.session.views = n ++ res.end (n + 'views')}) app.listen (3000)

Consider the tools to use

Congratulations, you are almost at the end of the article! If you've followed this tutorial and performed the above steps thoroughly and to the letter, you only have one area to cover in terms of Node.js security. Let's dive into using the right tools to look for module vulnerabilities!

  • Ninth: search vulnerabilities with Retire.js

The target from Remove.js is to help you detect the use of versions of modules with known vulnerabilities.

Just install with:

npm install -g remove

After that, run it with the command withdraw will look for vulnerabilities in the directory node_modules. (Also note that remove.js not only works with node modules but also with front-end libraries).

  • Tenth: audit your modules with the Node CLI security platform

nsp is the main command line interface for the Node security platform. Allows you to audit a file package.json or npm-shrinkwrap.json contra la API del NSP para comprobar si hay módulos vulnerables.

npm install nsp --global # From inside your project directory nsp check

Node.js security isn't a big deal after all, right? I hope that you have found these rules useful and necessary to secure your Node.js applications, and that you follow them in the future as security is part of your job. Congratulations!