# swagger-jsdoc: Generate OpenAPI from JSDoc annotations

> swagger-jsdoc turns JSDoc annotations and YAML files into OpenAPI, Swagger, or AsyncAPI specifications. It fits JavaScript services that keep API definitions beside route code, with Node.js 20 as its minimum runtime.

**Surnet/swagger-jsdoc** — Generates swagger/openapi specification based on jsDoc comments and YAML files.

- Repository: https://github.com/Surnet/swagger-jsdoc
- Stars: 1,788 · Forks: 230
- Language: JavaScript
- License: MIT
- Published: 2026-10-16 · Updated: 2026-10-16 · Language: en
- Canonical page: https://hysenlabs.com/projects/surnet-swagger-jsdoc

## Where swagger-jsdoc fits in a JavaScript API

swagger-jsdoc addresses a specific documentation problem: route information expressed in source comments can be converted into a machine-readable API specification. Its target users are developers working in JavaScript who want an OpenAPI document generated from files such as route modules and event handlers. The package supports OpenAPI 3.x, Swagger 2, and AsyncAPI 2.0, so it can document HTTP APIs and event-driven interfaces.

The repository includes examples for a basic application, event-driven APIs, extensions, and YAML anchors and aliases. That layout indicates support for more than one source format. JSDoc blocks containing `@openapi` or `@swagger` can define paths directly beside implementation comments. YAML files can also contribute specification content, including YAML structures that use reusable anchors and aliases.

The library is a code-adjacent documentation tool, not a documentation host. It returns a specification object but does not present a browsable API interface, publish endpoints, or host documentation. That boundary makes it suitable as a build-time or application-start component. A team still needs a consumer for the generated document if it wants interactive documentation or validation in another tool.

The model is most natural for services in which comments and endpoints change together. A change that adds or alters a route can also update its annotation. The trade-off is that the resulting contract depends on contributors maintaining both the implementation and schema content in a valid, consistent structure.

## How swagger-jsdoc turns comments into an API contract

The basic mechanism is visible in the README example. A JSDoc comment marks an operation with `@openapi`, then supplies a path and an HTTP method. Under the `get` key, the annotation describes the operation and its responses. Its structure follows the shape of an OpenAPI document rather than a separate JavaScript routing DSL.

The caller passes two principal configuration values. `definition` supplies top-level document information such as `openapi` and `info`, while `apis` contains glob patterns identifying files with annotations. The package locates those files, reads their JSDoc content, parses the annotation content, and combines the result with the supplied definition in `openapiSpecification`.

The dependency list clarifies several parts of that process. `glob` locates matching source files, `doctrine` parses JavaScript comments, and `yaml` handles YAML input. `lodash.mergewith` participates in assembling documentation fragments. Validation is handled by `@apidevtools/swagger-parser`. The README describes the returned value as a swagger tools-compatible, validated specification, although the amount of schema validation should be assessed against the exact annotations used by a project.

This assembly model keeps the general document identity separate from endpoint annotations. The `definition` establishes metadata such as the API title and version, while matching files contribute operational details. The repository's example directories also suggest that extensions and YAML composition are supported concerns, not merely incidental formatting.

## Installing swagger-jsdoc and generating a first specification

The repository requires Node.js 20.x or higher, and the package is published as CommonJS for version 6. The documented installation command adds it as an npm dependency and saves the entry in `package.json` and the lockfile managed by npm.

Run this from the project that owns the API documentation:

```bash
npm install swagger-jsdoc --save
```

A Yarn-based project can use the alternative installation documented in the README:

```bash
yarn add swagger-jsdoc
```

The first real use requires one annotated route file and a CommonJS script that loads `swagger-jsdoc`. In the example configuration below, the `apis` glob searches for annotated route files. The returned `openapiSpecification` is the generated specification object.

```javascript
const swaggerJsdoc = require('swagger-jsdoc');

const options = {
  definition: {
    openapi: '3.0.0',
    info: {
      title: 'Hello World',
      version: '1.0.0',
    },
  },
  apis: ['./src/routes*.js'],
};

const openapiSpecification = swaggerJsdoc(options);
```

The corresponding route annotation can remain next to the handler. This block describes `GET /` and declares a `200` response:

```javascript
/**
 * @openapi
 * /:
 *   get:
 *     description: Welcome to swagger-jsdoc!
 *     responses:
 *       200:
 *         description: Returns a mysterious string.
 */
app.get('/', (req, res) => {
  res.send('Hello World!');
});
```

After calling `swaggerJsdoc(options)`, the reader should inspect `openapiSpecification` and confirm that the configured `info` and annotated `GET /` operation appear in the returned object. The README does not document a required HTTP endpoint or a required output file, so serialization and serving remain application responsibilities.

## Validation behavior and its CI trade-off

The most important operational choice in the documented configuration is `failOnErrors`. By default, the README says swagger-jsdoc tries to parse documents as far as it can. Setting `failOnErrors` to `true` instructs it to throw when parsing errors occur. This gives a project a direct way to verify its annotations during a unit test or another build check.

