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

node-smart-cors

v1.0.0

Published

Intelligent, self-debugging, zero-config CORS middleware for Node.js with automated wildcard subdomains, error recovery, configuration validator, and interactive live CLI monitor.

Readme

node-smart-cors ⚡

CORS that explains itself.

node-smart-cors is an intelligent, self-debugging CORS middleware for Node.js. It goes beyond simple rule enforcement by validating your configurations on server startup, supporting wildcard subdomain matching, ensuring headers remain attached to error responses, and diagnosing blocked requests with copy-pasteable terminal solutions. It also features a real-time terminal monitor dashboard.


✨ Features

  • 💡 Startup Config Validator: Catches incompatible options (like combining credentials: true with origins: '*') and throws high-context errors before your server starts listening.
  • 🛡️ Deep Security Auditor: Scans and warns against dangerous configurations (like using broad wildcard roots, direct IP listings, or unencrypted HTTP links in production).
  • 🌐 Dynamic Subdomain Wildcards: Supports wildcard patterns (e.g. *.yourdomain.com) natively. It converts patterns into strict regular expressions ([a-zA-Z0-9-]+), ensuring phishing domains (like evil.yourdomain.com.attacker.com) are blocked.
  • ⚡ Auto-Localhost in Development: Automatically detects NODE_ENV and allows any local port (e.g., :3000, :5173, :8080) for localhost, 127.0.0.1, and [::1]. No more manual listings for frontend ports.
  • ❌ Error-Response Resilience: Inject CORS headers immediately on entry. This prevents browsers from turning a standard 401 Unauthorized or 500 Server Error response into a confusing "CORS blocked" error.
  • 🎯 Intelligent Suggestion Engine: Prints clear, beautiful terminal boxes explaining why a request was blocked (e.g., Vercel previews, Netlify previews, localhost port mismatches) alongside the exact config patch to fix it.
  • 📊 Live CLI Dashboard Monitor: Run npx node-smart-cors monitor to view an active, auto-refreshing dashboard showing total counts, allowance rates, top client origins, and real-time request logs.

🚀 Quick Start

Installation

npm install node-smart-cors

Usage with Express

const express = require('express');
const smartCors = require('node-smart-cors');

const app = express();

// Zero-Config Setup
// - Auto-detects NODE_ENV (development / production)
// - Bypasses all localhost ports in development
// - Hardens to strict matching in production
app.use(smartCors({
  analytics: true // Enables the Live CLI Monitor dashboard!
}));

app.get('/api/data', (req, res) => {
  res.json({ message: "CORS successfully negotiated!" });
});

app.listen(3000, () => {
  console.log("Server listening on port 3000");
});

⚙️ Configuration Schema

Below is the complete set of configuration parameters supported by node-smart-cors:

| Parameter | Type | Default | Description | | :--- | :--- | :--- | :--- | | environment | string | 'auto' | 'auto' (checks NODE_ENV), 'development', or 'production'. | | origins | string[] | [] | Allowed origins. Supports subdomain wildcards (e.g. *.example.com). | | devOrigins | string[] | [] | Origins allowed exclusively in the development environment. | | productionOrigins | string[] | [] | Origins allowed exclusively in the production environment. | | credentials | boolean | false | Set to true to allow cookies and auth headers. | | methods | string[] | ['GET', ...] | Array of allowed HTTP request methods. | | headers | string[] | [] | Allowed headers. Empty array reflections request headers. | | exposedHeaders | string[] | [] | Headers exposed to client browsers. | | maxAge | number | 86400 | Preflight OPTIONS cache duration in seconds. | | autoPreflight | boolean | true | Intercept and handle preflight OPTIONS requests automatically. | | allowAllInDev | boolean | true | Bypass all localhost and local IP ports in development. | | debug | boolean | false | Set to true to print pretty diagnostic boxes for every request in server logs. | | suggestFixes | boolean | true | Offer suggestion codes for blocked requests. | | securityChecks | boolean | true | Conduct static audits at startup to flag configuration risks. | | analytics | boolean | false | Enable live metric collection. | | analyticsFile | string | null | Custom path to write the telemetry IPC file (defaults to .node-smart-cors-analytics.json). |


📊 Live CLI Monitor

To view live request analytics, start your server with analytics: true and run the monitor in your terminal:

npx node-smart-cors monitor

What it displays:

  • Environment Status Indicator: Clear tag indicating if your middleware is evaluating rules under development or strict production limits.
  • Request Counters: Live tally of total, allowed, and blocked requests alongside your active Allow Rate (%).
  • Top Origin Hits: Visual horizontal ASCII bar chart displaying the frequency of inbound client origins.
  • Live Logs: Rolling feed of the last 6 request events displaying timestamp, method, allowance status, and client URL path.
  • Contextual Suggester: Automatically pops up the exact block explanation and copy-pasteable configuration fix code based on the most recent blocked origin.

🔍 How node-smart-cors Solves Common Pain Points

1. The Preflight (OPTIONS) Intercept

Simple requests (GET/POST with form encoding) do not require preflights. However, standard AJAX requests (POST with application/json or custom headers) trigger a preflight OPTIONS call before sending actual data. node-smart-cors intercepts OPTIONS requests and immediately responds with a 204 No Content along with correct authorization, bypassing downstream middlewares and routers completely.

2. Standardizing Error Responses

Standard CORS libraries only apply headers on successful route responses. If downstream middlewares (like an JWT authorizer or database driver) throw a 401 Unauthorized or 500 Server Error, the CORS headers are stripped, triggering a browser CORS block error instead. node-smart-cors mounts headers on Express's response object immediately on entry, guaranteeing headers are returned regardless of the final status code.

3. Dynamic Credentials with Wildcard Subdomains

Browsers forbid reflecting a global wildcard (*) when credentials: true is set. If you require credentials and wildcard subdomains (e.g. *.client.com), node-smart-cors dynamically computes matching checks and mirrors only the matched origin inside the Access-Control-Allow-Origin header, conforming to secure browser policies.


📦 Repository

🔗 https://github.com/Coderkube-App/node-smart-cors.git


📄 License

This project is licensed under the MIT License. See LICENSE for details.