CORS middleware for Triva framework. Handles Cross-Origin Resource Sharing with full configuration support.
npm install @trivajs/cors trivaimport{build,get,use,listen}from'triva';import{cors}from'@trivajs/cors';awaitbuild();// Enable CORS for all routesuse(cors());get('/api/data',(req,res)=>{res.json({message: 'CORS enabled!'});});listen(3000);✅ Simple & Flexible - Works seamlessly with Triva middleware system
✅ Zero Dependencies - Lightweight, no external dependencies
✅ Full Configuration - Complete control over CORS headers
✅ Pre-configured Modes - Development, strict, multi-origin, dynamic
✅ Preflight Handling - Automatic OPTIONS request handling
✅ Origin Validation - String, Array, RegExp, or Function validation
import{cors}from'@trivajs/cors';// Allow all origins (default)use(cors());// Specific originuse(cors({origin: 'https://example.com'}));// Multiple originsuse(cors({origin: ['https://example.com','https://app.example.com']}));// RegExp patternuse(cors({origin: /\.example\.com$/}));// Dynamic validationuse(cors({origin: (requestOrigin)=>{returnrequestOrigin.endsWith('.trusted-domain.com');}}));use(cors({// Origin validationorigin: 'https://example.com',// Allow credentials (cookies, authorization headers)credentials: true,// Allowed HTTP methodsmethods: ['GET','POST','PUT','DELETE'],// Allowed request headersallowedHeaders: ['Content-Type','Authorization'],// Headers exposed to the clientexposedHeaders: ['X-Total-Count','X-RateLimit-Remaining'],// Preflight cache duration (seconds)maxAge: 86400,// Pass preflight to next handlerpreflightContinue: false,// Preflight response status codeoptionsSuccessStatus: 204}));import{corsDevMode}from'@trivajs/cors';use(corsDevMode());// Allows all origins, methods, headersimport{corsStrict}from'@trivajs/cors';use(corsStrict('https://app.example.com'));// Credentials enabled, limited methodsimport{corsMultiOrigin}from'@trivajs/cors';use(corsMultiOrigin(['https://app.example.com','https://admin.example.com']));import{corsDynamic}from'@trivajs/cors';use(corsDynamic((origin)=>{// Custom validation logicconstallowedDomains=['example.com','trusted.com'];returnallowedDomains.some(domain=>origin.endsWith(domain));}));| Option | Type | Default | Description |
|---|---|---|---|
origin | string | array | RegExp | Function | '*' | Allowed origin(s) |
methods | string[] | ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE'] | Allowed methods |
allowedHeaders | string[] | [] | Allowed request headers (empty = reflect request) |
exposedHeaders | string[] | [] | Headers exposed to client |
credentials | boolean | false | Allow credentials |
maxAge | number | null | null | Preflight cache duration (seconds) |
preflightContinue | boolean | false | Pass preflight to next handler |
optionsSuccessStatus | number | 204 | Preflight response status |
import{build,get,post,use,listen}from'triva';import{cors}from'@trivajs/cors';awaitbuild();// CORS with credentials for authenticationuse(cors({origin: 'https://app.example.com',credentials: true,allowedHeaders: ['Content-Type','Authorization']}));get('/api/user',(req,res)=>{// Cookies and auth headers allowedres.json({user: 'authenticated'});});listen(3000);import{cors,corsDevMode,corsStrict}from'@trivajs/cors';constisDev=process.env.NODE_ENV==='development';if(isDev){use(corsDevMode());// Allow all in development}else{use(corsStrict('https://production.example.com'));// Strict in production}import{get,use}from'triva';import{cors,corsDevMode}from'@trivajs/cors';// Public API - allow allget('/api/public/data',use(corsDevMode()),(req,res)=>{res.json({public: true});});// Private API - strict CORSget('/api/private/data',use(cors({origin: 'https://app.example.com',credentials: true})),(req,res)=>{res.json({private: true});});import{corsDynamic}from'@trivajs/cors';// Check origin against databaseuse(corsDynamic(async(origin)=>{constallowedOrigins=awaitdb.getAllowedOrigins();returnallowedOrigins.includes(origin);}));use(cors({origin: /^https:\/\/.*\.example\.com$/}));// Allows: https://app.example.com, https://admin.example.com// Blocks: https://malicious.com- Origin Check - Validates request origin against configuration
- Set Headers - Adds appropriate CORS headers to response
- Preflight - Handles OPTIONS requests for preflight
- Next - Calls next middleware or route handler
❌ Don't use origin: '*' with credentials: true
✅ Do specify exact origins in production
❌ Don't expose sensitive headers unnecessarily
✅ Do limit exposedHeaders to what's needed
❌ Don't allow all methods by default
✅ Do specify only required methods
Check that your origin is exactly configured:
// Wrong (missing protocol)
origin: 'example.com'// Correct
origin: 'https://example.com'Ensure both are set:
use(cors({origin: 'https://example.com',// NOT '*'credentials: true}));And in client:
fetch('https://api.example.com',{credentials: 'include'});Add your headers to allowedHeaders:
use(cors({allowedHeaders: ['Content-Type','X-Custom-Header']}));# Run tests
npm test# Run example
npm run exampleMIT License - see LICENSE file
Issues and PRs welcome! See main Triva repository for contribution guidelines.
- Triva Framework - Main framework
- CORS Specification