In modern web applications, API endpoints are the gateways of the system to the outside world. If you don't make these gateways secure enough, leaks, unauthorized access, and serious data breaches become inevitable. One of the most effective methods to ensure security in APIs is to use middleware.
In this article, starting with the question "What is Middleware?", we will explain how we can ensure API endpoint security with the help of middleware through sample codes and scenarios.
What is Middleware?
Middleware are intermediate software layers that run before an API request reaches the server or before a response is generated. Their functions can be:
-
Authenticating the incoming request
-
Checking the user's authorization
-
Data validation (input validation)
-
Request logging
-
Rate limiting
Thanks to middleware, code repetition is reduced, making the API structure more secure, readable, and easy to maintain.
What Happens If Middleware Is Not Used?
-
The risk of unauthorized access increases.
-
Authentication deficiencies occur.
-
There is a high probability of leaking too much data.
-
Without rate limiting, you become vulnerable to attacks such as DDoS.
A simple example: If you have an endpoint like /api/user/delete/:id
and you don't check the sent ID, any user can delete other users' accounts.
Basic Middleware Types That Should Be Used in API Endpoints
1. Authentication Middleware
Checks whether the user is logged in to the system.
Example (Node.js / Express.js):
function authMiddleware(req, res, next) {
const token = req.headers['authorization'];
if (!token) {
return res.status(401).json({ message: 'Token not found!' });
}
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = decoded;
next();
} catch (error) {
return res.status(403).json({ message: 'Invalid token!' });
}
}
Usage:
app.get('/api/profile', authMiddleware, (req, res) => {
res.json({ user: req.user });
});
2. Authorization Middleware
Checks whether the authenticated user is authorized to perform specific actions.
Example:
function adminMiddleware(req, res, next) {
if (req.user.role !== 'admin') {
return res.status(403).json({ message: 'Unauthorized access!' });
}
next();
}
Usage:
app.delete('/api/user/:id', authMiddleware, adminMiddleware, (req, res) => {
// user deletion operations
});
3. Input Validation Middleware
Checks the format and content of the data coming to the server. Provides protection against dangers such as SQL Injection and XSS.
Example (with Joi Library):
const Joi = require('joi');
function validateUserInput(req, res, next) {
const schema = Joi.object({
email: Joi.string().email().required(),
password: Joi.string().min(6).required()
});
const { error } = schema.validate(req.body);
if (error) {
return res.status(400).json({ message: error.details[0].message });
}
next();
}
Usage:
app.post('/api/register', validateUserInput, (req, res) => {
// registration operations
});
4. Rate Limiting Middleware
Limits the number of requests that an IP address can make in a specific time period. Prevents DDoS or brute-force attacks.
Example (with Express-rate-limit):
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 100
});
app.use(limiter);
5. CORS Middleware
Ensures that requests only come from specific domains.
Example:
const cors = require('cors');
app.use(cors({
origin: 'https://siteniz.com'
}));
Example Real-Life Scenario: Violation Without Using Middleware
On a blog site, the endpoint named /api/admin/posts/delete/:postId
was published without using middleware. An attacker user was able to delete other users' posts by using postId
's that did not belong to them.
If authMiddleware
+ adminMiddleware
were used:
-
Authentication would be performed.
-
Only users with admin privileges could perform the operation.
-
Unauthorized transaction attempts would be prevented.
Conclusion: Middleware is the First Line of Defense for Security
Always protect your API endpoints with authentication, authorization, validation, and rate limiting layers. Remember, the best defense starts with questioning the incoming request at the first point of contact.
With the examples in this article, you can easily integrate a middleware architecture into your own system and make your APIs much more robust and professional.