Swagger Express Middleware
raw JSON →swagger-express-mw is an abandoned CommonJS middleware for integrating Swagger (OpenAPI 2.0) definitions with Express applications. It functions primarily as a wrapper around the `swagger-node-runner` package, handling the loading and application of Swagger definitions to an Express server. The package's current stable version is 0.7.0, released in January 2017. Both `swagger-express-mw` and its core dependency `swagger-node-runner` have not seen active development or releases in over seven years, indicating a lack of maintenance. While it simplifies the setup of Swagger-driven APIs by automating routing and validation based on a YAML or JSON definition, its age means it only supports Swagger 2.0 and is not compatible with modern OpenAPI 3.x specifications. There are several forks like `swagger-express-mw-fork` and `swagger-node-runner-fixed` attempting to address some of the issues or update dependencies for newer Node.js versions.
Common errors
error Error: Can't find 'swagger.yaml' or 'swagger.json' in '<path>/api/swagger' ↓
swagger.yaml or swagger.json) and placed in your_app_root/api/swagger/. Alternatively, specify the swaggerFile property in the configuration object passed to swaggerExpressMw.create() with the absolute path to your definition file. error TypeError: Cannot read properties of undefined (reading 'register') ↓
err callback parameter in swaggerExpressMw.create() for any errors during initialization (e.g., malformed Swagger file, missing dependencies). Ensure all configuration options are valid and that appRoot points to a valid directory. error YAMLParseError: bad indentation of a mapping entry ↓
swagger.yaml file for proper YAML syntax, paying close attention to indentation. Use a YAML linter or editor with YAML validation to identify and correct errors. Warnings
breaking Version 0.6.0 (and consequently 0.7.0 via `swagger-node-runner`) introduced significant breaking changes by migrating to `Sway` for Swagger parsing and validation. Existing projects on 0.5.x or earlier require specific upgrade instructions from `swagger-node-runner`'s release notes. ↓
breaking The package is abandoned and has not received updates since January 2017, making it incompatible with modern Node.js versions (e.g., Node.js 14+) without significant workarounds or use of unmaintained forks. This also means it does not support OpenAPI 3.x specifications. ↓
gotcha Due to its age and lack of maintenance, `swagger-express-mw` (and its dependency `swagger-node-runner`) contains known vulnerabilities in its transitive dependencies, such as `dicer` and `async`, which can lead to Denial of Service or privilege escalation. Relying on this package in production without mitigation poses security risks. ↓
Install
npm install swagger-express-mw yarn add swagger-express-mw pnpm add swagger-express-mw Imports
- swaggerExpressMw wrong
import swaggerExpressMw from 'swagger-express-mw';correctconst swaggerExpressMw = require('swagger-express-mw'); - create wrong
const { create } = require('swagger-express-mw');correctswaggerExpressMw.create(config, function(err, swaggerExpress) { /* ... */ });
Quickstart
const express = require('express');
const swaggerExpressMw = require('swagger-express-mw');
const path = require('path');
const fs = require('fs');
// Create an Express app
const app = express();
// Define your Swagger/OpenAPI 2.0 configuration
const config = {
appRoot: __dirname, // required config
// You might place your swagger.yaml in './api/swagger/swagger.yaml' or specify a path.
// For this example, we'll create a dummy one.
swaggerFile: path.resolve(__dirname, 'api', 'swagger', 'swagger.yaml')
};
// Ensure the directory for the swagger file exists
const swaggerDir = path.dirname(config.swaggerFile);
if (!fs.existsSync(swaggerDir)) {
fs.mkdirSync(swaggerDir, { recursive: true });
}
// Write a basic Swagger 2.0 YAML file for demonstration
const swaggerYamlContent = `
swagger: "2.0"
info:
version: "1.0.0"
title: "Hello API"
paths:
/hello:
get:
description: "Returns 'Hello {name}' to the caller"
parameters:
- name: "name"
in: "query"
description: "Name to greet"
required: false
type: "string"
responses:
200:
description: "Success"
schema:
type: "string"
`;
fs.writeFileSync(config.swaggerFile, swaggerYamlContent);
// Initialize swagger-express-mw
swaggerExpressMw.create(config, function(err, swaggerExpress) {
if (err) { throw err; }
// Install Swagger Express middleware into the Express app
swaggerExpress.register(app);
// Access the Swagger object for runtime configuration or documentation
const swaggerObject = swaggerExpress.runner.swagger;
console.log('Swagger API Title:', swaggerObject.info.title);
// Define a simple controller for the /hello path
// This would typically be in './api/controllers/hello_controller.js'
// and linked via x-swagger-router-controller and operationId in swagger.yaml
// For this quickstart, we'll handle it directly.
app.get('/hello', (req, res) => {
const name = req.query.name || 'Stranger';
res.send(`Hello, ${name}!`);
});
// Start the server
const port = process.env.PORT || 8000;
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`);
console.log(`Try: http://localhost:${port}/hello?name=World`);
console.log(`Swagger definition available at http://localhost:${port}/swagger`);
});
});