npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

express-route-enforcer

v1.0.0

Published

Enhanced Express routing with strict HTTP compliance, security best practices, and parameterized route support

Readme

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 📊

| 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 🤝

  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! 🚀