{"id":17968,"library":"swagger-express-mw","title":"Swagger Express Middleware","description":"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.","status":"abandoned","version":"0.7.0","language":"javascript","source_language":"en","source_url":"https://github.com/apigee-127/swagger-express","tags":["javascript","swagger","api","apis","connect"],"install":[{"cmd":"npm install swagger-express-mw","lang":"bash","label":"npm"},{"cmd":"yarn add swagger-express-mw","lang":"bash","label":"yarn"},{"cmd":"pnpm add swagger-express-mw","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core dependency that handles Swagger loading, routing, and validation. swagger-express-mw is a wrapper around it.","package":"swagger-node-runner","optional":false}],"imports":[{"note":"This package is CommonJS-only. There is no ESM export. The default export is a function to create the middleware.","wrong":"import swaggerExpressMw from 'swagger-express-mw';","symbol":"swaggerExpressMw","correct":"const swaggerExpressMw = require('swagger-express-mw');"},{"note":"The `create` function is a property of the module's default export, not a named export. It is the primary entry point for initializing the middleware.","wrong":"const { create } = require('swagger-express-mw');","symbol":"create","correct":"swaggerExpressMw.create(config, function(err, swaggerExpress) { /* ... */ });"}],"quickstart":{"code":"const express = require('express');\nconst swaggerExpressMw = require('swagger-express-mw');\nconst path = require('path');\nconst fs = require('fs');\n\n// Create an Express app\nconst app = express();\n\n// Define your Swagger/OpenAPI 2.0 configuration\nconst config = {\n  appRoot: __dirname, // required config\n  // You might place your swagger.yaml in './api/swagger/swagger.yaml' or specify a path.\n  // For this example, we'll create a dummy one.\n  swaggerFile: path.resolve(__dirname, 'api', 'swagger', 'swagger.yaml')\n};\n\n// Ensure the directory for the swagger file exists\nconst swaggerDir = path.dirname(config.swaggerFile);\nif (!fs.existsSync(swaggerDir)) {\n  fs.mkdirSync(swaggerDir, { recursive: true });\n}\n\n// Write a basic Swagger 2.0 YAML file for demonstration\nconst swaggerYamlContent = `\nswagger: \"2.0\"\ninfo:\n  version: \"1.0.0\"\n  title: \"Hello API\"\npaths:\n  /hello:\n    get:\n      description: \"Returns 'Hello {name}' to the caller\"\n      parameters:\n        - name: \"name\"\n          in: \"query\"\n          description: \"Name to greet\"\n          required: false\n          type: \"string\"\n      responses:\n        200:\n          description: \"Success\"\n          schema:\n            type: \"string\"\n`;\nfs.writeFileSync(config.swaggerFile, swaggerYamlContent);\n\n// Initialize swagger-express-mw\nswaggerExpressMw.create(config, function(err, swaggerExpress) {\n  if (err) { throw err; }\n\n  // Install Swagger Express middleware into the Express app\n  swaggerExpress.register(app);\n\n  // Access the Swagger object for runtime configuration or documentation\n  const swaggerObject = swaggerExpress.runner.swagger;\n  console.log('Swagger API Title:', swaggerObject.info.title);\n\n  // Define a simple controller for the /hello path\n  // This would typically be in './api/controllers/hello_controller.js'\n  // and linked via x-swagger-router-controller and operationId in swagger.yaml\n  // For this quickstart, we'll handle it directly.\n  app.get('/hello', (req, res) => {\n    const name = req.query.name || 'Stranger';\n    res.send(`Hello, ${name}!`);\n  });\n\n  // Start the server\n  const port = process.env.PORT || 8000;\n  app.listen(port, () => {\n    console.log(`Server running on http://localhost:${port}`);\n    console.log(`Try: http://localhost:${port}/hello?name=World`);\n    console.log(`Swagger definition available at http://localhost:${port}/swagger`);\n  });\n});\n","lang":"javascript","description":"This quickstart initializes an Express application with `swagger-express-mw`, dynamically creating a basic Swagger 2.0 YAML definition and registering the middleware. It demonstrates how to set up a simple API endpoint defined in Swagger and exposes the Swagger definition."},"warnings":[{"fix":"Consult the `swagger-node-runner@0.6.0` release notes for detailed upgrade instructions, including potential changes to configuration and controller implementations.","message":"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.","severity":"breaking","affected_versions":">=0.6.0"},{"fix":"For new projects or existing projects requiring OpenAPI 3.x support, consider modern alternatives like `express-openapi`, `swagger-express-middleware`, or `nestjs/swagger`. For critical security updates or Node.js compatibility, evaluate community-maintained forks like `swagger-node-runner-fixed` or `swagger-express-mw-fork`, but proceed with caution due to their limited maintenance.","message":"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.","severity":"breaking","affected_versions":">=0.7.0"},{"fix":"Update vulnerable transitive dependencies using `npm audit fix --force` or `yarn resolutions` if possible, but be aware that this may lead to breakage given the unmaintained nature of the primary package. The most robust fix is to migrate to a actively maintained OpenAPI middleware solution.","message":"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.","severity":"gotcha","affected_versions":">=0.1.0"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Ensure your Swagger definition file is correctly named (`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.","cause":"The middleware could not locate the primary Swagger definition file. By default, it looks for `swagger.yaml` or `swagger.json` within an `api/swagger` directory relative to the `appRoot` configuration.","error":"Error: Can't find 'swagger.yaml' or 'swagger.json' in '<path>/api/swagger'"},{"fix":"Check the `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.","cause":"This usually indicates that `swaggerExpressMw.create()` encountered an error or did not complete successfully, resulting in `swaggerExpress` being undefined or null, preventing the call to `swaggerExpress.register(app)`.","error":"TypeError: Cannot read properties of undefined (reading 'register')"},{"fix":"Carefully review your `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.","cause":"The `swagger.yaml` file contains syntax errors, specifically incorrect indentation which is critical for YAML parsing.","error":"YAMLParseError: bad indentation of a mapping entry"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}