How to secure NodeJS REST API from Attacks
Tags: node, secure, api, attacks
Published: 2022-04-30 15:09:47

Being a backend developer, One of the most important task is to make the API secure from different types of attacks. As a backend developer, you could have heard about different attacks on servers like XSS, SQL Injection attacks, DOS attacks, and other similar attacks. 

It is very necessary to write the code in a way so that it can be unaffected from these attacks. So in this article, we will see the necessary steps which should be taken while working with Nodejs to avoid such attacks.

###Most Common Attacks:

### 1. DOS Attacks
DOS attack mainly crush/ shut down the hosting server, or a network that makes it unreachable for the intended user. No one will be able to use the hosted application. In this type of attacks, attackers use script to continuously sending the request, creating huge traffic on server simultaneously. There are two general methods of DoS attacks: flooding services or crashing services.Flood attacks occur when the system receives too much traffic for the server to buffer, causing them to slow down and eventually stop, And crashing service  cause the target system or service to crash.

###Prevent a NodeJS API from DOS Attacks
To avoid this attacks limit should be set for the input reqeust and If you are using express framework then its very easy for developer to handle these because express framework itself have builtin capabilities to handle this. For DOS attacks express has a built-in body-parse which can be used, We can use body-parser to limit the size of input body.


```
const express = require('express');
const app = express();
app.use(express.json({ limit: '20kb' })); // Here input body limit is 20 kb
```

Another npm package which can be used to prevent DOS attack is express-rate-limit, which mainly set the limit of requests coming from a specific user/machine. If user touches the limit provided in specific time then, NodeJS will lock him to make further requests and show him an error message.

```
const limit = rateLimit({
  max: 100,// max requests
  windowMs: 30 * 60 * 1000, // 1 Hour
  message: 'You have touched the maximum limit of request' // error message
});
 
app.use('/route', limit); // Setting limit on specific route
```

###2. SQL/NoSQL Injection
It is a type of injection where attackers can insert malicious code/command/query which can break the authentication. In this attack, the Attacker mainly inserts the SQL/NoSQL query to a specific input field in the application which further gets used in the database query. This attack mainly bypass authentication, authorization, retrieves the content of the complete SQL/NoSQL database, and perform task like creating, modifying, deleting data in the database.

###Preventing SQL/NoSQL Injection Attacks
For a developer, It should be a very common practice to sanitize the input data which can be easly managed by the available NPM packages.For SQL database node-mysql package can be used for data sanitization. And if MongoDB is used then NPM package express-mongo-sanitize can be used for the required task.


###3. Cross-site scripting(XSS)
This is type of attacks in which Attacker inserts the unwanted script in the form of client(Browser) side script, Mainly over input forms which are encoded or validated.

###Prevent a NodeJS API from XSS Attacks
1. For this attack, we can use the xss-clean NPM package. This dependency mainly prevent users from inserting Scripts/HTML on input.

2. Helmet NPM package helps you secure your Express apps by setting various/special HTTP headers.

```
// Data Sanitization against XSS
app.use(xss());
// For various HTTP headers
app.use(helmet());
```

###4. Brute Force Attacks

In this attack, Attackers used to obtain sensitive data such as user passwords or personal PIN/identification number. In such attacks, attackers most likely uses automated software to generate huge guesses of values and tries to match if any one matches with the user information. Data saved with2 way encryption can also be cracked by the attackers, So developers try to use one-way encryption methods.

###Preventing Brute Force Attacks

1. If you using express, then express-rate-limit NPM package can itself many things for you. This NPM package helps to prevent from DOS & Brute Force Attacks both.

2. One of the most effective approaches is to limit the request where authentication process(like login, OTP check) is done. So that any automated software can't attempt for breaking the authentication by macking the request so many times.

3. Always save the data like password, OTP in encrypted format with format which can't be decrypt easily. There are so many packages available which does this task. I prefer to use the method which provides one way encryption and add a salt after the encryption.

4. One of most popular approach which is being followed by the bigger organisation in two-step authentication process which works best of these attacks.

###Conclusion
These are very common attacks for any web application, But if you are using NodeJS with Express framework then it's very easy to handle these attacks. And as a developer, we should always use these practices while developing any level of application.

[Click here](https://jsonworld.com/nodejs) to read more articles on NodeJS related topics.