1.0.0 โ€ข Published 5 months ago

express-route-enforcer v1.0.0

Weekly downloads
-
License
MIT
Repository
-
Last release
5 months ago

express-route-enforcer ๐Ÿ”’

npm version License: MIT Bundle Size

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 โšก

  1. Precompiled Routes:
    Routes are compiled to regex during initialization for faster matching.

  2. Method Caching:
    Allowed methods are cached using Set operations for O(1) lookups.

  3. Benchmarking:
    Use tools like autocannon for load testing:

    npx autocannon -c 100 -d 20 http://localhost:3000/api

API Reference ๐Ÿ“š

createRouteEnforcer(app, routeConfig, options)

  • app: Express application instance
  • routeConfig: Array of route configurations
  • options:
    • helmetOptions: Custom helmet configuration
    • corsOptions: Custom CORS configuration

createErrorHandler(options)

  • options:
    • includeStack: Include error stack traces (default: false)

Comparison vs Express Native ๐Ÿ“Š

FeatureExpress Nativeexpress-route-enforcer
405 Method HandlingโŒโœ…
Security HeadersManualโœ… Auto
Route ValidationโŒโœ… Pre-startup
Parametrized Routesโœ…โœ… Enhanced
Error FormattingManualโœ… Standardized
CORS SupportManualโœ… 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 ๐Ÿค

  1. Fork the repository
  2. Create feature branch (git checkout -b feature/improvement)
  3. Commit changes (git commit -am 'Add amazing feature')
  4. Push to branch (git push origin feature/improvement)
  5. Open Pull Request

License ๐Ÿ“„

MIT ยฉ Dannys-notepad


Upgrade Your Express Apps - Add production-ready routing with security and compliance in minutes! ๐Ÿš€