8 práticas recomendadas para aumentar a segurança em Node.js

8 best practices to increase security in Node.js

Increase the security of your Node.js application! Dive into best practices – from using HTTPS, validating data, employing security headers, to regular dependency audits.

Imagem em destaque

In recent years, the popularity of Node.js has been steadily increasing. Big companies like Twitter, eBay, Netflix, Reddit, and Paypal use it to power their backends and handle growing traffic. And startups are also not left behind as they are adopting this Javascript runtime to build their websites and take advantage of its advantages.

8 práticas recomendadas para aumentar a segurança em Node.js 1

#1: Protect against query injections with parameterized queries

SQL/NoSQL injections are one of the most common attacks a website can suffer today. Malicious actors send queries as if they were user input and force the system to provide sensitive information by mistake. Typically this is what happens when you use JS strings or string concatenations to insert values ​​into queries.

Fortunately, you can avoid this by using one of the many Node.js libraries with built-in features against these injections. Mongoose is one of the best at this as it provides support for indexed parameterized queries. By doing this, you will treat all input as such, preventing any information from being confused with an executable SQL statement.

#2 Pay attention to HTTP headers

Let's face it: HTTP headers can be both beneficial and harmful. Using the wrong ones or even employing the right ones in the wrong places can lead to cross-site scripting and clickjacking, among other known attacks. What can you do? You can't get rid of HTTP headers, so you can do one of two things: pay attention to each one and evaluate them manually, or protect them with Helmet.

Helmet is a relatively small but quite powerful Node module that can help you improve your header security just by installing it. Of course, you can easily configure it to enhance its features, but overall, you don't need to do much to get help adding or removing headers.

#3 Don't run Node.js with a root user

This may seem like a pretty basic thing, but you'd be surprised how many developers don't pay attention to it. Running Node.js code with root access opens the door for any bad actor to attack you when you don't expect it. Using a root user is actually easier for specific tasks (like changing a directory that the user doesn't have permission to write to), but you should try some workarounds to prevent this from happening.

Yes, I understand if you see this as overkill, but it's worth pointing out that every time you run code with sudo, you are exposing yourself to attack. Even when this seems like the worst case scenario, always make sure to run code with non-root users.

#4 Be careful with evaluation

Or don't use it if possible. Sure, eval can make your code more dynamic, but it can also allow attackers to insert malicious code that your application will end up executing. Because eval executes any string as code, you can never be sure what type of input the eval statement will deal with. Naturally, this can lead to all kinds of security issues, like DoS attacks.

These attacks are at the extreme end of what you can suffer through assessment. You can use it and not have any problems. You can use it safely if you're careful enough, but that's the problem – you need to pay attention to a lot of details to avoid the wide range of problems that can arise.

#5: Use 2FA to stop automated attacks

A broken authentication system is one of the biggest vulnerabilities you can have. If you implement weak password and session management policies in your applications, you expose yourself to attackers who steal credentials and deploy malicious code on your websites. That's why you should consider the various aspects that come with authentication: password creation and recovery, ID management, etc.

You can always use existing solutions like OAuth to handle all of this, but there's something else you should use: two-factor authentication (2FA). You can integrate it with your app or website via npm or Yarn packages and generate unique tokens for all users.

#6 Accept only small payloads

Any Node.js application can receive large requests that can put its performance under threat. This is because the more significant the payload, the more processing power it will require, which will divert that power from other more critical tasks. Because a single thread executes the payload, an attacker can take over your system without sending many requests – just a few with a larger payload.

Fortunately, this is a program you can quickly solve using Express's body parser, a middleware that will parse the bodies of incoming requests before their handlers. Thus, you can limit the body size of all incoming requests and accept those that have a body size below an accepted predefined limit.

#7 Maintain all environments with different credentials and access levels

One of the biggest vulnerabilities you can face is leaving your web applications in the hands of weak security rules. This often happens when you leave user account passwords, package configurations, and access levels default across different environments. Both development and testing environments are generally less protected; Therefore, if your settings and passwords remain the same in production, you are exposed to misconfigurations and brute force attacks.

The solution to this is to adjust the default settings to ensure that each environment has different credentials and access levels. This ensures that no known vulnerabilities reach production.

#8: Monitor Dependencies

One of the most common things that happen when you work with Node.js is that you end up having too many dependencies in just one project. Therefore, if you don't control them, you could have multiple vulnerabilities and entry points for attackers to exploit. The solution? To keep a strict history of all dependencies in your projects.

This will let you know which dependencies you are using at all times and will give you the ability to know which ones you need to target. The best way to do this is to use tools like Snyk and npm audits, which can help a lot, especially if you use them in the context of a continuous improvement approach.

Stepping up your Node.js game.

These practices are just the tip of the iceberg. There are many more things you can do to up your security game in Node.js. Fortunately, there are many guides and tools you can follow to ensure you have the highest level of protection possible. I know doing this can sometimes be daunting, but it's the safest way to leverage all the benefits of Node without compromising the integrity of your web applications, aligning well with the responsibilities outlined in the NodeJS job description.

Source: BairesDev

Conteúdo Relacionado

O Rails 8 sempre foi um divisor de águas...
A GenAI está transformando a força de trabalho com...
Entenda o papel fundamental dos testes unitários na validação...
Aprenda como os testes de carga garantem que seu...
Aprofunde-se nas funções complementares dos testes positivos e negativos...
Vídeos deep fake ao vivo cada vez mais sofisticados...
Entenda a metodologia por trás dos testes de estresse...
Descubra a imprevisibilidade dos testes ad hoc e seu...
A nomeação de Nacho De Marco para o Fast...
Aprenda como os processos baseados em IA aprimoram o...
O Node.js, o popular tempo de execução JavaScript assíncrono...
A web está em constante evolução, e com ela,...
A Inteligência Artificial (IA) tem sido um tema cada...
Você já se sentiu frustrado com a complexidade de...
O OpenStack é uma plataforma de computação em nuvem...
Você já se sentiu frustrado com a criação de...
A era digital trouxe uma transformação profunda na forma...
Nos dias atuais, a presença digital é fundamental para...
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.