npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

setupdocs

v1.0.1

Published

Explicit, FastAPI-style OpenAPI 3.0 documentation for Express: mark routes with swag.route() and get a live Swagger UI.

Readme

SetupDocs

Explicit, FastAPI-flavoured API documentation for Express.

Create one docs instance, mount it, then mark the routes you want documented with swag.route():

const swag = SetSwagger();
app.use(swag);

app.get("/users", swag.route(), handler);
app.post("/users", swag.route(), handler);

SetupDocs reads the path and HTTP method from Express. You never repeat them. Only routes that include swag.route() appear in the docs.

Install

npm install setupdocs

Express is a peer dependency (Express 4.18+ or Express 5.x):

npm install express

Requires Node.js 18 or newer. SetupDocs is tested against Express 4.22 and Express 5.3, and against Zod 4.6.7 when the optional Zod adapter is used.

Quick start

import express from "express";
import { SetSwagger } from "setupdocs";

const app = express();
app.use(express.json());

// 1. Create the docs instance.
const swag = SetSwagger({
  title: "My API",
  version: "1.0.0",
});

// 2. Mount it. This serves /docs and /docs.json.
app.use(swag);

// 3. Mark routes you want documented.
app.get("/users", swag.route(), (req, res) => {
  res.json([{ id: 1, name: "Ada" }]);
});

app.get("/users/:id", swag.route(), (req, res) => {
  res.json({ id: Number(req.params.id), name: "Ada" });
});

app.listen(3000);

Open:

  • http://localhost:3000/docs — Swagger UI
  • http://localhost:3000/docs.json — OpenAPI 3.0 JSON

A route is visible in the JSON document before its first request. No warm-up call is needed.

What is automatic

For every marked route, SetupDocs discovers:

  • the HTTP method (GET, POST, PUT, PATCH, DELETE, ...);
  • the Express path, including mount prefixes from nested routers on Express 4 (Express 5 requires swag.mountRouter() or a per-route prefix);
  • path parameters (/users/:id becomes /users/{id});
  • a default operation ID.

With no metadata, SetupDocs adds a basic summary (GET /users) and one default response that states the handler's responses are undocumented. default is OpenAPI-valid and does not claim that the handler returns 200. Declare the real status codes with swag.route({ responses: { ... } }).

Compatibility note: earlier releases emitted a generic 200 Successful response for routes without response metadata. The neutral default response replaces that fallback. This is a documentation-only change: Express still uses whatever status code the handler sends.

Paths

Express paths are converted to valid OpenAPI templates, and every template variable gets a matching required parameter:

