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';
await build();
// Enable CORS for all routes
use(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 origin
use(cors({
origin: 'https://example.com'
}));
// Multiple origins
use(cors({
origin: ['https://example.com', 'https://app.example.com']
}));
// RegExp pattern
use(cors({
origin: /\.example\.com$/
}));
// Dynamic validation
use(cors({
origin: (requestOrigin) => {
return requestOrigin.endsWith('.trusted-domain.com');
}
}));use(cors({
// Origin validation
origin: 'https://example.com',
// Allow credentials (cookies, authorization headers)
credentials: true,
// Allowed HTTP methods
methods: ['GET', 'POST', 'PUT', 'DELETE'],
// Allowed request headers
allowedHeaders: ['Content-Type', 'Authorization'],
// Headers exposed to the client
exposedHeaders: ['X-Total-Count', 'X-RateLimit-Remaining'],
// Preflight cache duration (seconds)
maxAge: 86400,
// Pass preflight to next handler
preflightContinue: false,
// Preflight response status code
optionsSuccessStatus: 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 logic
const allowedDomains = ['example.com', 'trusted.com'];
return allowedDomains.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';
await build();
// CORS with credentials for authentication
use(cors({
origin: 'https://app.example.com',
credentials: true,
allowedHeaders: ['Content-Type', 'Authorization']
}));
get('/api/user', (req, res) => {
// Cookies and auth headers allowed
res.json({ user: 'authenticated' });
});
listen(3000);import { cors, corsDevMode, corsStrict } from '@trivajs/cors';
const isDev = 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 all
get('/api/public/data', use(corsDevMode()), (req, res) => {
res.json({ public: true });
});
// Private API - strict CORS
get('/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 database
use(corsDynamic(async (origin) => {
const allowedOrigins = await db.getAllowedOrigins();
return allowedOrigins.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