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.
Maintainers
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: truewithorigins: '*') 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 (likeevil.yourdomain.com.attacker.com) are blocked. - ⚡ Auto-Localhost in Development: Automatically detects
NODE_ENVand allows any local port (e.g.,:3000,:5173,:8080) forlocalhost,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 Unauthorizedor500 Server Errorresponse 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 monitorto 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-corsUsage 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 monitorWhat 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.
