Kind: Type
Source: packages/common/interfaces/external/cors-options.interface.ts
Part of: Common
Set origin to a function implementing some custom logic. The function takes the request origin as the first parameter and a callback (which expects the signature err [object], allow [bool]) as the second.
CustomOrigin defines a callback-based function used to determine whether a request origin is allowed for CORS. It receives the incoming origin and must invoke a callback with either an error or a boolean indicating whether the origin should be permitted.
Definition
ts( requestOrigin: string | undefined, callback: (err: Error | null, origin?: StaticOrigin) => void, ) => void
Diagram
mermaidgraph LR A[Incoming request] --> B[Request Origin] B --> C[CustomOrigin function] C --> D{Custom validation logic} D -->|Allowed| E[callback(null, true)] D -->|Denied| F[callback(null, false)] D -->|Error| G[callback(error)]
Usage
tsimport type { CustomOrigin } from './cors-options.interface';
const allowedOrigins = new Set([
'https://app.example.com',
'https://admin.example.com',
]);
const validateOrigin: CustomOrigin = (origin, callback) => {
// Requests without an Origin header, such as server-to-server calls.
if (!origin) {
return callback(null, true);
}
if (allowedOrigins.has(origin)) {
return callback(null, true);
}
return callback(null, false);
};
// Example CORS configuration
const corsOptions = {
origin: validateOrigin,
};
AI Coding Instructions
- Implement
CustomOriginas a callback-based function; always call the callback with(error, allowed). - Return
trueonly after validating the supplied origin against trusted configuration or application rules. - Handle missing origins intentionally, since non-browser or same-origin requests may not include an
Originheader. - Use
callback(null, false)for denied origins and reserve errors for validation or configuration failures. - Keep origin validation centralized so CORS policy remains consistent across application entry points.
Was this page helpful?