If you have built a API with Node.com, there are chances that you have thought of security – at least a little bit.
You may have heard about SQL injections, brot force attacks, or data leaks.
But the point here is: It’s not just about big hexes. Even the smallest differences in your API can cause major problems. And no one wants to get it “Your data has been exposed”.
In this article, I give you my node. JS will pass in seven ways to tighten the API.
These are the practical points you can apply right now. I will keep the code examples easy and the language easy. Let’s enter it.
1. Use environmental variables
It is dangerous to store sensitive data such as direct database credentials, API keys, or JWT secrets in your code. If your code ends in the wrong hands, everything else does.
Instead, store this data in A .env
File and use dotenv
Package to access this:
require('dotenv').config();
const dbPassword = process.env.DB_PASSWORD;
Make sure you Never Make your commitment .env
File add it to your own .gitignore
File to keep it private.
2. Confirm all input
The attackers like the user’s input.
If you do not check what comes to your API, they will crash commands, injection code, or your app.
The best way to stop them is to verify each piece of input. Use a package like Joi
Or zod
To describe your API expectation:
const Joi = require('joi');
const schema = Joi.object({
username: Joi.string().alphanum().min(3).max(30).required(),
password: Joi.string().pattern(new RegExp('^(a-zA-Z0-9){6,30}$')).required()
});
const { error } = schema.validate(req.body);
if (error) {
return res.status(400).send(error.details(0).message);
}
In the aforementioned code, we have explained the correct type of data as expected of the scheme. In this way, the wrong data is blocked before you reach your logic or database.
3. Rate limit your closing points
Boots and Brutal Force attacks work your server flooding with requests. Once your server reaches the limit, your API will crash.
How often the user can hit your API by using the middleware like express-rate-limit
Here is an example.
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
});
app.use('/api/', limiter);
The aforementioned code limits the API requests coming from the IP address to 100 per 15 minutes. This is like a rapid collision in front of a running car.
4. Always use HTTPS
HTTP sends data to simple text. This means that anyone can read it between your server and the user. HTTPS encrypts everything. This is no longer optional.
If you are using a platform like heroic or versal, https is automatic. If you are hosting yourself, you can arrange it with services like Latez encryption.
Also, force HTTPS on all incoming traffic. You can use the middleware like this:
app.use((req, res, next) => {
if (req.headers('x-forwarded-proto') !== 'https') {
return res.redirect(' + req.headers.host + req.url);
}
next();
});
Encrypt the ride. Always
HTTP headers are key value -value couples that have been sent in requests and reactions to the web. They give extra information about what they are being sent – as it is sending it, what kind of it is, how it should be handled, and much more.
HTTP headers are small, but they can be powerful tools to protect your app. Helmet
A node is a JS Middleware that sets a safe header for you.
const helmet = require('helmet');
app.use(helmet());
The helmet cross site helps to prevent attacks (XSS), click jacking, and other such attacks that just set the right header.
A line of code, a big step in security.
6. Clean the data to prevent injection attacks
Injection attacks occur when you close your eyes and rely on the input and plug it into command or inquiry.
For example, the attacker can offer a piece of text that turns into your database into a command.
You should clear the data before coming to any sensitive function. Like the libraries express-mongo-sanitize
Or xss-clean
Help clean the malicious input.
const mongoSanitize = require('express-mongo-sanitize');
const xss = require('xss-clean');
app.use(mongoSanitize());
app.use(xss());
It takes away dangerous characters and scripts that can cause real harm.
7. Use strong verification and permission
Verification is about to know who the user is, and the permission is about what they can do. You need both, and you need to be strong.
Use JWT (JSON Web Token) or session to handle login users. Here is a quick JWT example:
const jwt = require('jsonwebtoken');
const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET, {
expiresIn: '1h'
});
Always verify the token before giving the user access to safe routes:
const decoded = jwt.verify(token, process.env.JWT_SECRET);
And don’t forget the role. A user who can see the data should not be deleted unless they do it.
The final views
Security is not just a feature – this is a habit. You can’t do everything together, but you can start with some important changes.
Use environmental variables. Confirm your inputs. Add limiting rate. Move to https. Install the helmet. Clean everything. Lock your endorsement.
Each of these steps is a small lock on a large door. The more you add, the harder it is to break. So take some time now. Your future and your user will thank you.
For more lessons of cybersecurity, Join our newsletter. Learning the basics of aggressive cybersecurity, let us check our Security Starter course.