fastify / fastify-cors

Fastify CORS
MIT License
419 stars 59 forks source link

Multiple @fastify/cors #284

Closed hibangun closed 6 months ago

hibangun commented 10 months ago

Prerequisites

Issue

I have a project that follow @mcollina's modular monolith structure, like

- modules
  - foo
    - routes
    - index.ts
    - preHandler.ts
  - another_foo

Inside foo/preHandler.ts I have

import fastifyCors from "@fastify/cors";

async function foo(
  fastify: FastifyInstance,
  opts: FastifyPluginOptions
): Promise<void> {
  ...
  fastify.register(fastifyCors, {
    origin: "http://firsturl",
    methods: ["GET"],
    credentials: true,
  });
}

export default fp(foo);

But I want to setup the cors in another endpoint /another_foo, so inside another_foo/preHandler.ts I have

import fastifyCors from "@fastify/cors";

async function another_foo(
  fastify: FastifyInstance,
  opts: FastifyPluginOptions
): Promise<void> {
  ...
  fastify.register(fastifyCors, {
    origin: "http://secondurl",
    methods: ["POST", "PUT"],
    credentials: true,
  });
}

export default fp(another_foo);

using this approach I got error like this:

[ERROR] 21:13:01 FastifyError: The decorator 'corsPreflightEnabled' has already been added!

So basically the goal I want to achieve is to be able to set different cors for different url, can anyone help me?

mcollina commented 10 months ago

You'd need to handle encapsulation better: https://fastify.dev/docs/latest/Guides/Plugins-Guide/#how-to-handle-encapsulation-and-distribution.

Fdawgs commented 6 months ago

Closing as has been answered by @mcollina above.