DEV Community

Vaibhav Singh
Vaibhav Singh

Posted on

Introducing Route Guard: A Flexible API Validation Module for Node.js πŸš€

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

  1. 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
},
},
};

  1. 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)