CORS handling
@duplojs/http/cors automatically adds CORS headers to regular responses and creates an OPTIONS /* route to handle preflight requests.
Full example
ts
import { createHub } from "@duplojs/http";
import { corsPlugin } from "@duplojs/http/cors";
export const hub = createHub({ environment: "DEV" })
.plug(
corsPlugin({
allowOrigin: [
"https://app.example.com",
"https://admin.example.com",
],
allowHeaders: ["content-type", "authorization"],
exposeHeaders: ["x-request-id", "x-rate-limit-remaining"],
allowMethods: true,
credentials: true,
maxAge: 600,
}),
);In this example:
allowOriginrestricts which origins are allowed.allowHeadersdeclares which HTTP headers are accepted during preflight.exposeHeadersmakes selected headers readable by the browser.allowMethods: trueautomatically generatesaccess-control-allow-methodsfrom the routes registered in theHub.credentials: trueaddsaccess-control-allow-credentials: truefor credentials.maxAgedefines the preflight cache duration in seconds.
Params interface
ts
interface CorsPluginParams {
readonly allowOrigin?:
| string
| RegExp
| readonly string[]
| ((origin: string) => boolean | Promise<boolean>)
| true;
readonly allowHeaders?: string | readonly string[] | true;
readonly exposeHeaders?: string | readonly string[];
readonly maxAge?: number;
readonly credentials?: boolean;
readonly allowMethods?: RequestMethods | readonly RequestMethods[] | true;
}You must provide at least one option to the plugin.
Option details
allowOriginaccepts a single origin, a list, a regular expression, a validation function, ortrueto allow all origins.allowHeadersaccepts a string, a list, ortruefor all headers.exposeHeaderslists the headers the browser can read after the request.allowMethodsaccepts one method, a list, ortrueto compute allowed methods automatically per path.credentialsenables cookies and other authentication credentials to be shared.maxAgecontrols how long theOPTIONSresponse can be cached.
