Best Practices: Node JS Security
Tags: webdev, beginners, programming, javascript
Published: 2021-11-25 11:28:23

As programmers, we must ensure that our web applications are safe.
In this short post, I'll go through a few methods for securing your web app.

Any flaw can result in the loss of data, effort, or even the program itself. My focus is on Node Js but this principle is applicable to other languages too.
![security](https://media.giphy.com/media/3o6MbmTd7iUDK5AiHu/giphy.gif)

---

## 🥦 API secrets should never be shared. 
 Don't over expose the data you are sending to the front end.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xhl764iarwtgntn5atrk.PNG)
The above response can be replaced with `user successfully created`. 

---

## 🥦 Use helment
<mark>Helmet </mark> helps you secure your Express apps by setting various HTTP headers. It's not a silver bullet, but it can help. [source](https://www.npmjs.com/package/helmet)
```Javascript
const helmet = require('helmet')
app.use(helmet())
```
🎯 Your headers would appear like this if you didn't use <kbd>helmet</kbd>. 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zmb15vnz7g245u0va2eq.PNG)


🎯 With helmet it looks like 👇🏿
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z16gfizb0gsqka5r5iwc.PNG)
  
These two lines of code can aid in the protection of sensitive data on your website. 

---

## 🥦 Deprecated or vulnerable versions of Express should not be used.
We get deprecated warnings more often than not.
Ensure that your packages are up to date or  you transition to the most recent release. 
```Javascript
app.use(bodyParser()); //Now deprecated
```

---

## 🥦 Environment Variable
When I first started learning web development, one of the first harsh warnings I received came from a senior developer.
"Make sure you save your API keys and other information in a safe place. <kbd>.env</kbd>".
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/71sfohzj8zdf1f9gw65w.PNG)

---
 
## 🥦 Rate limiter
To keep your applications safe,
You must build some sort of rate-limiting for brute force assaults.
The rate-limiter package in Node.js can be used. 
<kbd>npm install express-rate-limit</kbd>
```Javascript
const rateLimit = require("express-rate-limit");
const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100 // limit each IP to 100 requests per windowMs
});

//  apply to all requests
app.use(limiter);
```
[source](https://www.npmjs.com/package/express-rate-limit)

---

## 🥦 Passwords should not be stored in plain text.
There are libraries that assist in the conversion of plain passwords to hashed passwords. <kbd>bycrypt</kbd> is one such library. 

```Javascript
const bcrypt = require('bcrypt');
const saltRounds = 10;
const myPlaintextPassword = 's0/\/\P4$$w0rD';
const someOtherPlaintextPassword = 'not_bacon';
```
It is critical that you utilize the most recent library. 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wqvrrwpdczuql368k18o.PNG)
Consider the difference between< kbd>bcrypt</kbd> and <kbd>bcryptjs</kbd>. I would want to use libraries that are actively maintained.
 
## Limit the amount of information shared to the client
For example in the code  below the password is removed from the data sent back to the user <kbd> { password: 0 }</kbd> this is called <mark>Projection</mark>.
```Javascript
router.get('/me', VerifyToken, function(req, res, next) {

    User.findById(req.userId, { password: 0 }, function(err, user) { //{password: 0 is called projection i.e hide certain infos from the fetched data}
        if (err) return res.status(500).send("There was a problem finding the user.");
        if (!user) return res.status(404).send("No user found.");
        res.status(200).send(user);
    });

});
```

One security-conscious statement : You should never send a "user not found" message to a user (or tell them their password is incorrect).
This is known as an account enumeration vulnerability <mark>account enumeration vulnerability</mark>).
This would allow someone else to discover whether or not a user exists in your system, allowing them to utilize the information for spam lists, phishing, and other purposes. 

It's preferable to simply state that the credentials provided were incorrect or something like that. 

## Conclusion
This is just a basic guide to adding security to your web app.
Look into additional options for securing your server. 

## Discuss 
What other procedures or strategies do you employ in order to secure your online application? 


## Reference
[Best Practice-Security](https://expressjs.com/en/advanced/best-practice-security.html)

Thanks for reading
![thanks](https://media.giphy.com/media/mVJ5xyiYkC3Vm/giphy.gif)