@xenterprises/fastify-xswagger
v1.2.1
Published
Fastify plugin for route-scoped Swagger documentation with access control
Downloads
44
Readme
@xenterprises/fastify-xswagger
Fastify plugin for generating route-scoped Swagger/OpenAPI documentation with Basic Auth access control and environment-aware behavior.
Install
npm install @xenterprises/fastify-xswaggerPeer dependency: fastify@>=5.0.0
Usage
import Fastify from "fastify";
import xSwagger from "@xenterprises/fastify-xswagger";
const fastify = Fastify({ logger: true });
// Define routes with schemas
fastify.get("/public/users", {
schema: { tags: ["users"], description: "List users" }
}, async () => ({ users: [] }));
fastify.get("/admin/settings", {
schema: { tags: ["admin"], description: "Get settings" }
}, async () => ({ settings: {} }));
// Register xSwagger — creates separate docs per prefix
await fastify.register(xSwagger, {
docs: [
{ prefix: "/public", access: "public", title: "Public API" },
{ prefix: "/admin", access: "private", title: "Admin API" },
],
auth: {
username: process.env.DOCS_USER,
password: process.env.DOCS_PASSWORD,
},
disableInProduction: "public",
});
await fastify.listen({ port: 3000 });
// Public docs: http://localhost:3000/public/documentation
// Admin docs: http://localhost:3000/admin/documentation (Basic Auth)Options
| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| docs | DocConfig[] | Yes | — | Array of documentation configurations (at least one) |
| auth | { username, password } | When private docs exist | — | Basic Auth credentials for private doc access |
| disableInProduction | boolean \| 'public' | No | false | Controls which docs are disabled when NODE_ENV=production |
| docsPath | string | No | '/documentation' | Base path appended to each prefix for the Swagger UI |
| active | boolean | No | true | Set false to disable the plugin entirely |
DocConfig
| Name | Type | Required | Default | Description |
|------|------|----------|---------|-------------|
| prefix | string | Yes | — | Route prefix to document (e.g. '/api', '/admin') |
| title | string | Yes | — | Title shown in the Swagger UI header |
| access | 'public' \| 'private' | Yes | — | 'private' requires Basic Auth to view docs |
| version | string | No | '1.0.0' | API version shown in the spec |
| description | string | No | Auto-generated | Description shown in the spec info |
Environment Controls
The disableInProduction option controls docs availability when NODE_ENV === 'production':
| Value | Development | Production |
|-------|-------------|------------|
| false | All docs enabled | All docs enabled |
| true | All docs enabled | All docs disabled |
| 'public' | All docs enabled | Only private docs enabled |
Decorated Properties
After registration, the plugin decorates fastify.xswagger:
// Configuration summary (credentials are never exposed)
fastify.xswagger.config
// {
// docsPath: '/documentation',
// disableInProduction: false,
// docCount: 2,
// hasAuth: true,
// environment: 'development'
// }
// Access individual doc instances by key
// Key is the prefix with leading slash removed and slashes replaced by underscores
// /admin → admin, /api/v1 → api_v1
fastify.xswagger.docs.admin
// Each doc instance exposes:
fastify.xswagger.docs.admin.prefix // '/admin'
fastify.xswagger.docs.admin.access // 'private'
fastify.xswagger.docs.admin.title // 'Admin API'
fastify.xswagger.docs.admin.version // '1.0.0'
fastify.xswagger.docs.admin.uiPath // '/admin/documentation'
fastify.xswagger.docs.admin.specPath // '/admin/documentation/json'
fastify.xswagger.docs.admin.spec() // Returns the OpenAPI spec objectExported Constants
import xSwagger, {
ACCESS_LEVELS, // { PUBLIC: 'public', PRIVATE: 'private' }
DEFAULT_DOCS_PATH, // '/documentation'
DISABLE_MODES, // { ALL: true, PUBLIC_ONLY: 'public', NONE: false }
DEFAULT_VERSION, // '1.0.0'
} from "@xenterprises/fastify-xswagger";Hiding Routes
Routes with schema.hide: true are excluded from documentation:
fastify.get("/public/internal/debug", {
schema: { hide: true }
}, handler);Environment Variables
| Name | Required | Description |
|------|----------|-------------|
| NODE_ENV | No | Set to 'production' to activate disableInProduction behavior |
| DOCS_USER | When private docs | Username for Basic Auth (passed via auth.username) |
| DOCS_PASSWORD | When private docs | Password for Basic Auth (passed via auth.password) |
Error Reference
All errors are prefixed with [xSwagger]:
| Error | When |
|-------|------|
| [xSwagger] At least one doc configuration is required | docs is missing, empty, or not an array |
| [xSwagger] docs[N].prefix is required and must be a string | Doc config has missing/invalid prefix |
| [xSwagger] docs[N].title is required and must be a string | Doc config has missing/invalid title |
| [xSwagger] docs[N].access must be 'public' or 'private' | Doc config has invalid access level |
| [xSwagger] docs[N].version must be a string | Doc config has non-string version |
| [xSwagger] docs[N].description must be a string | Doc config has non-string description |
| [xSwagger] auth.username and auth.password are required when using private docs | Private docs defined without valid auth |
| [xSwagger] docsPath must be a non-empty string | Invalid docsPath option |
| [xSwagger] disableInProduction must be true, false, or 'public' | Invalid disableInProduction value |
How It Works
The plugin creates isolated Swagger instances for each doc configuration:
- Validation — All options are validated at startup with descriptive error messages.
- Environment check — Each doc config is evaluated against
disableInProductionandNODE_ENVto determine if it should be skipped. - Encapsulated registration — For each enabled doc,
@fastify/swaggerand@fastify/swagger-uiare registered inside an encapsulated scope to avoid decorator conflicts between instances. - Route filtering — A transform function filters the OpenAPI spec to only include routes matching the doc's prefix.
- Auth guard — Private docs get a
onRequesthook using timing-safe Basic Auth comparison viacrypto.timingSafeEqual. - Decoration — The
fastify.xswaggernamespace exposes config metadata and doc instances. Auth credentials are never stored in the config object.
Testing
npm testLicense
UNLICENSED
