Skip to content

feat(openAPI): allow hiding routes#2890

Open
horvbalint wants to merge 6 commits into
nitrojs:v2from
horvbalint:feat/openAPIEnabled-route-option
Open

feat(openAPI): allow hiding routes#2890
horvbalint wants to merge 6 commits into
nitrojs:v2from
horvbalint:feat/openAPIEnabled-route-option

Conversation

@horvbalint
Copy link
Copy Markdown
Contributor

@horvbalint horvbalint commented Nov 18, 2024

🔗 Linked issue

#2889

❓ Type of change

  • 📖 Documentation (updates to the documentation, readme, or JSdoc annotations)
  • 🐞 Bug fix (a non-breaking change that fixes an issue)
  • 👌 Enhancement (improving an existing functionality like performance)
  • ✨ New feature (a non-breaking change that adds functionality)
  • 🧹 Chore (updates to the build process or auxiliary tools and libraries)
  • ⚠️ Breaking change (fix or feature that would cause existing functionality to change)

📚 Description

This PR adds a new property openAPIEnabled to the NitroRouteMeta and NitroRouteConfig types. Using this property one can include/exclude specific routes in the generated _openapi.json.

To only include a part of the backend one can do for example:

export default defineNitroConfig({
  experimental: {
    openAPI: true,
  },
  routeRules: {
    "**": {
      openAPIEnabled: false,
    },
    "/api/public/**": {
      openAPIEnabled: true,
    },
  },
});

It is also possible to override this rule using the routes meta, like:

// /api/public/exceptionRoute.ts

defineRouteMeta({
  openAPIEnabled: false
})

📝 Checklist

  • I have linked an issue or discussion.
  • I have updated the documentation accordingly.

@horvbalint horvbalint marked this pull request as ready for review November 18, 2024 13:30
@horvbalint horvbalint requested a review from pi0 as a code owner November 18, 2024 13:30
@xMaxximum

This comment was marked as off-topic.

@horvbalint
Copy link
Copy Markdown
Contributor Author

hey, @horvbalint what's the progress on this? I looked at the checks and the error don't seem to have anything to do with the additon of the property.

Hi, the PR is ready for review I think. The error in the checks dont seem to come from my changes, but I had no time to investigate it :/

@xMaxximum

This comment was marked as off-topic.

@Nonolanlan1007 Nonolanlan1007 mentioned this pull request Feb 12, 2025
1 task
@nitrojs nitrojs deleted a comment from necmettindev Mar 2, 2025
@miantiao-me
Copy link
Copy Markdown

Expecting to be able to merge secondary PRs, a lot of the OpenAPI generated by the current code is not needed

CleanShot 2025-05-21 at 19 57 03@2x
CleanShot 2025-05-21 at 19 58 21@2x

@bitbytebit1
Copy link
Copy Markdown

I was also looking for this feature. In the mean time I achieved the same using a nitro plugin:

export default defineNitroPlugin((nitroApp) => {
  nitroApp.hooks.hook("beforeResponse", (event, { body }) => {
    if (event.path === "/openapi.json") {
      const entriesToDelete = [
        "/openapi.json",
        "/_docs/scalar",
        "/",
      ];
      entriesToDelete.forEach((entry) => {
        delete body.paths[entry];
      });
    }
  });
});

@pi0 pi0 changed the title feat: Add openAPIEnabled property to route metas and route rules feat(openAPI): allow hiding routes Dec 16, 2025
@vercel
Copy link
Copy Markdown

vercel Bot commented Dec 16, 2025

@pi0 is attempting to deploy a commit to the Nitro Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Dec 16, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@pkg-pr-new
Copy link
Copy Markdown

pkg-pr-new Bot commented Dec 16, 2025

Open in StackBlitz

npm i https://pkg.pr.new/nitrojs/nitro/nitropack@2890

commit: c11303c

@vachmara
Copy link
Copy Markdown

My fully typed version adapted from @bitbytebit1 :

import { defineNitroPlugin, useRuntimeConfig } from 'nitropack/runtime'
import { createRouter, toRouteMatcher } from 'radix3'

declare module 'nitropack/types' {
  interface NitroOpenAPIConfig {
    allow?: string[]
  }
}

export default defineNitroPlugin((nitroApp) => {
  const openapi = useRuntimeConfig()?.nitro?.openAPI
  const endpoint = openapi?.route || '/_openapi.json'
  const allow: string[] = Array.isArray(openapi?.allow) ? openapi.allow : []

  const router = createRouter({
    routes: Object.fromEntries(allow.map(p => [p, { ok: true }]))
  })
  const matcher = toRouteMatcher(router)

  nitroApp.hooks.hook('beforeResponse', (event, response) => {
    const body = response.body as { paths?: Record<string, unknown> }
    if (event.path !== endpoint) return
    if (!body?.paths) return

    for (const p of Object.keys(body.paths)) {
      // If allowlist is empty => keep everything
      if (allow.length && matcher.matchAll(p).length === 0) {
        delete body.paths?.[p]
      }
    }
  })
})

Usage on nuxt.config.ts:

export default defineNuxtConfig({
  nitro: {
    openAPI: {
      allow: [
        '/api/**'
      ],
    }
  }
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants