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

@trivajs/cors

v1.0.0

Published

CORS middleware for Triva framework - handles Cross-Origin Resource Sharing with full configuration

Readme

@trivajs/cors

CORS middleware for Triva framework. Handles Cross-Origin Resource Sharing with full configuration support.

Installation

npm install triva
npm install @trivajs/cors

Quick Start

import { 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);

Features

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

Usage

Basic Configuration

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');
  }
}));

Advanced Configuration

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
}));

Pre-configured Modes

Development Mode (Allow All)

import { corsDevMode } from '@trivajs/cors';

use(corsDevMode());
// Allows all origins, methods, headers

Strict Mode (Single Origin)

import { corsStrict } from '@trivajs/cors';

use(corsStrict('https://app.example.com'));
// Credentials enabled, limited methods

Multi-Origin Mode

import { corsMultiOrigin } from '@trivajs/cors';

use(corsMultiOrigin([
  'https://app.example.com',
  'https://admin.example.com'
]));

Dynamic Mode

import { corsDynamic } from '@trivajs/cors';

use(corsDynamic((origin) => {
  // Custom validation logic
  const allowedDomains = ['example.com', 'trusted.com'];
  return allowedDomains.some(domain => origin.endsWith(domain));
}));

Configuration Options

| 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 |

Examples

API with Authentication

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);

Multiple Environments

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
}

Route-Specific CORS

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 });
});

Dynamic Origin with Database

import { corsDynamic } from '@trivajs/cors';

// Check origin against database
use(corsDynamic(async (origin) => {
  const allowedOrigins = await db.getAllowedOrigins();
  return allowedOrigins.includes(origin);
}));

Subdomain Wildcard

use(cors({
  origin: /^https:\/\/.*\.example\.com$/
}));
// Allows: https://app.example.com, https://admin.example.com
// Blocks: https://malicious.com

How It Works

  1. Origin Check - Validates request origin against configuration
  2. Set Headers - Adds appropriate CORS headers to response
  3. Preflight - Handles OPTIONS requests for preflight
  4. Next - Calls next middleware or route handler

Security Best Practices

Don't use origin: '*' with credentials: trueDo 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

Troubleshooting

CORS Error: Origin Not Allowed

Check that your origin is exactly configured:

// Wrong (missing protocol)
origin: 'example.com'

// Correct
origin: 'https://example.com'

Credentials Not Working

Ensure both are set:

use(cors({
  origin: 'https://example.com', // NOT '*'
  credentials: true
}));

And in client:

fetch('https://api.example.com', {
  credentials: 'include'
});

Preflight Failing

Add your headers to allowedHeaders:

use(cors({
  allowedHeaders: ['Content-Type', 'X-Custom-Header']
}));

Testing

# Run tests
npm test

# Run example
npm run example

License

MIT License - see LICENSE file

Contributing

Issues and PRs welcome! See main Triva repository for contribution guidelines.

Triva Framework - Main framework