or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-swagger-ui-express

Express middleware to serve auto-generated Swagger UI documentation for REST APIs

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/swagger-ui-express@5.0.x

To install, run

npx @tessl/cli install tessl/npm-swagger-ui-express@5.0.0

index.mddocs/

Swagger UI Express

Swagger UI Express provides Express middleware to serve auto-generated Swagger UI documentation for REST APIs. It integrates swagger-ui-dist with Express.js applications, allowing developers to serve interactive API documentation directly from their Express servers based on swagger.json files.

Package Information

  • Package Name: swagger-ui-express
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install swagger-ui-express

Core Imports

const swaggerUi = require('swagger-ui-express');

For ES6 modules:

import swaggerUi from 'swagger-ui-express';

Basic Usage

const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');

const app = express();

// Serve Swagger UI at /api-docs
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));

app.listen(3000);

Architecture

Swagger UI Express consists of several key components:

  • Static Asset Middleware: Serves Swagger UI static files (CSS, JS, images) from swagger-ui-dist package
  • HTML Generation: Creates customizable HTML pages that initialize Swagger UI with your API documentation
  • Dynamic Document Support: Supports loading swagger documents from various sources (inline, URL, dynamic)
  • Customization System: Provides extensive customization options for styling, behavior, and authentication

Capabilities

Core Middleware Functions

Primary functions for serving Swagger UI documentation with Express applications.

/**
 * Creates Express middleware to serve Swagger UI interface
 * @param {Object|null} swaggerDoc - Swagger document object (or null for URL loading)
 * @param {Object|boolean} opts - Configuration options object or legacy explorer boolean
 * @param {Object} [options] - Legacy parameter for swagger options (deprecated)
 * @param {string} [customCss] - Legacy parameter for custom CSS (deprecated)
 * @param {string} [customfavIcon] - Legacy parameter for custom favicon (deprecated)
 * @param {string} [swaggerUrl] - Legacy parameter for swagger URL (deprecated)
 * @param {string} [customSiteTitle] - Legacy parameter for custom site title (deprecated)
 * @returns {Function} Express middleware function (req, res) => void
 */
function setup(swaggerDoc, opts, options, customCss, customfavIcon, swaggerUrl, customSiteTitle);

/**
 * Pre-configured middleware array for serving Swagger UI static assets
 * Static composition: [swaggerInitFn, swaggerAssetMiddleware()]
 * @type {Array<Function>} Array of Express middleware functions
 */
const serve;

/**
 * Creates middleware array with custom static file serving options
 * @param {Object} [options] - Express static options (redirect, cacheControl, etc.)
 * @returns {Array<Function>} Array of Express middleware functions [swaggerInitFn, swaggerAssetMiddleware(options)]
 */
function serveWithOptions(options);

/**
 * Creates middleware array for serving files with dynamic swagger document support
 * @param {Object|null} swaggerDoc - Swagger document object or null
 * @param {Object} [opts] - Configuration options
 * @returns {Array<Function>} Array of Express middleware functions [swaggerInitWithOpts, swaggerAssetMiddleware()]
 */
function serveFiles(swaggerDoc, opts);

/**
 * Generates HTML string for Swagger UI interface
 * @param {Object|null} swaggerDoc - Swagger document object or null
 * @param {Object|boolean} [opts] - Configuration options or legacy explorer boolean
 * @param {Object} [options] - Legacy swagger options (deprecated)
 * @param {string} [customCss] - Custom CSS styles
 * @param {string} [customfavIcon] - Custom favicon URL
 * @param {string} [swaggerUrl] - URL to swagger document
 * @param {string} [customSiteTitle] - Page title
 * @param {string} [_htmlTplString] - Custom HTML template override
 * @param {string} [_jsTplString] - Custom JavaScript template override
 * @returns {string} Complete HTML document string
 */
function generateHTML(swaggerDoc, opts, options, customCss, customfavIcon, swaggerUrl, customSiteTitle, _htmlTplString, _jsTplString);

Configuration Options

Configuration object structure for the opts parameter in setup functions.

