# CustomOrigin

**Kind:** Type

**Source:** [`packages/common/interfaces/external/cors-options.interface.ts`](https://github.com/nestjs/nest/blob/master/packages/common/interfaces/external/cors-options.interface.ts#L12)

**Part of:** [Common](subsystem-packages-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

```mermaid
graph 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

```ts
import 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 `CustomOrigin` as a callback-based function; always call the callback with `(error, allowed)`.
- Return `true` only 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 `Origin` header.
- 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.
