Uses API Gateway's CORS configuration and the command worker to handler CORS. APIg adds the CORS headers to any response that matches the configuration (headers, methods, etc) and the $default path returns a 204 response on OPTIONS.
No middleware required, no response headers required, same behavior for ALL paths.
new Service(..., {
cors: {
allowHeaders: ["authorization", "content-type"],
// TODO: Change this for prod!
allowOrigins: ["*"],
allowMethods: [CorsHttpMethod.ANY],
},
})
Option 2 - Custom
Uses a command and the router to handler CORS. Requires the commands to return CORS headers manually or via a middleware. Requires the OPTIONS path(s) to be implemented. Allows for customization and dynamic behavior beyond the API level which API gateway allows for.
// Middleware
export async function cors<In>({
next,
context,
}: MiddlewareInput<In>): Promise<MiddlewareOutput<In>> {
const response = await next(context);
// change for prod!!
response.headers.set("Access-Control-Allow-Origin", "*");
response.headers.set(
"Access-Control-Allow-Headers",
"Authorization,Content-Type"
);
return response;
}
// options command
// the "*" path is turned into a /{proxy+}
cors.options("*", () => return new HttpResponse(undefined, { status: 204 })); // or 200
// any command or path
cors.command(...)
cors.get(...)
Advanced and tested CORS support!
Option 1 - Infra Config
Uses API Gateway's CORS configuration and the command worker to handler CORS. APIg adds the CORS headers to any response that matches the configuration (headers, methods, etc) and the $default path returns a 204 response on OPTIONS.
No middleware required, no response headers required, same behavior for ALL paths.
Option 2 - Custom
Uses a command and the router to handler CORS. Requires the commands to return CORS headers manually or via a middleware. Requires the OPTIONS path(s) to be implemented. Allows for customization and dynamic behavior beyond the API level which API gateway allows for.