Last updated Aug 26, 2022

Nodejs Security Best Practices: A Developer Guide

Follow key security tips to protect your Node.js apps.

Nodejs Security Best Practices: A Developer Guide

In this article, we will discuss some major security concerns in modern web development and possible solutions to overcome them.  

So, let's get started...

1) COMPROMISED DATABASE:

Problem:

Suppose that an attacker gained access to our database, so they can easily steal your password or other important information.

Solution: 

In this case, to prevent even bigger problems, we must always encrypt passwords and password reset tokens, this way, the attacker can't at least, steal our user's password and also can't reset them. 

To summarize,

✔️ Strongly encrypt passwords with salt and hash (bcrypt)

✔️ Strongly encrypt password reset tokens (SHA 256)  

2) BRUTE FORCE ATTACKS:

Problem:

Brute Force Attacks are where the attacker basically tries to guess a password by trying millions and millions of random passwords until they find the right one.

Solution:

Here what we can do is to make the login request really slow and the Bcrpts bcrypt package actually does this for us.

Another strategy is to implement rate limiting, which limits the number of requests coming from one single IP.

Also, a nice strategy is to actually implement a maximum number of login attempts for each user.

For Example, we could make it so that after 10 failed attempts, the user would have to wait one hour until he can try again.

To summarize,

✔️ Use bcrypt (to make login requests slow) 

✔️ Implement rate limiting (express-rate-limit) 

✔️ Implement maximum login attempt  

3) CROSS-SITE SCRIPTING (XSS) ATTACKS:

Problem:

Cross-Site-Scripting is where the attackers try to inject scripts into our page to run his malicious code.

On the client side, this is especially dangerous because it allows the attackers to read the local storage.  

Solution:

The JSON web token should never be kept in local storage, for this reason.

Instead, it should be stored in an HTTP-only cookie that makes it so that browser can only receive and send the cookie but cannot access or modify it any way, and so that then makes it impossible for any attackers to steal the JSON web token that is stored in the cookie.

On the Backend side, in order to prevent XSS attacks, we should sanitize user input data and set some special HTTP headers, which makes these attacks a bit more difficult to happen.

To summarize,

✔️ Store JWT in HTTPOnly cookies

✔️ Sanitize user input data 

✔️ Set special HTTP headers (helmet package)

 4) DENIAL-OF-SERVICE (DOS) ATTACK:

Problem:

It Happens When the attackers send so many requests to a server that it breaks down and the application becomes unavailable.

Solution:

In this case, Implememitign Rate limiting is a good solution for this.

Also, we should limit the amount of data that can be sent in a body in a post or patch request.we can also, avoid using, so-called evil regular expressions to be in our code, and these are just regular expressions that take an exponential time to run for non-matching inputs and they can be exploited to bring our entire  application down.

To summarize,

✔️Implement rate limiting (express-rate-limit)

✔️ Limit body payload (in body-parser)

✔️ Avoid evil regular expressions  

5) NOSQL QUERY INJECTION:

Problem:

Here is what happens when an attacker, instead of inputting valid data, injects some query in order to create query expressions that are gonna translate to true.

For example, to be logged in even without providing a valid username and password

Solution:

Here Using Mongoose is actually a pretty good strategy for preventing these kinds of attacks because a good schema forces each value to have well-defined data, Which then effectively makes this type of attack very difficult to execute.

Also, it's a good idea to still sanitize input data, just to be sure.

To summarize,

✔️Use mongoose for MongoDB (because of SchemaTypes)

✔️ Sanitize user input data

So, these are some major common issues and attacks that can happen to the website and the solution you can implement to reduce them.

There are also some other things we should take care of to make sure our application is secure, as listed below:  

OTHER BEST PRACTICES AND SUGGESTIONS

✔️ Always use HTTPS

In a production application, all communication between server and client needs to happen over HTTPS, Otherwise,anyone can listen into the conversation and steal our JSON web Token

✔️Create random password reset tokens with expiry dates

Always creates random password tokens, not generated from dates or something like that, because they are effectively passwords and so, they should be treated as such, plus always give them expiry dates.

✔️ Deny access to JWT after password change

✔️ Don’t commit sensitive config data to Git

✔️ Don’t send error details to clients

✔️ Prevent Cross-Site Request Forgery (csurf package)

✔️ Require re-authentication before a high-value action

✔️ Implement a blacklist of untrusted JWT

✔️ Confirm user email address after first creating an account

✔️ Keep user logged in with refresh tokens

✔️ Implement two-factor authentication

✔️Prevent parameter pollution from causing Uncaught Exception

So, That's it, for now, hope you like this, and if then please share it with your friends.

Tags

Available for projectsLet’s build together

Need this built properly,
not just explained?

I take on Angular and NestJS work directly — auth systems, multi-tenant SaaS, API rewrites and the deploy pipeline underneath them. You talk to the person writing the code.

Projects delivered
20+ Projects delivered
Angular • NestJS
7+ years Angular • NestJS
Average reply time
1 day Average reply time

What I can help with

  • Auth and permissions systems
  • Multi-tenant SaaS foundations
  • API design and rewrites
  • Deploy pipelines and VPS setup
  • Bug fixing and performance optimization
Send me a message

Tell me about your project and I’ll get back with a realistic scope and price.

Turn
Your Ideas
Into Reality

Stay in the loop

Get the finished tutorials, projects and resources in your inbox.

Join 5,000+ developers and get new tutorials, source code, product updates and exclusive content — straight to your inbox.

  • No spam
  • Useful content only
  • Unsubscribe anytime

Subscribe to TutsCoder

Be the first to get new tutorials, projects and tips.

Join 5,000+ developers already learning with us.

Learn
Build
Grow

Discussion

Comments

Share your thoughts, ask questions or suggest improvements. Let’s learn and grow together!

Loading comments…

Join the discussion

Sign in to join the discussion. Your account also keeps your saved tutorials and path progress.