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.
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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With