or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

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

0

# Swagger UI Express

1

2

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.

3

4

## Package Information

5

6

- **Package Name**: swagger-ui-express

7

- **Package Type**: npm

8

- **Language**: JavaScript

9

- **Installation**: `npm install swagger-ui-express`

10

11

## Core Imports

12

13

```javascript

14

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

15

```

16

17

For ES6 modules:

18

19

```javascript

20

import swaggerUi from 'swagger-ui-express';

21

```

22

23

## Basic Usage

24

25

```javascript

26

const express = require('express');

27

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

28

const swaggerDocument = require('./swagger.json');

29

30

const app = express();

31

32

// Serve Swagger UI at /api-docs

33

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

34

35

app.listen(3000);

36

```

37

38

## Architecture

39

40

Swagger UI Express consists of several key components:

41

42

- **Static Asset Middleware**: Serves Swagger UI static files (CSS, JS, images) from swagger-ui-dist package

43

- **HTML Generation**: Creates customizable HTML pages that initialize Swagger UI with your API documentation

44

- **Dynamic Document Support**: Supports loading swagger documents from various sources (inline, URL, dynamic)

45

- **Customization System**: Provides extensive customization options for styling, behavior, and authentication

46

47

## Capabilities

48

49

### Core Middleware Functions

50

51

Primary functions for serving Swagger UI documentation with Express applications.

52

53

```javascript { .api }

54

/**

55

* Creates Express middleware to serve Swagger UI interface

56

* @param {Object|null} swaggerDoc - Swagger document object (or null for URL loading)

57

* @param {Object|boolean} opts - Configuration options object or legacy explorer boolean

58

* @param {Object} [options] - Legacy parameter for swagger options (deprecated)

59

* @param {string} [customCss] - Legacy parameter for custom CSS (deprecated)

60

* @param {string} [customfavIcon] - Legacy parameter for custom favicon (deprecated)

61

* @param {string} [swaggerUrl] - Legacy parameter for swagger URL (deprecated)

62

* @param {string} [customSiteTitle] - Legacy parameter for custom site title (deprecated)

63

* @returns {Function} Express middleware function (req, res) => void

64

*/

65

function setup(swaggerDoc, opts, options, customCss, customfavIcon, swaggerUrl, customSiteTitle);

66

67

/**

68

* Pre-configured middleware array for serving Swagger UI static assets

69

* Static composition: [swaggerInitFn, swaggerAssetMiddleware()]

70

* @type {Array<Function>} Array of Express middleware functions

71

*/

72

const serve;

73

74

/**

75

* Creates middleware array with custom static file serving options

76

* @param {Object} [options] - Express static options (redirect, cacheControl, etc.)

77

* @returns {Array<Function>} Array of Express middleware functions [swaggerInitFn, swaggerAssetMiddleware(options)]

78

*/

79

function serveWithOptions(options);

80

81

/**

82

* Creates middleware array for serving files with dynamic swagger document support

83

* @param {Object|null} swaggerDoc - Swagger document object or null

84

* @param {Object} [opts] - Configuration options

85

* @returns {Array<Function>} Array of Express middleware functions [swaggerInitWithOpts, swaggerAssetMiddleware()]

86

*/

87

function serveFiles(swaggerDoc, opts);

88

89

/**

90

* Generates HTML string for Swagger UI interface

91

* @param {Object|null} swaggerDoc - Swagger document object or null

92

* @param {Object|boolean} [opts] - Configuration options or legacy explorer boolean

93

* @param {Object} [options] - Legacy swagger options (deprecated)

94

* @param {string} [customCss] - Custom CSS styles

95

* @param {string} [customfavIcon] - Custom favicon URL

96

* @param {string} [swaggerUrl] - URL to swagger document

97

* @param {string} [customSiteTitle] - Page title

98

* @param {string} [_htmlTplString] - Custom HTML template override

99

* @param {string} [_jsTplString] - Custom JavaScript template override

100

* @returns {string} Complete HTML document string

101

*/

102

function generateHTML(swaggerDoc, opts, options, customCss, customfavIcon, swaggerUrl, customSiteTitle, _htmlTplString, _jsTplString);

103

```

104

105

### Configuration Options

106

107

Configuration object structure for the `opts` parameter in setup functions.

108

109

```javascript { .api }

110

/**

111

* Configuration options object for setup functions

112

*/

113

interface SetupOptions {

114

/** Show/hide Swagger Explorer bar (enables dropdown for multiple specs) */

115

explorer?: boolean;

116

/** Options passed directly to Swagger UI client */

117

swaggerOptions?: SwaggerUIOptions;

118

/** Custom CSS styles as string */

119

customCss?: string;

120

/** URL or array of URLs to external CSS files */

121

customCssUrl?: string | string[];

122

/** URL or array of URLs to external JavaScript files */

123

customJs?: string | string[];

124

/** Inline JavaScript code as string or array of strings */

125

customJsStr?: string | string[];

126

/** Custom favicon URL */

127

customfavIcon?: string;

128

/** Custom page title (default: "Swagger UI") */

129

customSiteTitle?: string;

130

/** Custom robots meta tag content */

131

customRobots?: string;

132

/** URL to swagger document (legacy, use swaggerOptions.url instead) */

133

swaggerUrl?: string;

134

/** Array of multiple swagger documents for dropdown (legacy, use swaggerOptions.urls instead) */

135

swaggerUrls?: SwaggerUrlConfig[];

136

}

137

138

/**

139

* Swagger UI client configuration options

140

* Passed directly to SwaggerUIBundle constructor

141

*/

142

interface SwaggerUIOptions {

143

/** URL to swagger specification */

144

url?: string;

145

/** Array of multiple swagger specifications for dropdown */

146

urls?: SwaggerUrlConfig[];

147

/** Swagger validator URL or null to disable validation */

148

validatorUrl?: string | null;

149

/** Default expansion state: 'list', 'full', or 'none' */

150

docExpansion?: 'list' | 'full' | 'none';

151

/** Sort operations: 'alpha', 'method', or custom function */

152

operationsSorter?: 'alpha' | 'method' | Function;

153

/** Enable deep linking to operations and tags */

154

deepLinking?: boolean;

155

/** Pre-authorize API key configuration */

156

preauthorizeApiKey?: {

157

authDefinitionKey: string;

158

apiKeyValue: string;

159

};

160

/** OAuth configuration for authentication */

161

oauth?: {

162

clientId: string;

163

clientSecret?: string;

164

realm?: string;

165

appName?: string;

166

scopeSeparator?: string;

167

additionalQueryStringParams?: Object;

168

};

169

/** Authorization action configuration */

170

authAction?: Object;

171

/** Custom options merged into SwaggerUIBundle configuration */

172

[key: string]: any;

173

}

174

175

/**

176

* Configuration for multiple swagger specifications

177

*/

178

interface SwaggerUrlConfig {

179

/** Display name for the specification in dropdown */

180

name: string;

181

/** URL to the swagger specification */

182

url: string;

183

}

184

```

185

186

### Usage Patterns

187

188

**Basic Setup with Document:**

189

```javascript

190

const express = require('express');

191

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

192

const swaggerDocument = require('./swagger.json');

193

194

const app = express();

195

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

196

```

197

198

**Router Integration:**

199

```javascript

200

const router = require('express').Router();

201

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

202

const swaggerDocument = require('./swagger.json');

203

204

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

205

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

206

```

207

208

**Load Swagger from URL:**

209

```javascript

210

const options = {

211

swaggerOptions: {

212

url: 'http://petstore.swagger.io/v2/swagger.json'

213

}

214

};

215

216

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

217

```

218

219

**Multiple Swagger Documents:**

220

```javascript

221

const options = {

222

explorer: true,

223

swaggerOptions: {

224

urls: [

225

{ url: 'http://petstore.swagger.io/v2/swagger.json', name: 'Spec1' },

226

{ url: 'http://petstore.swagger.io/v2/swagger.json', name: 'Spec2' }

227

]

228

}

229

};

230

231

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

232

```

233

234

**Dynamic Document Modification:**

235

```javascript

236

app.use('/api-docs', function(req, res, next){

237

swaggerDocument.host = req.get('host');

238

req.swaggerDoc = swaggerDocument;

239

next();

240

}, swaggerUi.serveFiles(), swaggerUi.setup());

241

```

242

243

**Custom Styling:**

244

```javascript

245

const options = {

246

customCss: '.swagger-ui .topbar { display: none }',

247

customCssUrl: '/custom.css',

248

customJs: '/custom.js',

249

customJsStr: 'console.log("Custom JS loaded")',

250

customSiteTitle: 'My API Documentation'

251

};

252

253

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

254

```

255

256

**Multiple Instances:**

257

```javascript

258

// Use serveFiles for multiple instances

259

app.use('/api-docs-one', swaggerUi.serveFiles(docOne, options), swaggerUi.setup(docOne));

260

app.use('/api-docs-two', swaggerUi.serveFiles(docTwo, options), swaggerUi.setup(docTwo));

261

```

262

263

**Authentication Configuration:**

264

```javascript

265

const options = {

266

swaggerOptions: {

267

preauthorizeApiKey: {

268

authDefinitionKey: 'api_key',

269

apiKeyValue: 'Bearer your-token-here'

270

},

271

oauth: {

272

clientId: 'your-client-id',

273

clientSecret: 'your-client-secret',

274

realm: 'your-realm',

275

appName: 'your-app-name'

276

}

277

}

278

};

279

```

280

281

**Static File Options:**

282

```javascript

283

// Custom static file serving options

284

app.use('/api-docs', swaggerUi.serveWithOptions({

285

redirect: false,

286

cacheControl: false

287

}));

288

```

289

290

### Internal Utility Functions

291

292

The package includes several internal utility functions that affect behavior:

293

294

```javascript { .api }

295

/**

296

* Removes query parameters from URL string

297

* @param {string} q - URL string with optional query parameters

298

* @returns {string} URL without query parameters

299

*/

300

function trimQuery(q);

301

302

/**

303

* Converts URL to external script tag HTML

304

* @param {string} url - JavaScript file URL

305

* @returns {string} HTML script tag

306

*/

307

function toExternalScriptTag(url);

308

309

/**

310

* Converts JavaScript code to inline script tag HTML

311

* @param {string} jsCode - JavaScript code string

312

* @returns {string} HTML script tag with inline code

313

*/

314

function toInlineScriptTag(jsCode);

315

316

/**

317

* Converts URL to external stylesheet link tag HTML

318

* @param {string} url - CSS file URL

319

* @returns {string} HTML link tag

320

*/

321

function toExternalStylesheetTag(url);

322

323

/**

324

* Converts string or array to HTML tags using provided converter function

325

* @param {string|string[]} customCode - Code or URLs to convert

326

* @param {Function} toScript - Converter function (toExternalScriptTag or toInlineScriptTag)

327

* @returns {string} Combined HTML tags

328

*/

329

function toTags(customCode, toScript);

330

331

/**

332

* Serializes object to JavaScript variable declaration, preserving functions

333

* @param {Object} obj - Object to serialize

334

* @param {string} [prop] - Optional property name

335

* @returns {string} JavaScript variable declaration string

336

*/

337

function stringify(obj, prop);

338

```

339

340

### Internal Components and Templates

341

342

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

343

344

```javascript { .api }

345

/**

346

* Default favicon HTML string used when no custom favicon is provided

347

*/

348

const favIconHtml: string;

349

350

/**

351

* HTML template string with placeholders for customization

352

* Placeholders: robotsMetaString, title, favIconString, customJs, customJsStr, customCssUrl, customCss

353

*/

354

const htmlTplString: string;

355

356

/**

357

* JavaScript initialization template string with placeholder for SwaggerUI options

358

* Placeholder: swaggerOptions

359

*/

360

const jsTplString: string;

361

```

362

363

**Template Placeholders:**

364

365

HTML Template (`htmlTplString`):

366

- `<% robotsMetaString %>` - Robots meta tag content

367

- `<% title %>` - Page title

368

- `<% favIconString %>` - Favicon HTML

369

- `<% customJs %>` - External JavaScript script tags

370

- `<% customJsStr %>` - Inline JavaScript code

371

- `<% customCssUrl %>` - External CSS link tags

372

- `<% customCss %>` - Inline CSS styles

373

374

JavaScript Template (`jsTplString`):

375

- `<% swaggerOptions %>` - Serialized SwaggerUI configuration object

376

377

### Error Handling

378

379

The middleware automatically handles these cases:

380

381

**Route Protection:**

382

- Blocks access to `/package.json` endpoint (returns 404 status)

383

- Prevents exposure of sensitive package information

384

385

**Content Serving:**

386

- Serves `/swagger-ui-init.js` with proper `application/javascript` content-type

387

- Automatically generates initialization script with current configuration

388

- Falls through to next middleware for unhandled requests

389

390

**Template Processing:**

391

- Safely processes template placeholders in HTML and JavaScript templates

392

- Handles missing or invalid configuration gracefully

393

- Preserves function objects during JSON serialization using custom stringify

394

395

### Request Object Extensions

396

397

When using dynamic documents, the middleware expects:

398

399

```javascript { .api }

400

/**

401

* Request object extension for dynamic swagger documents

402

*/

403

interface Request {

404

/** Swagger document object to render dynamically (overrides static document) */

405

swaggerDoc?: Object;

406

}

407

```

408

409

### Dependencies

410

411

- **express**: Peer dependency (>=4.0.0 || >=5.0.0-beta) - Express framework

412

- **swagger-ui-dist**: Direct dependency (>=5.0.0) - Provides Swagger UI static assets (CSS, JS, images)