Cross-Origin Resource Sharing (CORS) middleware for Koa.js applications with comprehensive configuration options
npx @tessl/cli install tessl/npm-koa--cors@5.0.00
# @koa/cors
1
2
@koa/cors provides Cross-Origin Resource Sharing (CORS) middleware for Koa.js applications, enabling developers to configure CORS policies for web applications and APIs. It offers comprehensive options for controlling access including origin specification, customizable allowed methods, configurable headers, credentials handling, and advanced security features.
3
4
## Package Information
5
6
- **Package Name**: @koa/cors
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install @koa/cors`
10
11
## Core Imports
12
13
```javascript
14
const cors = require('@koa/cors');
15
```
16
17
For ES modules:
18
19
```javascript
20
import cors from '@koa/cors';
21
```
22
23
## Basic Usage
24
25
```javascript
26
const Koa = require('koa');
27
const cors = require('@koa/cors');
28
29
const app = new Koa();
30
31
// Enable CORS with default options
32
app.use(cors());
33
34
// Or with custom options
35
app.use(cors({
36
origin: 'https://example.com',
37
allowMethods: ['GET', 'POST', 'PUT', 'DELETE'],
38
allowHeaders: ['Content-Type', 'Authorization'],
39
credentials: true
40
}));
41
42
app.listen(3000);
43
```
44
45
## Capabilities
46
47
### CORS Middleware Factory
48
49
Creates CORS middleware for Koa.js applications with configurable options.
50
51
```javascript { .api }
52
/**
53
* CORS middleware factory
54
* @param {Object} [options] - CORS configuration options
55
* @returns {Function} Koa.js middleware function
56
*/
57
function cors(options);
58
```
59
60
**Usage Examples:**
61
62
```javascript
63
// Default CORS (allows all origins with *)
64
const app = new Koa();
65
app.use(cors());
66
67
// Dynamic origin function
68
app.use(cors({
69
origin(ctx) {
70
const allowedOrigins = ['https://example.com', 'https://app.example.com'];
71
const requestOrigin = ctx.get('Origin');
72
return allowedOrigins.includes(requestOrigin) ? requestOrigin : false;
73
}
74
}));
75
76
// Comprehensive configuration
77
app.use(cors({
78
origin: 'https://trusted-domain.com',
79
allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
80
allowHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'],
81
exposeHeaders: ['X-Total-Count', 'X-Custom-Header'],
82
credentials: true,
83
maxAge: 86400, // 24 hours
84
keepHeadersOnError: true,
85
secureContext: false,
86
privateNetworkAccess: false
87
}));
88
```
89
90
### Configuration Options
91
92
```javascript { .api }
93
interface CorsOptions {
94
/** Access-Control-Allow-Origin header value */
95
origin?: string | ((ctx: Context) => Promise<string | false> | string | false);
96
/** Access-Control-Allow-Methods header value */
97
allowMethods?: string | string[];
98
/** Access-Control-Expose-Headers header value */
99
exposeHeaders?: string | string[];
100
/** Access-Control-Allow-Headers header value */
101
allowHeaders?: string | string[];
102
/** Access-Control-Max-Age header value in seconds */
103
maxAge?: string | number;
104
/** Access-Control-Allow-Credentials header */
105
credentials?: boolean | ((ctx: Context) => Promise<boolean> | boolean);
106
/** Add set headers to err.header if an error is thrown */
107
keepHeadersOnError?: boolean;
108
/** Enable Cross-Origin-Opener-Policy & Cross-Origin-Embedder-Policy headers */
109
secureContext?: boolean;
110
/** Handle Access-Control-Request-Private-Network requests */
111
privateNetworkAccess?: boolean;
112
}
113
```
114
115
**Option Details:**
116
117
- **origin**: Controls `Access-Control-Allow-Origin` header. Can be a string, function, or `'*'` (default). When `credentials` is true and origin is `'*'`, it automatically uses the request's Origin header.
118
119
- **allowMethods**: Sets allowed HTTP methods. Default: `'GET,HEAD,PUT,POST,DELETE,PATCH'`. Accepts string or array format.
120
121
- **exposeHeaders**: Specifies headers exposed to the client. Accepts string or array format.
122
123
- **allowHeaders**: Sets allowed request headers. If not specified, uses the value from `Access-Control-Request-Headers`. Accepts string or array format.
124
125
- **maxAge**: Cache duration for preflight requests in seconds. Must be string or number.
126
127
- **credentials**: Controls `Access-Control-Allow-Credentials` header. Can be boolean or function. Default: `false`.
128
129
- **keepHeadersOnError**: Whether to preserve CORS headers when errors occur. Default: `true`.
130
131
- **secureContext**: Enables secure context headers (`Cross-Origin-Opener-Policy: same-origin` and `Cross-Origin-Embedder-Policy: require-corp`). Default: `false`.
132
133
- **privateNetworkAccess**: Handles private network access requests by responding with `Access-Control-Allow-Private-Network: true`. Default: `false`.
134
135
### Middleware Function
136
137
The returned middleware function that handles CORS for each request.
138
139
```javascript { .api }
140
/**
141
* CORS middleware function
142
* @param {Object} ctx - Koa context object
143
* @param {Function} next - Next middleware in the chain
144
* @returns {Promise<void>}
145
*/
146
async function corsMiddleware(ctx, next);
147
```
148
149
**Behavior:**
150
151
- **Simple Requests**: Sets appropriate CORS headers and continues to next middleware
152
- **Preflight Requests**: Handles OPTIONS requests by setting CORS headers and responding with 204 status
153
- **Header Management**: Always sets `Vary: Origin` header for proper caching
154
- **Error Handling**: Preserves CORS headers in error responses when `keepHeadersOnError` is true
155
- **Security Features**: Supports modern security headers through `secureContext` option
156
157
## Types
158
159
```javascript { .api }
160
/**
161
* Koa context object (from Koa.js framework)
162
*/
163
interface Context {
164
/** Get request header value */
165
get(field: string): string;
166
/** Set response header */
167
set(field: string, value: string): void;
168
/** Set response status code */
169
status: number;
170
/** HTTP method of the request */
171
method: string;
172
/** Add value to Vary header */
173
vary(field: string): void;
174
}
175
176
/**
177
* Error object with headers property for CORS error handling
178
*/
179
interface CorsError extends Error {
180
headers?: Record<string, string>;
181
}
182
```
183
184
## Error Handling
185
186
When `keepHeadersOnError` is enabled (default), CORS headers are preserved in error responses:
187
188
```javascript
189
// Error with CORS headers preserved
190
app.use(cors({ keepHeadersOnError: true }));
191
app.use(async (ctx, next) => {
192
try {
193
await next();
194
} catch (err) {
195
// CORS headers are automatically included in err.headers
196
ctx.status = err.status || 500;
197
ctx.body = { error: err.message };
198
ctx.set(err.headers || {});
199
}
200
});
201
```
202
203
## Advanced Configuration Examples
204
205
**Dynamic CORS based on environment:**
206
207
```javascript
208
const isDevelopment = process.env.NODE_ENV === 'development';
209
210
app.use(cors({
211
origin: isDevelopment ? '*' : 'https://production-domain.com',
212
credentials: !isDevelopment
213
}));
214
```
215
216
**Function-based origin validation:**
217
218
```javascript
219
app.use(cors({
220
async origin(ctx) {
221
const requestOrigin = ctx.get('Origin');
222
223
// Check against database or external service
224
const isAllowed = await checkOriginPermissions(requestOrigin);
225
226
return isAllowed ? requestOrigin : false;
227
}
228
}));
229
```
230
231
**Conditional credentials:**
232
233
```javascript
234
app.use(cors({
235
origin: (ctx) => ctx.get('Origin'),
236
credentials: (ctx) => {
237
// Only allow credentials for specific paths
238
return ctx.path.startsWith('/api/auth');
239
}
240
}));
241
```