/**
 * Configuration options object for setup functions
 */
interface SetupOptions {
  /** Show/hide Swagger Explorer bar (enables dropdown for multiple specs) */
  explorer?: boolean;
  /** Options passed directly to Swagger UI client */
  swaggerOptions?: SwaggerUIOptions;
  /** Custom CSS styles as string */
  customCss?: string;
  /** URL or array of URLs to external CSS files */
  customCssUrl?: string | string[];
  /** URL or array of URLs to external JavaScript files */
  customJs?: string | string[];
  /** Inline JavaScript code as string or array of strings */
  customJsStr?: string | string[];
  /** Custom favicon URL */
  customfavIcon?: string;
  /** Custom page title (default: "Swagger UI") */
  customSiteTitle?: string;
  /** Custom robots meta tag content */
  customRobots?: string;
  /** URL to swagger document (legacy, use swaggerOptions.url instead) */
  swaggerUrl?: string;
  /** Array of multiple swagger documents for dropdown (legacy, use swaggerOptions.urls instead) */
  swaggerUrls?: SwaggerUrlConfig[];
}

/**
 * Swagger UI client configuration options
 * Passed directly to SwaggerUIBundle constructor
 */
interface SwaggerUIOptions {
  /** URL to swagger specification */
  url?: string;
  /** Array of multiple swagger specifications for dropdown */
  urls?: SwaggerUrlConfig[];
  /** Swagger validator URL or null to disable validation */
  validatorUrl?: string | null;
  /** Default expansion state: 'list', 'full', or 'none' */
  docExpansion?: 'list' | 'full' | 'none';
  /** Sort operations: 'alpha', 'method', or custom function */
  operationsSorter?: 'alpha' | 'method' | Function;
  /** Enable deep linking to operations and tags */
  deepLinking?: boolean;
  /** Pre-authorize API key configuration */
  preauthorizeApiKey?: {
    authDefinitionKey: string;
    apiKeyValue: string;
  };
  /** OAuth configuration for authentication */
  oauth?: {
    clientId: string;
    clientSecret?: string;
    realm?: string;
    appName?: string;
    scopeSeparator?: string;
    additionalQueryStringParams?: Object;
  };
  /** Authorization action configuration */
  authAction?: Object;
  /** Custom options merged into SwaggerUIBundle configuration */
  [key: string]: any;
}

/**
 * Configuration for multiple swagger specifications
 */
interface SwaggerUrlConfig {
  /** Display name for the specification in dropdown */
  name: string;
  /** URL to the swagger specification */
  url: string;
}

Usage Patterns

Basic Setup with Document:

const express = require('express');
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');

const app = express();
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));

Router Integration:

const router = require('express').Router();
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./swagger.json');

router.use('/api-docs', swaggerUi.serve);
router.get('/api-docs', swaggerUi.setup(swaggerDocument));

Load Swagger from URL:

const options = {
  swaggerOptions: {
    url: 'http://petstore.swagger.io/v2/swagger.json'
  }
};

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(null, options));

Multiple Swagger Documents:

const options = {
  explorer: true,
  swaggerOptions: {
    urls: [
      { url: 'http://petstore.swagger.io/v2/swagger.json', name: 'Spec1' },
      { url: 'http://petstore.swagger.io/v2/swagger.json', name: 'Spec2' }
    ]
  }
};

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(null, options));

Dynamic Document Modification:

app.use('/api-docs', function(req, res, next){
  swaggerDocument.host = req.get('host');
  req.swaggerDoc = swaggerDocument;
  next();
}, swaggerUi.serveFiles(), swaggerUi.setup());

Custom Styling:

const options = {
  customCss: '.swagger-ui .topbar { display: none }',
  customCssUrl: '/custom.css',
  customJs: '/custom.js',
  customJsStr: 'console.log("Custom JS loaded")',
  customSiteTitle: 'My API Documentation'
};

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument, options));

Multiple Instances:

// Use serveFiles for multiple instances
app.use('/api-docs-one', swaggerUi.serveFiles(docOne, options), swaggerUi.setup(docOne));
app.use('/api-docs-two', swaggerUi.serveFiles(docTwo, options), swaggerUi.setup(docTwo));

