@gulibs/tegg-cors
v0.0.1
Published
CORS plugin for Egg.js 4.x
Maintainers
Readme
@gulibs/tegg-cors
CORS (Cross-Origin Resource Sharing) plugin for Egg.js 4.x, powered by @koa/cors.
Features
- ✅ Full CORS support with customizable options
- ✅ Integration with egg-security's safe domain check
- ✅ TypeScript support with full type definitions
- ✅ Dynamic origin validation with function support
- ✅ Preflight request handling
- ✅ Private Network Access support
Requirements
- Node.js >= 22.18.0
- Egg.js >= 4.1.0-beta.35
Install
Install Latest Version
npm i @gulibs/tegg-cors
# or
npm i @gulibs/tegg-cors@latestInstall Beta Version
To install the beta version, you must explicitly specify the @beta tag:
npm i @gulibs/tegg-cors@betaNote: Using @latest or no tag will install the latest stable version, not the beta version.
Usage
1. Enable Plugin
// config/plugin.ts
import corsPlugin from '@gulibs/tegg-cors';
export default {
...corsPlugin(),
};2. Configure CORS Options
// config/config.default.ts
export default {
teggCors: {
// Allow all origins (not recommended for production)
origin: '*',
// Or specify allowed origins
origin: 'https://example.com',
// Or use a function for dynamic origin validation
origin: async (ctx) => {
const origin = ctx.get('origin');
// Your custom validation logic
return origin;
},
// Allowed HTTP methods
allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH',
// Expose custom headers to the client
exposeHeaders: ['X-Custom-Header'],
// Allow custom headers in requests
allowHeaders: ['Content-Type', 'Authorization'],
// Preflight cache duration (in seconds)
maxAge: 600,
// Allow credentials (cookies, authorization headers)
credentials: true,
// Keep headers on error responses
keepHeadersOnError: false,
// Private Network Access
privateNetworkAccess: false,
},
};Configuration Options
Basic Options
origin
Type: string | ((ctx: Context) => string | Promise<string>)
Default: Uses egg-security's isSafeDomain check if available
Set the Access-Control-Allow-Origin header.
Examples:
// Allow all origins (not recommended for production)
origin: '*'
// Allow specific origin
origin: 'https://example.com'
// Allow multiple origins
origin: (ctx) => {
const allowedOrigins = ['https://example.com', 'https://app.example.com'];
const origin = ctx.get('origin');
return allowedOrigins.includes(origin) ? origin : '';
}
// Use egg-security integration (default behavior)
// No need to configure if egg-security is enabled
// It will automatically check against domainWhiteListallowMethods
Type: string | string[]
Default: 'GET,HEAD,PUT,POST,DELETE,PATCH'
Set the Access-Control-Allow-Methods header.
allowMethods: 'GET,POST,PUT'
// or
allowMethods: ['GET', 'POST', 'PUT']exposeHeaders
Type: string | string[]
Default: undefined
Set the Access-Control-Expose-Headers header.
exposeHeaders: ['X-Custom-Header', 'X-Request-Id']allowHeaders
Type: string | string[]
Default: undefined (reflects the request's Access-Control-Request-Headers)
Set the Access-Control-Allow-Headers header.
allowHeaders: ['Content-Type', 'Authorization', 'X-Custom-Header']maxAge
Type: string | number
Default: undefined
Set the Access-Control-Max-Age header (preflight cache duration in seconds).
maxAge: 600 // 10 minutescredentials
Type: boolean
Default: false
Set the Access-Control-Allow-Credentials header.
credentials: trueNote: When credentials: true, origin cannot be '*'. You must specify exact origins.
keepHeadersOnError
Type: boolean
Default: false
Add CORS headers to error responses.
keepHeadersOnError: trueprivateNetworkAccess
Type: boolean
Default: false
Set the Access-Control-Allow-Private-Network header for Private Network Access.
privateNetworkAccess: trueIntegration with egg-security
If you have egg-security plugin enabled and don't configure a custom origin handler, tegg-cors will automatically use the domainWhiteList from egg-security:
// config/config.default.ts
export default {
// egg-security configuration
security: {
domainWhiteList: ['https://example.com', 'https://app.example.com'],
},
// tegg-cors will automatically use domainWhiteList for origin validation
teggCors: {
credentials: true,
},
};Common Use Cases
Allow specific domains
export default {
teggCors: {
origin: (ctx) => {
const allowedOrigins = [
'https://example.com',
'https://app.example.com',
'https://admin.example.com',
];
const origin = ctx.get('origin');
return allowedOrigins.includes(origin) ? origin : '';
},
credentials: true,
},
};Allow all subdomains
export default {
teggCors: {
origin: (ctx) => {
const origin = ctx.get('origin');
if (origin && /^https:\/\/[\w-]+\.example\.com$/.test(origin)) {
return origin;
}
return '';
},
credentials: true,
},
};Development vs Production
// config/config.default.ts
export default {
teggCors: {
origin: '*', // Allow all in development
},
};
// config/config.prod.ts
export default {
teggCors: {
origin: 'https://example.com', // Restrict in production
credentials: true,
},
};TypeScript Support
Full TypeScript support with type definitions:
import type { CorsConfig } from '@gulibs/tegg-cors';
const corsConfig: CorsConfig = {
origin: 'https://example.com',
credentials: true,
allowMethods: ['GET', 'POST'],
};Testing
# Run tests
pnpm test
# Type check
pnpm run typecheck
# Lint
pnpm run lintBuild
pnpm run buildLicense
Related
- @koa/cors - Underlying CORS middleware
- egg-security - Security plugin for Egg.js
- Egg.js - Born to build better enterprise frameworks and apps
Contributing
Contributions are welcome! Please read our contributing guidelines first.
