1.0.0 โข Published 5 months ago
express-route-enforcer v1.0.0
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
Allow
headers - ๐ 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-enforcer
Peer Dependencies:
npm install express helmet cors http-errors path-to-regexp
Quick 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 likeautocannon
for 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! ๐
1.0.0
5 months ago