sam-goodwin / eventual

Build scalable and durable micro-services with APIs, Messaging and Workflows
https://docs.eventual.ai
MIT License
174 stars 4 forks source link

feat: support api gateway and path based CORS #305

Closed thantos closed 1 year ago

thantos commented 1 year ago

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.

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(...)