In today's world of web development, APIs are the backbone of communication between services. Ensuring the validity and security of incoming requests is crucial to maintain robust and secure applications. Thatβs where Route Guard, a lightweight and powerful Node.js module, steps in to simplify API validation.
π What is Route Guard?
Route Guard is a Node.js library designed to validate API requests effortlessly. It helps developers enforce strict validation rules for headers, body fields, data types, and required parameters. Whether you're working on a small project or scaling up, Route Guard ensures your APIs are secure and well-structured.
π Key Features
Flexible Validation Rules: Easily define validation rules for headers and body fields.
Required Fields & Type Checking: Enforce the presence of required fields and validate data types.
Enumerated Values: Limit values to predefined options (e.g., roles like 'admin', 'user').
Detailed Error Reporting: Get precise error messages when validation fails, helping with debugging and user feedback.
π Installation
Getting started with Route Guard is simple:
npm install routeguard
π How to Use Route Guard
- Define Your Validation Rules Create a validationRules.js file and specify the rules for each API route:
module.exports = {
'/api/users': {
headers: {
'api-key': { required: true, type: 'string' }, // API key validation
},
body: {
username: { required: true, type: 'string' }, // Ensure username is a string
email: { required: true, type: 'string' }, // Email validation
role: { required: true, type: 'string', enum: ['user', 'admin'] }, // Role validation
},
},
};
- Integrate Route Guard in Your Application Use the RouteValidator class to validate incoming requests:
`const RouteValidator = require('routeguard');
const rules = require('./validationRules');
const validator = new RouteValidator(rules);
// Sample Express route
app.post('/api/users', (req, res) => {
const result = validator.validate('/api/users', req);
if (result.isValid) {
res.status(200).send({ message: 'User created successfully!' });
} else {
res.status(400).send({ errors: result.errors });
}
});`
π Example API Requests
β
Valid Request:
curl -X POST http://localhost:3000/api/users \
-H "Content-Type: application/json" \
-H "api-key: valid-api-key" \
-d '{"username": "john_doe", "email": "john@example.com", "role": "admin"}'
β Invalid Request (Missing API Key):
curl -X POST http://localhost:3000/api/users \
-H "Content-Type: application/json" \
-d '{"username": "john_doe", "email": "john@example.com", "role": "admin"}'
π Error Response:
{
"errors": [
{
"field": "headers.api-key",
"message": "api-key is required in headers."
}
]
}
π¬ Testing with Jest
Route Guard supports easy testing using Jest. Run the test suite with:
npm test
Sample Output:
PASS tests/routeguard.test.js
β should reject missing required header (20 ms)
β should reject invalid role values (15 ms)
β should accept valid request (10 ms)
π€ Contribute to Open Source
We welcome contributions! If youβd like to improve Route Guard or suggest new features, feel free to:
Star the repo:
GitHub: https://github.com/v0nser/routeguard
Submit an issue or pull request: Contributions are welcome!
π Conclusion
Route Guard is a simple yet powerful tool that adds an extra layer of security to your APIs. By validating headers and body fields with customizable rules, you can ensure that your API endpoints are robust, secure, and reliable.
Start building more secure APIs today with Route Guard!
Links:
NPM: https://www.npmjs.com/package/routeguard
GitHub: https://github.com/v0nser/routeguard
What are your thoughts? Let us know how Route Guard has helped you build better APIs in the comments below!
Top comments (0)