Skip to content

CORS

@modularityjs/http-fastify-cors is a thin wrapper around @fastify/cors that registers CORS handling at the framework level. The module is registered once in the app's modules array; every controller route inherits the policy.

Setup

ts
import { HttpModule } from '@modularityjs/http';
import { HttpFastifyModule } from '@modularityjs/http-fastify';
import { HttpFastifyCorsModule } from '@modularityjs/http-fastify-cors';

const modules = [
  HttpModule.forRoot({ port: 3000 }),
  HttpFastifyModule,
  HttpFastifyCorsModule.forRoot({
    origin: ['https://app.example.com', 'https://admin.example.com'],
    credentials: true,
    maxAge: 600,
  }),
];

HttpFastifyCorsModule.forRoot() is optional — without it, the default origin: false rejects every cross-origin request. Apps must opt in explicitly.

Configuration

OptionDefaultNotes
originfalsestring | string[] | RegExp | RegExp[] | boolean | (origin) => boolean. Use a literal allow-list in production.
methods['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE']Echoed in Access-Control-Allow-Methods.
credentialsfalseSends Access-Control-Allow-Credentials: true. Required for cookie-based auth across origins.
allowedHeadersundefinedWhen unset, the response reflects whatever the browser sent in Access-Control-Request-Headers.
exposedHeadersundefinedHeaders JavaScript may read in addition to the safelisted ones.
maxAgeundefinedCache duration for the preflight response, in seconds.
optionsSuccessStatus204Status returned for OPTIONS preflight responses.

Tenant-aware origins

Pass a function for origin to compute the allow-list per request — useful for multi-tenant apps that read the allow-list from a database or feature flag.

ts
HttpFastifyCorsModule.forRoot({
  origin: async (origin) => {
    if (!origin) return false;
    return await tenantStore.isAllowedOrigin(origin);
  },
  credentials: true,
});