express-route-enforcer
v1.0.0
Published
Enhanced Express routing with strict HTTP compliance, security best practices, and parameterized route support
Maintainers
Readme
express-route-enforcer 🔒
Enhanced Express routing with strict HTTP compliance, security best practices, and parameterized route support.
Features ✨
- 🚦 Proper HTTP Compliance: 404/405 responses with
Allowheaders - 🔐 Security First: Auto-configured helmet & CORS
- 🎯 Parametrized Routes: Full Express-style path parameter support
- 📝 Structured Config: Centralized route declaration
- 🚨 Standardized Errors: Consistent JSON error format
- ⚡ Performance Optimized: Precompiled route matching
- 🧪 Validation: Runtime config checks during startup
Installation 📦
npm install express-route-enforcerPeer Dependencies:
npm install express helmet cors http-errors path-to-regexpQuick Start 🚀
const express = require('express');
const { createRouteEnforcer, createErrorHandler } = require('express-route-enforcer');
const app = express();
app.use(express.json());
// Route Configuration
const routeConfig = [
{
path: '/api/users/:id',
methods: ['GET', 'PUT'],
middlewares: [
(req, res, next) => {
console.log('Accessing user:', req.params.id);
next();
},
(req, res) => res.json({ user: { id: req.params.id } })
]
}
];
// Initialize Enforcer
const enforcer = createRouteEnforcer(app, routeConfig, {
helmetOptions: { contentSecurityPolicy: false },
corsOptions: { origin: 'https://trusted-domain.com' }
});
app.use(enforcer);
app.use(createErrorHandler({ includeStack: true }));
app.listen(3000, () => {
console.log('Server running on port 3000');
});Configuration ⚙️
Route Configuration Schema
interface RouteConfig {
path: string; // Express-style path
methods: string[]; // HTTP methods (case-insensitive)
middlewares: Function[];// Array of Express middleware functions
}Security Options
createRouteEnforcer(app, routeConfig, {
helmetOptions: { ... }, // Custom helmet configuration
corsOptions: { ... } // Custom CORS configuration
});Error Handling 🚨
Standard Error Format:
{
"error": {
"message": "Method PATCH not allowed",
"status": 405,
"timestamp": "2024-02-20T14:30:00.000Z",
"stack": "..." // Optional in development
}
}Customization:
app.use(createErrorHandler({
includeStack: process.env.NODE_ENV === 'development'
}));Advanced Usage 🧠
Parameterized Routes
{
path: '/books/:genre/:author?',
methods: ['GET'],
middlewares: [(req, res) => {
res.json({
genre: req.params.genre,
author: req.params.author || 'unknown'
});
}]
}Wildcard Methods
{
path: '/health',
methods: ['ALL'], // Handles any HTTP method
middlewares: [healthCheckHandler]
}Custom Security Policies
createRouteEnforcer(app, routes, {
helmetOptions: {
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "trusted-cdn.com"]
}
}
},
corsOptions: {
origin: [/\.example.com$/, 'https://partner.site'],
methods: ['GET', 'POST']
}
});Performance Considerations ⚡
Precompiled Routes:
Routes are compiled to regex during initialization for faster matching.Method Caching:
Allowed methods are cached using Set operations for O(1) lookups.Benchmarking:
Use tools likeautocannonfor load testing:npx autocannon -c 100 -d 20 http://localhost:3000/api
API Reference 📚
createRouteEnforcer(app, routeConfig, options)
app: Express application instancerouteConfig: Array of route configurationsoptions:helmetOptions: Custom helmet configurationcorsOptions: Custom CORS configuration
createErrorHandler(options)
options:includeStack: Include error stack traces (default: false)
Comparison vs Express Native 📊
| Feature | Express Native | express-route-enforcer | |------------------------|----------------|------------------------| | 405 Method Handling | ❌ | ✅ | | Security Headers | Manual | ✅ Auto | | Route Validation | ❌ | ✅ Pre-startup | | Parametrized Routes | ✅ | ✅ Enhanced | | Error Formatting | Manual | ✅ Standardized | | CORS Support | Manual | ✅ Integrated |
Testing 🧪
const request = require('supertest');
describe('User API', () => {
it('GET /api/users/123 returns 200', async () => {
await request(app)
.get('/api/users/123')
.expect(200)
.expect(res => {
assert(res.body.user.id === '123');
});
});
it('DELETE /api/users/123 returns 405', async () => {
const res = await request(app)
.delete('/api/users/123')
.expect(405);
assert(res.headers.allow.includes('GET, PUT'));
});
});Contributing 🤝
- Fork the repository
- Create feature branch (
git checkout -b feature/improvement) - Commit changes (
git commit -am 'Add amazing feature') - Push to branch (
git push origin feature/improvement) - Open Pull Request
License 📄
MIT © [Dannys-notepad]
Upgrade Your Express Apps - Add production-ready routing with security and compliance in minutes! 🚀