The option changes failure handling rather than annotation syntax:

```javascript
const swaggerJsdoc = require('swagger-jsdoc');

const options = {
  failOnErrors: true,
  definition: {
    openapi: '3.0.0',
    info: {
      title: 'Hello World',
      version: '1.0.0',
    },
  },
  apis: ['./src/routes*.js'],
};

const openapiSpecification = swaggerJsdoc(options);
```

With this configuration, a parsing error should stop execution rather than allow an incomplete result to continue unnoticed. That behavior is useful when the specification is an enforced interface artifact. It also means a malformed annotation can break a test or application startup instead of producing a partial object for later inspection.

The repository defines `npm test` as a combined script that runs its JavaScript tests and lint task through `npm-run-all2`. The README does not provide a dedicated swagger-jsdoc CLI validation command, so users should not infer one from the package's `swagger-jsdoc` binary entry. The concrete CI integration point shown here is a JavaScript call with `failOnErrors: true`.

## JSDoc annotations versus independently authored specifications

A real alternative is to maintain an OpenAPI YAML or JSON file separately and load it directly in documentation, testing, or client-generation tooling. That approach keeps the API contract in a dedicated document instead of deriving it from JSDoc blocks embedded in JavaScript files.

The difference is where changes are made. swagger-jsdoc uses source comments as operation inputs, then combines them with a JavaScript `definition` object. A standalone specification has one explicit document that can be reviewed and validated independently of route implementation. It does not require contributors to keep comment annotations and implementation files synchronized.

The alternative also changes the tooling boundary. swagger-jsdoc is a CommonJS Node.js package that resolves file patterns and processes comments, so it is convenient when documentation generation already runs in a JavaScript service or build. A separate document may be simpler when a non-JavaScript client team owns the contract, when annotations become awkward for complex reusable schemas, or when the document needs to be consumed outside the Node.js project.

Neither approach automatically guarantees contract accuracy. swagger-jsdoc can expose malformed annotations through validation, while a standalone file can still describe routes incorrectly. The practical distinction is ownership and composition. Choose swagger-jsdoc when colocated annotations are part of the project's documentation convention. Choose a standalone OpenAPI file when the contract must remain independent of JavaScript source layout.

## Release activity, runtime requirements, and package boundaries

The repository is not archived, and its last push was on 2026-10-13. The listed releases include `v6.3.0` on 2026-05-22, followed by `v6.2.1` on 2022-04-18 and `v6.2.0` on 2022-04-02. The README states that Node.js 20.x or higher is required and that version 6 is published in the CommonJS module system.

The `package.json` entry is `6.3.0`, while the repository documentation also links to version-specific documentation for 7.x, 6.x, and 5.x. That distinction matters when selecting examples: the installation and usage examples in this repository describe the CommonJS v6 interface, so copying an example written for another module system could produce a different integration result.

The package declares `swagger-jsdoc` as both its main package and a binary. The documented tutorial, however, uses the JavaScript API through `require('swagger-jsdoc')`; it does not explain a CLI workflow. The package also declares dependencies for comment parsing, YAML processing, glob expansion, merging, command-line parsing, and specification parsing. Consumers therefore need to account for a Node.js dependency tree even when they only call the documented generator.

The MIT license permits use under its terms, but teams must read the repository's `LICENSE` file for the complete obligations. The README does not document upgrade procedures, migration guidance, rollback steps, or compatibility guarantees between versions. The release list and package metadata establish available versions, but they do not replace a project-specific check of annotation output before upgrading.

## Conclusion

swagger-jsdoc is a practical choice for Node.js teams whose API documentation belongs beside route implementations, especially when those teams want one annotated source tree. It is less suitable for services documented independently, codebases below Node.js 20,. Evaluate it first by converting a representative route file with `failOnErrors` enabled and confirming that the generated document matches the API contract used by clients.

## FAQ

### What does swagger-jsdoc generate?

swagger-jsdoc reads JSDoc annotations and YAML files and generates an OpenAPI, Swagger, or AsyncAPI specification. The README shows an `@openapi` block contributing a `GET /` operation to the returned specification.

### What Node.js version does swagger-jsdoc v6 require?

The README requires Node.js 20.x or higher. Version 6 is published in the CommonJS module system.

### How can swagger-jsdoc fail on parsing errors?

Set `failOnErrors: true` in the options object. The README states that this causes an error to be thrown when parsing errors occur instead of continuing with the default best-effort behavior.

## Sources

- [Issues](https://github.com/Surnet/swagger-jsdoc/issues)
- [License: MIT](https://github.com/Surnet/swagger-jsdoc/blob/master/LICENSE)
- [README](https://github.com/Surnet/swagger-jsdoc/blob/master/README.md)
- [Releases](https://github.com/Surnet/swagger-jsdoc/releases)
- [Surnet/swagger-jsdoc on GitHub](https://github.com/Surnet/swagger-jsdoc)

---

Hysen Labs editorial analysis, written from the project's own repository and release notes. Cite the canonical page: https://hysenlabs.com/projects/surnet-swagger-jsdoc
