Swagger Express Fixed Middleware

raw JSON →
1.0.2 verified Thu Apr 23 auth: no javascript maintenance

swagger-express-fixed is a specialized fork of the legacy apigee-127/swagger-express library, designed to provide critical compatibility fixes for Node.js environments beyond version 10. The package, currently at version 1.0.2, aims to enable older Express applications that rely on the original `swagger-express` to run on modern Node.js runtimes without necessitating a complete rewrite to contemporary OpenAPI tooling like `swagger-ui-express` and `swagger-jsdoc`. It achieves this by integrating an updated `swagger-node-runner` (or its fixed variant), which now utilizes the `Sway` engine for robust API validation. This fork prioritizes stability and bug fixes over new feature development, making its release cadence infrequent and focused on critical maintenance for existing projects.

error TypeError: Cannot read property 'swaggerUi' of undefined
cause The original `swagger-express` package or an unpatched `swagger-node-runner` is being used with a Node.js version greater than 10, leading to module loading or dependency resolution failures.
fix
Ensure you are using swagger-express-fixed and that its internal dependencies are correctly resolved. Verify package-lock.json and node_modules structure. If this error persists, consider a clean npm install.
error YAMLSemanticError: (in ..., at line x, column y)
cause Syntax error, incorrect indentation, or invalid schema in the provided Swagger/OpenAPI YAML definition file. YAML is sensitive to whitespace and structure.
fix
Carefully review the specified line and column in your swagger.yaml file for syntax errors, improper indentation, or schema violations. Use an OpenAPI/Swagger editor or linter (e.g., swagger-cli validate) to validate your YAML file.
error Error: The 'apis' array is empty. No files were found matching the provided paths.
cause The `apis` configuration in `swagger-express-fixed` (or its underlying `swagger-node-runner`) does not correctly point to your API definition files (e.g., `swagger.yaml` or `controller` files).
fix
Verify the apis array in your config object (or swagger.yaml) contains the correct relative or absolute paths to your API definition files. Ensure file names and extensions match and are accessible from the appRoot.
error Failed to load API definition. Possible cross-origin (CORS) issue?
cause The Swagger UI, often served on a different path or port than the API, is blocked by browser security policies from fetching the API definition JSON due to a missing or misconfigured CORS header.
fix
Implement a CORS middleware in your Express application that explicitly allows requests from the origin where your Swagger UI is hosted. This might involve setting Access-Control-Allow-Origin headers. Ensure the swaggerURL and basePath are correctly configured in swagger.init options.
breaking The original `apigee-127/swagger-express` is known to be incompatible with Node.js versions greater than 10. This `_fixed` fork specifically addresses these runtime issues. Attempting to use the unpatched version on newer Node.js runtimes will result in crashes or unexpected behavior.
fix Migrate to `swagger-express-fixed` for Node.js > 10 compatibility, or update to more modern OpenAPI documentation tools like `swagger-ui-express` and `swagger-jsdoc`.
breaking The underlying `swagger-node-runner` dependency, used by this package, transitioned to a 'Sway-based release' in version `0.6.0`. This change introduces a new validation engine, which might alter API behavior or strictness compared to older versions, potentially breaking existing API contracts if not carefully reviewed.
fix Thoroughly test API endpoints after upgrading, paying close attention to request validation, response generation, and error handling for any regressions or stricter enforcement of the OpenAPI specification. Refer to `swagger-node-runner` release notes.
gotcha Cross-Origin Resource Sharing (CORS) issues are common when serving Swagger UI, especially if the API and the UI are on different origins, or if the API definitions themselves have CORS-related misconfigurations. This can lead to the Swagger UI failing to load API definitions or make requests.
fix Ensure your Express application is configured with appropriate CORS middleware (e.g., `cors` package) to allow requests from the Swagger UI origin. Verify `basePath` in your Swagger definition matches your application's deployment path.
gotcha This package is primarily built for Swagger/OpenAPI 2.0 specifications. While OpenAPI 3.x is the current standard, using a 3.x definition directly with this tool might lead to parsing errors or unexpected behavior as it may not fully support the newer specification structure (e.g., `components` object, `requestBody`).
fix Ensure your Swagger/OpenAPI definition adheres to the 2.0 specification for full compatibility. If migrating to OpenAPI 3.x, consider using dedicated 3.x compatible tools like `swagger-ui-express` with `swagger-jsdoc` or `express-openapi`.
npm install swagger-express-fixed
yarn add swagger-express-fixed
pnpm add swagger-express-fixed

Demonstrates how to initialize `swagger-express-fixed` with a basic Express application, loading a Swagger/OpenAPI definition file and setting up the API routes and UI.

const express = require('express');
const path = require('path');
const swagger = require('swagger-express-fixed');

const app = express();
const port = 3000;

const config = {
  appRoot: __dirname, // required for swagger-node-runner
  swaggerFile: path.resolve(__dirname, './api/swagger.yaml') // Path to your API definition
};

/* Example swagger.yaml content (place in ./api/swagger.yaml)
---
swagger: '2.0'
info:
  title: My Express API
  version: '1.0.0'
paths:
  /hello:
    get:
      summary: Returns a greeting
      responses:
        200:
          description: A simple greeting
          schema:
            type: string
*/

swagger.create(config, function(err, swaggerMiddleware) {
  if (err) { throw err; }

  // Add swagger-express-fixed middleware to your Express app
  app.use(swaggerMiddleware.swaggerSecurity({})
  app.use(swaggerMiddleware.swaggerMetadata());
  app.use(swaggerMiddleware.swaggerValidator());
  app.use(swaggerMiddleware.swaggerRouter({ useStubs: true }));
  app.use(swaggerMiddleware.swaggerUi());

  // Custom error handler (optional)
  app.use(function(err, req, res, next) {
    if (err.statusCode) {
      res.status(err.statusCode).json(err.message);
    } else {
      res.status(500).json('Internal Server Error');
    }
  });

  app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}`);
    console.log(`Swagger UI available at http://localhost:${port}/docs`);
  });
});