| Express path | OpenAPI path | Parameters | | --- | --- | --- | | /users/:id | /users/{id} | id (string) | | /users/:id? | /users/{id} | id (required in OpenAPI; optional in Express) | | /users/:id(\\d+) | /users/{id} | id (integer) | | /files/* | /files/{wildcard} | wildcard (string) | | /users(.:format)? | /users | - | | ['/a', '/b'] | /a and /b | - |

Express 5 wildcards (/files/*rest -> /files/{rest}) and optional groups (/users{/:id} -> /users/{id}) are detected from the running Express version.

Path forms OpenAPI cannot express - regular-expression routes, unnamed non-optional groups, duplicate parameter names - throw a PathSyntaxError naming the path instead of emitting a broken document.

Methods OpenAPI does not define (for example CONNECT, or the extra verbs registered by app.all) are skipped with a console warning. A path is never emitted with zero operations, and duplicate method + path registrations keep the first marker and warn.

What is not automatic

Express handlers are ordinary functions. Unlike FastAPI, where request and response models are part of the function signature, an Express handler does not expose:

  • the shape of req.body;
  • what res.json(...) returns;
  • which status codes it can produce;
  • validation rules;
  • authentication requirements;
  • descriptions, tags, or examples.

SetupDocs does not inspect handler code to guess these things. Supply them through metadata when you need richer documentation.

Adding metadata

Metadata is optional and goes inside swag.route(...):

app.post(
  "/users",
  swag.route({
    summary: "Create a user",
    description: "Creates a user and returns the stored record.",
    tags: ["Users"],
    requestBody: {
      required: true,
      content: {
        "application/json": {
          schema: {
            type: "object",
            required: ["name"],
            properties: {
              name: { type: "string" },
              email: { type: "string", format: "email" },
            },
          },
        },
      },
    },
    responses: {
      201: { description: "User created" },
      400: { description: "Invalid request body" },
    },
  }),
  handler
);

Path and method still come from Express. The metadata only adds information that Express cannot provide.

Request bodies and responses

Register express.json() before routes that read JSON. Body parsing belongs to the consuming Express app; SetupDocs does not install application middleware.

import express from "express";
import { SetSwagger } from "setupdocs";

const app = express();
app.use(express.json());

const swag = SetSwagger({ title: "Students API", version: "1.0.0" });
app.use(swag);

app.post(
  "/students",
  swag.route({
    summary: "Create a student",
    requestBody: {
      required: true,
      description: "Student to create",
      content: {
        "application/json": {
          schema: {
            type: "object",
            required: ["name", "age", "fav_subject"],
            properties: {
              name: { type: "string" },
              age: { type: "integer" },
              fav_subject: { type: "string" },
            },
          },
          example: { name: "Ada", age: 20, fav_subject: "Maths" },
        },
      },
    },
    responses: {
      201: { description: "Student created" },
      400: { description: "Missing or invalid request body" },
      500: { description: "Unexpected server error" },
    },
  }),
  (req, res) => {
    if (!req.body?.name) {
      return res.status(400).json({ error: "name is required" });
    }
    return res.status(201).json({ id: 1, name: req.body.name });
  }
);

A valid requestBody is copied into the generated operation, so Swagger UI shows a Request body editor with the documented JSON schema, media type, required fields, description, and example. Request bodies are never represented as path parameters, and SetupDocs never guesses a schema from req.body.

responses is documentation, not runtime control. The codes you declare are what Swagger UI lists; the handler decides what it actually sends. A handler that returns 500 does not change the static OpenAPI document, and documenting 201 does not make a failed request succeed. If you omit responses, SetupDocs emits a neutral default response instead of implying 200.

Metadata fields

| Field | Purpose | | --- | --- | | summary | Short operation title | | description | Longer explanation | | tags | Group operations in Swagger UI | | operationId | Stable operation identifier | | deprecated | Mark the operation as deprecated | | security | Per-operation security, e.g. [{ BearerAuth: [] }]; [] opts out of global security | | parameters | Extra query, header, or cookie parameters | | requestBody | Request body content and schemas | | responses | Response descriptions, content, and schemas | | extensions | Custom x-* OpenAPI extensions | | prefix | Explicit mount prefix for Express 5 nested routers |

Path parameters are generated automatically; do not add them manually.

Metadata validation

Metadata is validated while the spec is generated. Malformed values throw an error that names the route and field instead of emitting a document that only fails when Swagger UI or another OpenAPI tool loads it. This covers, among others:

  • non-string summaries, descriptions, and operation IDs;
  • non-string or empty tag names;
  • invalid parameter names, in values, and non-boolean flags;
  • parameter and response header objects that do not define exactly one of schema or content, and content maps with more than one media type;
  • request bodies without a non-empty content object;
  • invalid media type keys such as "application json";
  • response keys that are not a status code, a range such as "2XX", or "default";
  • response objects without a string description;
  • malformed schema shapes such as non-object properties, non-array required, empty enum or allOf, and invalid type values;
  • security requirements that are not arrays of objects with string arrays as scope lists;
  • malformed security scheme definitions such as an http scheme without scheme, an apiKey without name/in, an oauth2 scheme without at least one supported flow, or an openIdConnect scheme without openIdConnectUrl;
  • OAuth2 flows with missing or empty required URLs, non-HTTP(S) or relative URLs, non-object or non-string scopes entries, unsupported flow names, or unsupported flow fields;
  • Reference Objects with sibling fields other than $ref.

Local $ref values are resolved against the finished document, so a typo like #/components/schemas/Usr throws instead of producing a dangling reference. Strings that merely look like references inside example, examples, default, enum, or const are treated as data and are not resolved. External references are allowed because SetupDocs does not bundle them. requestBody, individual responses, and response headers also accept a top-level { $ref: "..." } object, which is passed through and validated.

Valid metadata is copied unchanged. Validation never coerces a value or drops an invalid field silently.

Security

securitySchemes only defines reusable schemes under components.securitySchemes. Defining a scheme does not make any route protected:

const swag = SetSwagger({
  securitySchemes: {
    BearerAuth: { type: "http", scheme: "bearer", bearerFormat: "JWT" },
  },
});

app.get("/public", swag.route(), handler);                       // public
app.get("/private", swag.route({ security: [{ BearerAuth: [] }] }), handler);

To protect everything by default, opt in explicitly with the document-level security option. Individual operations can then opt out with security: [] (OpenAPI's way of overriding global security):

const swag = SetSwagger({
  securitySchemes: { BearerAuth: { type: "http", scheme: "bearer" } },
  security: [{ BearerAuth: [] }],
});

app.get("/dashboard", swag.route(), handler);          // inherits global auth
app.get("/health", swag.route({ security: [] }), handler); // explicitly public

Referencing a scheme that is not defined throws at generation time; SetupDocs never silently falls back to a default scheme.

Nested routers

With Express 4, mount prefixes are discovered automatically:

const users = express.Router();

users.get(
  "/:id",
  swag.route({ summary: "Get a user" }),
  handler
);

app.use("/api/v1", users);
// Documented as /api/v1/users/{id}

A router mounted directly at the root (app.use(users) or app.use("/", users)) works on both Express 4 and Express 5.

Express 5 limitation and workaround

Express 5's router package no longer keeps the app.use() mount path on the router layer. For a router mounted at a non-root path:

app.use("/api/v1", users); // Express 5

SetupDocs cannot automatically recover /api/v1. It warns and skips the marked routes inside that router rather than documenting them at the wrong path (/users/{id}).

Workarounds:

  1. Explicit prefix in metadata (per-route):

    const users = express.Router();
    users.get(
      "/:id",
      swag.route({ prefix: "/api/v1", summary: "Get a user" }),
      handler
    );
    app.use("/api/v1", users);
    // Documented as /api/v1/users/{id}
  2. swag.mountRouter(router, prefix) (per-router):

    const users = express.Router();
    users.get("/:id", swag.route({ summary: "Get a user" }), handler);
    app.use("/api/v1", users);
    swag.mountRouter(users, "/api/v1");
    // All marked routes in `users` documented under /api/v1

    The prefix is the mount path exactly as passed to app.use() or router.use(). For a top-level router that is an absolute path. For a nested router it is relative to the parent router. A root mount (app.use(router)) needs no prefix and does not consume an entry.

    const api = express.Router();
    const users = express.Router();
    users.get("/:id", swag.route(), handler);
    
    api.use("/users", users);
    app.use("/api/v1", api);
    
    swag.mountRouter(api, "/api/v1");
    swag.mountRouter(users, "/users"); // relative to `api`
    // Documented as /api/v1/users/{id}
  3. Register routes directly on the app (no nested router), or use Express 4 when automatic nested-router prefixes are required.

The same router at multiple prefixes

A router instance can be mounted more than once, and each mount can be documented separately. Pass an array of mount prefixes in mount order:

app.use("/api/v1", users);
app.use("/api/v2", users);
swag.mountRouter(users, ["/api/v1", "/api/v2"]);

// Documented under both /api/v1/users and /api/v2/users

Repeated calls append to the same ordered list, so this is equivalent and works with existing single-prefix code:

swag.mountRouter(users, "/api/v1");
swag.mountRouter(users, "/api/v2");

Nested routers follow the same rule per physical mount. When a parent router is mounted twice, a child router mounted once inside it is traversed twice but still has one mount, so register its prefix once:

const api = express.Router();
const users = express.Router();
users.get("/:id", swag.route(), handler);

api.use("/users", users);
app.use("/api/v1", api);
app.use("/api/v2", api);

swag.mountRouter(api, ["/api/v1", "/api/v2"]);
swag.mountRouter(users, "/users"); // reused for both parent mounts
// Documented as /api/v1/users/{id} and /api/v2/users/{id}

Parameterised mount prefixes work the same way:

app.use("/orgs/:orgId/v1", users);
app.use("/orgs/:orgId/v2", users);
swag.mountRouter(users, ["/orgs/:orgId/v1", "/orgs/:orgId/v2"]);
// Documented under /orgs/{orgId}/v1/... and /orgs/{orgId}/v2/...

Prefixes are matched to physical mounts in the order Express stores them. If a router has more mounts than registered prefixes, the extra mounts are skipped with a warning instead of being documented under a guessed path. One prefix entry per mount keeps the generated document accurate.

Options

const swag = SetSwagger({
  title: "My API",              // default: "API Documentation"
  version: "2.0.0",             // default: "1.0.0"
  description: "About this API",
  path: "/docs",                // Swagger UI path
  specPath: "/docs.json",       // OpenAPI JSON path
  servers: [
    { url: "https://api.example.com", description: "Production" },
  ],
  securitySchemes: {              // definitions only - nothing is protected yet
    BearerAuth: { type: "http", scheme: "bearer" },
  },
  security: [],                   // document-level security; [] = none (default)
  customCss: ".topbar { display: none; }",
  customJs: "",
  favicon: "https://example.com/favicon.ico",
  tryItOutEnabled: true,
  persistAuthorization: false,    // default: false - opt in to storing credentials
  specCors: false,                // default: false - no wildcard CORS on the spec
  specCache: false,               // default: false - no-store HTTP caching
  specCachePolicy: "private",     // "private" | "public" | "no-store"; used when specCache is true
  specCacheMaxAge: 3600,          // default: 3600 seconds, used when specCache is true
  docsCachePolicy: "public",      // "public" | "private" | "no-store" for the /docs HTML page
  allowFraming: false,            // default: false - UI cannot be iframed
  serveAssetsLocally: false,      // default: false - use the pinned CDN
  filter: true,
  deepLinking: true,
  displayRequestDuration: false,
});

Swagger UI assets and the spec endpoint

By default the docs page loads Swagger UI 5.11.0 from https://unpkg.com/[email protected]. The version is pinned, the CDN stylesheet and script tags carry Subresource Integrity (SRI) hashes for the exact 5.11.0 files, and script requests use crossorigin="anonymous". A compromised CDN response or npm package with different bytes is therefore blocked by the browser instead of executing in the docs origin.

SRI only protects the CDN path. The browser still needs network access to unpkg.com, and that third-party origin can observe requests for the docs assets. For security-sensitive deployments, or when you need the page to work without a public CDN, install the matching package and self-host the assets:

npm install [email protected]
const swag = SetSwagger({ serveAssetsLocally: true });

swagger-ui-dist is an optional peer dependency. Enabling serveAssetsLocally without it throws a descriptive error when SetSwagger() is called, rather than serving a page whose CSS/JS 404s. Local assets are served from <path>/swagger-ui.css, <path>/swagger-ui-bundle.js, <path>/swagger-ui-standalone-preset.js, <path>/favicon-32x32.png and <path>/oauth2-redirect.html. Only those allowlisted filenames are served; other package files and path-traversal attempts return 404. The local asset responses use Cache-Control: public, max-age=86400, immutable independently of docsCachePolicy.

The SRI hashes in src/ui-server.ts are tied to Swagger UI 5.11.0. If the pinned version is changed, recompute the hashes from the exact versioned swagger-ui-dist files and update the constants in the same change. Do not copy hashes from another version.

The OpenAPI JSON endpoint is intentionally conservative:

  • specCors: false (default) emits no Access-Control-Allow-Origin header. Set it to true only if another origin is meant to read the spec. When enabled, OPTIONS gets a CORS preflight response; otherwise it gets 405.

  • specCache: false (default) sends Cache-Control: no-store, no-cache, must-revalidate. Set it to true to enable HTTP caching. specCachePolicy then controls the header:

    • "private" (default) sends Cache-Control: private, max-age=<specCacheMaxAge>. Browsers may cache the response, but shared caches such as CDNs and reverse proxies must not. This is the safe default for authenticated docs.
    • "public" sends Cache-Control: public, max-age=<specCacheMaxAge>. Use this only when the document is intentionally public. Do not use it for docs behind authentication unless your edge cache is configured to strip or bypass cached entries for unauthenticated users.
    • "no-store" sends Cache-Control: no-store, no-cache, must-revalidate even though the server-side memo remains active.

    specCacheMaxAge defaults to 3600 seconds. The HTTP header is a hint for browsers and intermediate caches; it does not control server-side generation.

    The server keeps a memoised OpenAPI document per SetupDocs instance. The memo is validated by a fingerprint of the Express router stack, including route paths/methods, markers, and swag.mountRouter() prefix lists. When routes are added, removed, or mountRouter prefixes change, the fingerprint changes and the document is regenerated automatically on the next request. The fingerprint does not track mutations of existing metadata objects or SetSwagger() configuration objects; call swag.invalidateSpecCache() if you mutate either at runtime.

  • docsCachePolicy controls the /docs HTML page independently of the spec:

    • "public" (default) sends Cache-Control: public, max-age=3600. The page is static for a given configuration and does not contain the OpenAPI document, so this remains the historical default.
    • "private" sends Cache-Control: private, max-age=3600. Browsers may cache the page, but shared caches must not.
    • "no-store" sends Cache-Control: no-store, no-cache, must-revalidate.

    Use "private" or "no-store" when the docs are behind authentication and you do not want a CDN or reverse proxy to retain the HTML page. This option does not affect /docs.json; use specCache and specCachePolicy for the document. Self-hosted Swagger UI assets keep their own Cache-Control: public, max-age=86400, immutable header. Invalid docsCachePolicy or specCachePolicy values throw when SetSwagger() is called instead of silently falling back.

  • persistAuthorization: false (default) keeps entered credentials in memory for the page session only. Set it to true to persist them across reloads.

  • allowFraming: false (default) sends X-Frame-Options: DENY and Content-Security-Policy: frame-ancestors 'none' on the docs page. Enable it only if you intentionally embed the page; otherwise a hostile page could overlay Swagger UI's "Try it out" controls.

Both docs endpoints accept only GET and HEAD (OPTIONS is added for CORS preflight when specCors is on); other methods receive 405 Method Not Allowed.

The docs endpoints have no built-in authentication. Marking routes with swag.route() controls what is documented, not who can read the documentation. In production, mount the docs behind your existing auth middleware, disable them when not needed, or at minimum be aware that /docs.json reveals every marked path and every schema you attached to it.

Mount the docs on a protected router so the auth middleware runs first:

const requireDocsAuth = (req, res, next) => {
  // Use your existing session, bearer-token, or SSO check here.
  if (isAuthorized(req)) return next();
  return res.status(401).json({ error: "Unauthorized" });
};

// Docs are served at /internal/docs and /internal/docs.json.
app.use("/internal", requireDocsAuth, swag);

If the docs must stay at /docs and /docs.json, guard those paths before app.use(swag). Middleware order matters: a docs request that reaches app.use(swag) first will be served without running later auth middleware.

When the docs are protected, also set docsCachePolicy: "private" or "no-store" and keep specCache off (or use specCachePolicy: "private" / "no-store") so a shared cache cannot retain either response for a different user or access boundary.

The document is memoised, but each /docs.json request still walks the router stack to check the cache fingerprint. That per-request CPU cost grows with the number of routes and mounts. If /docs.json is publicly reachable in a large application, put it behind authentication and an edge cache, and apply rate limiting. specCache only controls HTTP cache headers; it does not remove the server-side fingerprint cost. Marking a route is what makes it appear in the document; the marker itself does not add runtime authentication to your application.

Trusted configuration

customCss and customJs are injected verbatim into the documentation page. They are code, not data: treat them exactly like a <script> tag you wrote yourself. Never build them from request input, environment values controlled by other users, database content, or query parameters. If you need per-request content in the docs page, put it in your OpenAPI metadata instead.

Every other option (title, description, favicon, specPath, servers) is escaped for HTML, and objects embedded in inline scripts are serialized with <, >, &, U+2028 and U+2029 escaped, so a value containing </script> cannot break out of the page. favicon and specPath additionally reject javascript: and other non-http(s) schemes. favicon also accepts inline raster data URLs (data:image/png, data:image/jpeg, data:image/gif, data:image/webp). SVG data URLs are rejected, even though the value is attribute-escaped; use a local or HTTPS SVG/icon URL if you need one. specPath must be a local path or an http(s) URL.

Programmatic helpers

Generate the document without mounting the middleware:

import { generateSpec } from "setupdocs";
import fs from "node:fs";

const spec = generateSpec(app, { title: "My API" });
fs.writeFileSync("openapi.json", JSON.stringify(spec, null, 2));

List the marked routes:

import { discoverRoutes } from "setupdocs";

const routes = discoverRoutes(app);
// [{ method: "GET", path: "/users", openApiPath: "/users", ... }]

Helpers on the instance:

swag.generateSpec(app);
swag.discoverRoutes(app);

All helpers consider only marked routes.

Zod schemas (optional)

Zod support is an optional peer dependency. The core setupdocs entry point never imports Zod, so you only need to install it if you use the adapter:

npm install setupdocs zod

Supported Zod version: ^4.6.7 (Zod 4.6.7 or newer, below 5). Import the adapter from its own subpath:

import { z } from "zod";
import { SetSwagger, response } from "setupdocs";
import {
  zodToOpenAPI,
  registerZodSchemas,
  getRegisteredZodSchemas,
} from "setupdocs/zod";

const User = z.object({
  id: z.number().int(),
  name: z.string(),
  email: z.email(),
});

const refs = registerZodSchemas({ User });
// Component names must match OpenAPI 3.0's ^[A-Za-z0-9._-]+$ pattern.

const swag = SetSwagger({
  components: { schemas: getRegisteredZodSchemas() },
});

app.use(swag);

app.get(
  "/users/:id",
  swag.route({
    responses: {
      200: {
        description: "A user",
        content: { "application/json": { schema: refs.User } },
      },
    },
  }),
  handler,
);

// Or convert a single schema inline:
const userSchema = zodToOpenAPI(User);

The adapter uses Zod's public z.toJSONSchema() API with target: "openapi-3.0", so output always matches the document version (OpenAPI 3.0.3, including nullable: true rather than 3.1 type: [...]). There is no separate openapi option.

zodToOpenAPI(schema, options) accepts:

| Option | Purpose | | --- | --- | | title | Title for the generated schema | | description | Description for the generated schema | | io | "output" (default) or "input"; controls how transforms, coercions, and defaults are described |

Dates become string / date-time, bigints become integer / int64, and sets become arrays with uniqueItems: true. z.record(z.string(), valueSchema) becomes an object with additionalProperties.

Zod constructs that OpenAPI 3.0 cannot describe accurately throw a ZodSchemaError instead of silently producing an empty or unconstrained schema. This includes functions, symbols, NaN, void, undefined, custom schemas, the output side of transforms, and z.map() (use z.record() for string-keyed maps). The error names the offending property path and suggests a supported replacement. z.any() and z.unknown() intentionally remain unconstrained ({}) because "no constraints" is an accurate representation. Use io: "input" when a transform's input shape is the meaningful one.

Recursive schemas need a component name so their references stay inside #/components/schemas. Register them with zodToOpenAPIRef(schema, "Name") or registerZodSchemas({ Name: schema }); calling zodToOpenAPI() on an unnamed recursive schema throws a ZodSchemaError explaining this instead of emitting an invalid $ref: "#".

How it works

swag.route(metadata?) returns ordinary Express middleware carrying a hidden symbol marker. SetupDocs walks Express's router stack and keeps only route layers whose handler chain contains that marker. Express supplies the path and method.

This relies on Express's internal _router (Express 4) or router (Express 5) property, which is not a guaranteed public API. The implementation covers the usual Express 4/5 layouts; a future major version could require an adapter. In particular, Express 5 does not retain non-root router mount paths, so marked routes inside app.use("/prefix", router) are skipped with a warning (see Nested routers above).

Current scope

  • Explicit swag.route() markers only; there is no auto-discovery mode.
  • Zod 4 schemas are supported through the optional setupdocs/zod subpath; the core package does not require Zod.
  • Schemas and detailed responses are copied from metadata verbatim; no inference from handlers.
  • Express 4 and Express 5 are the target platforms.

Development

npm install
npm run typecheck  # TypeScript, no emit
npm run build      # ESM + CommonJS + TypeScript declarations
npm test           # builds, then runs the test suite
npm run check      # typecheck and full build/test suite
npm run example    # examples/express-app.js on port 3000
npm run demo       # richer demo on port 3000

Pull requests and pushes to main or master run the clean-install, typecheck, build, test, dependency audit, and package dry-run checks on Node.js 18, 20, and 22. The package has no separate style linter configured; npm run check is the release validation command and prepublishOnly runs it before publication.

The test suite has these environment expectations:

  • HTTP tests bind to 127.0.0.1 on an ephemeral port (no external network access is required, and nothing listens on a public interface).
  • npm test needs the dist/ directory to be writable because it runs the build first.
  • test/package.test.mjs shells out to npm pack --dry-run and imports the package by its own name, so npm must be on PATH and the project directory must be readable by the current user. It does not publish or upload anything.
  • OpenAPI validation is performed with @apidevtools/swagger-parser, which is installed as a dev dependency.

After starting an example, open http://localhost:3000/docs.

Development dependency override

package.json pins the transitive esbuild development dependency to 0.27.2 through overrides. tsup 8.5.1 accepts esbuild@^0.27.0, but esbuild versions 0.27.3 through 0.28.0 are affected by GHSA-g7r4-m6w7-qqqr, a low-severity local development-server issue on Windows. Version 0.27.2 is the latest unaffected release inside tsup's supported range. tsup 9 requires Node.js 22.18 or newer, while SetupDocs still supports Node.js 18, so moving to tsup 9 would break the supported development toolchain. Revisit this override when tsup 8.x updates its esbuild range or when the minimum Node.js version is raised. The override affects only this project's development install; npm does not apply a dependency's overrides field to consumers installing SetupDocs.

License

MIT