DEV Community

Cover image for Best Practices: Node JS Security
Abayomi Ogunnusi
Abayomi Ogunnusi

Posted on

Best Practices: Node JS Security

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


🥦 API secrets should never be shared.

Don't over expose the data you are sending to the front end.
Image description
The above response can be replaced with user successfully created.


🥦 Use helment

Helmet helps you secure your Express apps by setting various HTTP headers. It's not a silver bullet, but it can help. source

const helmet = require('helmet')
app.use(helmet())
Enter fullscreen mode Exit fullscreen mode

🎯 Your headers would appear like this if you didn't use helmet.
Image description

🎯 With helmet it looks like 👇🏿
Image description

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.

app.use(bodyParser()); //Now deprecated
Enter fullscreen mode Exit fullscreen mode

🥦 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. .env".
Image description


🥦 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.
npm install express-rate-limit

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);
Enter fullscreen mode Exit fullscreen mode

source


🥦 Passwords should not be stored in plain text.

There are libraries that assist in the conversion of plain passwords to hashed passwords. bycrypt is one such library.

const bcrypt = require('bcrypt');
const saltRounds = 10;
const myPlaintextPassword = 's0/\/\P4$$w0rD';
const someOtherPlaintextPassword = 'not_bacon';
Enter fullscreen mode Exit fullscreen mode

It is critical that you utilize the most recent library.
Image description
Consider the difference between< kbd>bcrypt and bcryptjs. I would want to use libraries that are actively maintained.

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

Thanks for reading
thanks

Discussion (0)