Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastify Swagger - Exclude certain routes

Tags:

fastify

when using the @fastify-swagger plugin, is there an easy way to exclude certain routes via the @fastify-swagger options?

I know this can be done within the schema by specifing hide: true, but it would be useful to exclude routes by endpoints.

like image 409
Dally Avatar asked Sep 20 '25 16:09

Dally


2 Answers

You can add schema: { hide: true } explicitly on specific routes you want to hide

fastify.get("/b", { schema: { hide: true } }, hello);  // hide from swagger UI
fastify.get("/c", { schema: { tags: ["X-HIDDEN"] } }, hello); // also hide from swagger UI
like image 112
TBA Avatar answered Sep 23 '25 10:09

TBA


You can do it by using the onRoute hook, here is a quick example:

async function run () {
  const fastify = require('fastify')({ logger: true });

  await fastify.register(require('@fastify/swagger'))
  await fastify.register(require('@fastify/swagger-ui'), {
    routePrefix: '/docs',
  })

  fastify.addHook('onRoute', (routeOptions) => {

    const shouldHide = [
      '/a',
      '/c',
    ].includes(routeOptions.url);

    if (shouldHide) {
      routeOptions.schema ??= {};
      routeOptions.schema.hide = true;
    }

  });

  function hello () {
    return { hello: 'world' };
  }

  fastify.get('/a', hello); // it will be hidden
  fastify.get('/b', hello);
  fastify.get('/c', hello); // it will be hidden
  fastify.get('/d', hello);

  await fastify.listen({ port: 3000 });
}

run()

Output at http://localhost:3000/docs

enter image description here


UPDATE 2025:

A new feature has been added to hide it more easily: https://github.com/fastify/fastify-swagger?tab=readme-ov-file#hide-a-route

like image 42
Manuel Spigolon Avatar answered Sep 23 '25 09:09

Manuel Spigolon