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
| Option | Default | Notes |
|---|---|---|
origin | false | string | 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. |
credentials | false | Sends Access-Control-Allow-Credentials: true. Required for cookie-based auth across origins. |
allowedHeaders | undefined | When unset, the response reflects whatever the browser sent in Access-Control-Request-Headers. |
exposedHeaders | undefined | Headers JavaScript may read in addition to the safelisted ones. |
maxAge | undefined | Cache duration for the preflight response, in seconds. |
optionsSuccessStatus | 204 | Status 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,
});