route-scoped-cors
v0.1.2
Published
Per-route CORS method scoping middleware for Express and NestJS — prevents HTTP verb tampering by advertising only the methods each route actually handles.
Downloads
499
Maintainers
Readme
route-scoped-cors
Per-route CORS method scoping middleware for Express and NestJS.
Instead of advertising every HTTP method on every route, this middleware inspects the Express router at runtime and sets Access-Control-Allow-Methods to only the methods actually registered for the matched path. This prevents HTTP verb tampering and gives browsers accurate preflight information.
How it works
- OPTIONS preflight — responds
204with the exact methods for that route. - Disallowed method — responds
405 Method Not Allowedwith anAllowheader. - Allowed method — passes through unchanged.
- The route map is built lazily on the first request, so all routes are guaranteed to be registered before inspection.
Installation
npm install route-scoped-corsUsage
Express
import express from 'express';
import { routeScopedCors } from 'route-scoped-cors';
const app = express();
// Must be added after routes are defined, or use install() which is lazy-safe
app.use(routeScopedCors());
app.get('/users', handler);
app.post('/users', handler);Or use the install helper:
import { install } from 'route-scoped-cors';
const app = express();
install(app); // equivalent to app.use(routeScopedCors())NestJS
Import RouteScopedCorsModule into your root module. It automatically applies the middleware to all routes via NestJS's configure() lifecycle hook — no extra wiring needed.
// app.module.ts
import { Module } from '@nestjs/common';
import { RouteScopedCorsModule } from 'route-scoped-cors/nestjs';
@Module({
imports: [RouteScopedCorsModule.forRoot()],
})
export class AppModule {}With options:
RouteScopedCorsModule.forRoot({
fallbackMethods: ['GET', 'POST', 'OPTIONS'],
})Options
| Option | Type | Default | Description |
|---|---|---|---|
| fallbackMethods | string[] | ['GET','POST','PUT','PATCH','DELETE','OPTIONS'] | Methods returned for unmatched or unknown paths |
Response behaviour
Preflight (OPTIONS)
HTTP/1.1 204 No Content
Access-Control-Allow-Methods: GET, POST, OPTIONSMethod not allowed
HTTP/1.1 405 Method Not Allowed
Allow: GET, POST
{
"statusCode": 405,
"message": "Method Not Allowed",
"error": "DELETE is not supported on this resource. Allowed: GET, POST"
}Notes
- This middleware complements (not replaces) a CORS origin/headers package like
cors. SetpreflightContinue: trueon your cors config so preflight requests reach this middleware. - The route map is cached after the first request. It does not update if routes are added dynamically at runtime.
License
MIT
