express-router-bds
v1.1.1
Published
High-performance routing system for Express based on the proven insitu-js architecture
Maintainers
Readme
Express-Router
Express-Router is a high-performance routing system for Express.js based on the proven architecture of insitu-js. It provides an optimized routing solution with support for parametrized routes, JSON route files loading, directory-based route loading, and an extensible hooks system.
Key Features
- High-Performance Routing: Uses indexes and regex caching for optimized route matching
- Parametrized Routes: Full support for dynamic routes like
/users/:id - JSON Route Loading: Define routes in JSON configuration files
- Directory-Based Loading: Load multiple route files from a directory
- Hook System: Extensible via the express-hooked hook system
- Express Middleware: Fully compatible with Express.js architecture
- Duplicate Route Detection: Alerts when duplicate routes are defined
- Static Route Support: Serve static files from directories
Important Notes on Hook Usage
When using the hook system, be careful with the next parameter in middleware functions:
- Hooks that receive the
nextparameter should not callnext()unless specifically intended to control flow - Calling
next()from within a hook can interfere with the normal Express flow and cause issues like "headers already sent" errors - For logging or pre-processing purposes, use hooks without calling
next()
Example of safe hook usage:
// Safe - only for logging
routerIntegration.addHook('before_route_processing', (req, res) => {
console.log(`Processing route: ${req.method} ${req.url}`);
});
// Potentially problematic - avoid calling next() unless necessary
routerIntegration.addHook('before_route_processing', (req, res, next) => {
console.log(`Processing route: ${req.method} ${req.url}`);
// next(); // Only call if you specifically need to control the flow
});Installation
npm install express-router-bds express-hookedQuick Start
1. Basic Setup
const express = require('express');
const ExpressRouterIntegration = require('express-router');
const app = express();
const routerIntegration = new ExpressRouterIntegration();
// Add routes directly
routerIntegration
.get('/api/hello', (req, res) => {
res.json({ message: 'Hello from Express-Router!' });
})
.get('/api/users/:id', (req, res) => {
const userId = req.params.id;
res.json({ message: `User ID: ${userId}` });
});
// Apply router to Express app
routerIntegration.applyToApp(app);
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});2. JSON Route Files
Define routes in JSON files:
[
{
"method": "GET",
"path": "/api/users",
"controller": "./controllers/usersController",
"handler": "listUsers",
"contentType": "application/json"
},
{
"method": "GET",
"path": "/api/users/:id",
"controller": "./controllers/usersController",
"handler": "getUser",
"contentType": "application/json"
}
]3. Directory-Based Loading
Load routes from multiple JSON files in a directory:
const RouteDirectoryLoader = require('express-router/RouteDirectoryLoader');
const routeDirectoryLoader = new RouteDirectoryLoader();
// Load routes from directory containing multiple JSON files
routeDirectoryLoader.loadRoutesFromDirectory(routerIntegration, './routes')
.then(routes => {
console.log(`${routes.length} routes loaded from directory`);
});Advanced Features
Hook System
The routing system integrates with the express-hooked hook system, allowing customization through extension points.
Available Hooks
pre_route_load: Executed before loading routes from a filepost_route_load: Executed after loading routes from a fileroute_added: Executed after a route is addedbefore_route_processing: Executed before processing any routeroute_matched: Executed when a matching route is foundbefore_route_handler: Executed before executing a route handlerafter_route_handler: Executed after executing a route handlerroute_handler_error: Executed when a route handler error occurs
Custom Hook Example
// Register a hook to execute logic before processing any route
routerIntegration.addHook('before_route_processing', (req, res) => {
console.log(`Processing route: ${req.method} ${req.url}`);
});
// Register a hook when a matching route is found
routerIntegration.addHook('route_matched', (matchedRoute, req, res) => {
console.log(`Route found: ${matchedRoute.route.path}`);
console.log(`Parameters:`, matchedRoute.params);
});Performance Benefits
Express-Router implements several optimizations that make it faster than traditional Express routing:
- Regex Caching: Regular expressions for parametrized routes are cached to avoid recompilation
- Route Indexing: Routes are indexed by method and path segments for faster lookup
- Pre-filtering: Candidate routes are pre-filtered using indexes before detailed matching
- Hierarchical Search: Multiple search strategies (exact, parametrized, prefix) with optimal ordering
Why Choose Express-Router?
- Battle-tested Architecture: Based on the proven insitu-js routing system used in production
- High Performance: Optimized algorithms for route matching
- Flexible Loading: Support for both file-based and directory-based route definitions
- Extensible: Rich hook system for customization
- Developer Friendly: Clean API and comprehensive documentation
- Production Ready: Built with reliability and scalability in mind
License
Apache 2.0