Authentication Configuration:

const options = {
  swaggerOptions: {
    preauthorizeApiKey: {
      authDefinitionKey: 'api_key',
      apiKeyValue: 'Bearer your-token-here'
    },
    oauth: {
      clientId: 'your-client-id',
      clientSecret: 'your-client-secret',
      realm: 'your-realm',
      appName: 'your-app-name'
    }
  }
};

Static File Options:

// Custom static file serving options
app.use('/api-docs', swaggerUi.serveWithOptions({ 
  redirect: false, 
  cacheControl: false 
}));

Internal Utility Functions

The package includes several internal utility functions that affect behavior:

/**
 * Removes query parameters from URL string
 * @param {string} q - URL string with optional query parameters
 * @returns {string} URL without query parameters
 */
function trimQuery(q);

/**
 * Converts URL to external script tag HTML
 * @param {string} url - JavaScript file URL
 * @returns {string} HTML script tag
 */
function toExternalScriptTag(url);

/**
 * Converts JavaScript code to inline script tag HTML
 * @param {string} jsCode - JavaScript code string
 * @returns {string} HTML script tag with inline code
 */
function toInlineScriptTag(jsCode);

/**
 * Converts URL to external stylesheet link tag HTML
 * @param {string} url - CSS file URL
 * @returns {string} HTML link tag
 */
function toExternalStylesheetTag(url);

/**
 * Converts string or array to HTML tags using provided converter function
 * @param {string|string[]} customCode - Code or URLs to convert
 * @param {Function} toScript - Converter function (toExternalScriptTag or toInlineScriptTag)
 * @returns {string} Combined HTML tags
 */
function toTags(customCode, toScript);

/**
 * Serializes object to JavaScript variable declaration, preserving functions
 * @param {Object} obj - Object to serialize
 * @param {string} [prop] - Optional property name
 * @returns {string} JavaScript variable declaration string
 */
function stringify(obj, prop);

Internal Components and Templates

The package includes internal template strings and constants that enable customization:

/**
 * Default favicon HTML string used when no custom favicon is provided
 */
const favIconHtml: string;

/**
 * HTML template string with placeholders for customization
 * Placeholders: robotsMetaString, title, favIconString, customJs, customJsStr, customCssUrl, customCss
 */
const htmlTplString: string;

/**
 * JavaScript initialization template string with placeholder for SwaggerUI options
 * Placeholder: swaggerOptions
 */
const jsTplString: string;

Template Placeholders:

HTML Template (htmlTplString):

  • <% robotsMetaString %> - Robots meta tag content
  • <% title %> - Page title
  • <% favIconString %> - Favicon HTML
  • <% customJs %> - External JavaScript script tags
  • <% customJsStr %> - Inline JavaScript code
  • <% customCssUrl %> - External CSS link tags
  • <% customCss %> - Inline CSS styles

JavaScript Template (jsTplString):

  • <% swaggerOptions %> - Serialized SwaggerUI configuration object

Error Handling

The middleware automatically handles these cases:

Route Protection:

  • Blocks access to /package.json endpoint (returns 404 status)
  • Prevents exposure of sensitive package information

Content Serving:

  • Serves /swagger-ui-init.js with proper application/javascript content-type
  • Automatically generates initialization script with current configuration
  • Falls through to next middleware for unhandled requests

Template Processing:

  • Safely processes template placeholders in HTML and JavaScript templates
  • Handles missing or invalid configuration gracefully
  • Preserves function objects during JSON serialization using custom stringify

Request Object Extensions

When using dynamic documents, the middleware expects:

/**
 * Request object extension for dynamic swagger documents
 */
interface Request {
  /** Swagger document object to render dynamically (overrides static document) */
  swaggerDoc?: Object;
}

Dependencies

  • express: Peer dependency (>=4.0.0 || >=5.0.0-beta) - Express framework
  • swagger-ui-dist: Direct dependency (>=5.0.0) - Provides Swagger UI static assets (CSS, JS, images)