delvedor/find-my-way

Method 'OPTIONS' already declared for route '/*'

twalling opened this issue · 6 comments

It seems around the 7.0.1 update something changed which now throws an error for my following route.

const httpMethods: HTTPMethods[] = [
  'DELETE',
  'GET',
  'HEAD',
  'PATCH',
  'POST',
  'PUT',
  'OPTIONS',
];

export default async function proxy(fastify: FastifyInstance) {
  fastify.route({
    method: httpMethods,
    url: '/',
    handler,
  });

  fastify.route({
    method: httpMethods,
    url: '/*',
    handler,
  });
}

Nothing changed in our app and I've been running into this when I upgrade fastify from 4.6.0 to 4.7.0 (or higher). That was when the dependency for find-my-way went from 7.0.0 to 7.2.0. Looking through diffs/releases it seems like the 7.0.1 update may have touched something which affected our setup.

We're not using fastify-static which I've seen from past issues can also be an issue.

Hi, thanks for reporting. I think it might be #297. If you want you can find and fix it or I will do it when i have some time for it.

I'll start with forking and seeing if I can expose it via a test. Thanks.

I couldn't reproduce with a test. I think everything is fine here. For anyone who might run into this I've been able to narrow it down to @fastify/cors which was adding a route at *. To figure out which fastify plugin was adding the conflicting route I added this to my app:

  fastify.addHook('onRoute', (route) => {
    console.log('adding route', route.url);
  });

Then proceeded to comment out each fastify plugin I was using. Now I just have to figure out how to resolve the issue.

So @fastify/cors adds the following route:

  fastify.options('*', { schema: { hide: hideOptionsRoute } }, (req, reply) => {
    if (!req.corsPreflightEnabled) {
      // Do not handle preflight requests if the origin option disabled CORS
      reply.callNotFound()
      return
    }

    reply.send()
  })

https://github.com/fastify/fastify-cors/blob/master/index.js#L42

#297 specifically prevents my routes that I documented in this ticket from being used when @fastify/cors is used. Before closing this ticket I'm just curious if anyone has any input on what the correct setup would be? It would seem right now that one cannot use @fastify/cors and @fastify/http-proxy together on a project. (I'm using the same approach @fastify/http-proxy regarding routes.

You can separate this two hanlders by using constraints. I guess proxy request should have specific header you can use. Does it work for you?

I have everything I need. Thanks for all the quick responses.