Joor provides built-in support for Cross-Origin Resource Sharing (CORS), allowing you to securely share resources across different origins.

Importing CORS

To use the CORS functionality in your Joor application, you need to import the cors function from the joor package:

import { cors } from 'joor';

The cors function takes an options object with these properties:

PropertyTypeDefaultDescription
originsstring[]["*"]An array of allowed URLs. Supports patterns like https://*.example.com.
methodsstring[]["*"]An array of uppercase HTTP methods (e.g., ["GET", "POST"]).
allowedHeadersstring[]["*"]An array of acceptable headers. Use capitalized headers, e.g., Content-Type.
exposedHeadersstring[] or stringundefinedA string or array listing headers exposed to clients. Optional.
allowsCookiesbooleanfalseA boolean indicating whether credentials are allowed.
maxAgenumber0A number (in seconds) that sets how long a preflight response is cached.

If any required array is missing or invalid, Joor defaults to ["*"]. Currently, only global CORS is supported.

Pattern Matching in Origins

The origins property supports pattern matching to allow multiple subdomains or specific URL patterns. For example:

  • https://*.example.com allows any subdomain of example.com.

Example Usage

Basic Example

import Joor, { cors } from 'joor';
import { CORS_OPTIONS } from 'joor/types';

const app = new Joor();
const corsOptions: CORS_OPTIONS = {
  origins: ['http://localhost:3000'],
  methods: ['GET', 'POST'],
  allowedHeaders: ['Content-Type'],
  allowsCookies: true,
};

app.use(cors(corsOptions));
app.start();

Example with All Defaults

import Joor, { cors } from 'joor';

const app = new Joor();

app.use(cors());
app.start();

Example with Custom Headers and Methods

import Joor, { cors } from 'joor';
import { CORS_OPTIONS } from 'joor/types';

const app = new Joor();
const corsOptions: CORS_OPTIONS = {
  origins: ['https://*.example.com'],
  methods: ['GET', 'POST', 'PUT'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  exposedHeaders: ['X-Custom-Header'],
  allowsCookies: false,
  maxAge: 3600,
};

app.use(cors(corsOptions));
app.start();

CORS_OPTIONS is a type alias covering all supported CORS properties. If the options provided are invalid or not an object, a cors-options-invalid exception is thrown. If the options object lacks valid required data, defaults are applied.