Automating Node.js Documentation with Swagger

Automating Node.js Documentation with Swagger In a fast-paced development environment, documentation often becomes an afterthought. However, clear and well-structured API documentation is crucial for maintaining consistency, improving onboarding, and reducing technical debt. Swagger is the industry standard for automating API documentation, ensuring that developers and stakeholders have an up-to-date reference for your Node.js applications. This guide provides a step-by-step approach to integrating Swagger into a TypeScript-based Node.js project, ensuring seamless API documentation generation. Setting Up a Node.js Project with TypeScript Before integrating Swagger, ensure you have a Node.js project set up with TypeScript. Step 1: Initialize Your Project mkdir my-nodejs-project cd my-nodejs-project npm init -y Step 2: Install TypeScript npm install typescript --save-dev npx tsc --init This initializes TypeScript and generates a tsconfig.json file. Installing Required Dependencies To integrate Swagger into your project, install the following dependencies: npm install swagger-autogen swagger-ui-express npm install -D @types/swagger-ui-express Update tsconfig.json Modify the TypeScript configuration to enable importing JSON files: "resolveJsonModule": true Add Swagger Script to package.json "scripts": { "swagger": "ts-node src/swagger.ts" } This script generates Swagger documentation automatically. Setting Up API Routes Create a User Routes File (src/routes/user.routes.ts) Define your API endpoints here. For example: import express from 'express'; const router = express.Router(); router.get('/users', (req, res) => { res.json({ message: 'List of users' }); }); export default router; Create an Index Route File (src/routes/index.ts) Import and register the user routes in this file: import express from 'express'; import userRoutes from './user.routes'; const router = express.Router(); router.use('/users', userRoutes); export default router; Generating API Documentation with Swagger Create swagger.ts in src/ import swaggerAutogen from 'swagger-autogen'; const doc = { info: { version: 'v1.0.0', title: 'LexBridge API', description: 'LexBridge is a seamless platform that connects clients with verified legal experts, offering secure communication, easy appointment booking, transparent pricing, and comprehensive legal services all in one place.' }, host: `localhost:${process.env.PORT || 8080}`, basePath: '/', schemes: ['http', 'https'], }; const outputFile = './swagger-output.json'; const endpointsFiles = ['src/routes/index.ts']; swaggerAutogen()(outputFile, endpointsFiles, doc); This script generates swagger-output.json, which contains the API documentation. Configuring Express Application Create src/app.ts import express from 'express'; import cors from 'cors'; import routes from './routes'; import swaggerUi from 'swagger-ui-express'; import swaggerDocument from './swagger-output.json'; const app = express(); app.use(cors({ origin: process.env.CORS_ORIGIN, credentials: true })); app.use(express.json({ limit: '16kb' })); app.use(express.urlencoded({ extended: true, limit: '16kb' })); app.use(express.static('public')); // Mount API routes under /api/v1 prefix app.use('/api/v1', routes); // Serve Swagger documentation app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument)); export default app; Starting the Server Create src/index.ts import app from './app'; const PORT = process.env.PORT || 8080; app.listen(PORT, () => { console.log(`

Mar 3, 2025 - 02:12
 0
Automating Node.js Documentation with Swagger

Automating Node.js Documentation with Swagger

In a fast-paced development environment, documentation often becomes an afterthought. However, clear and well-structured API documentation is crucial for maintaining consistency, improving onboarding, and reducing technical debt. Swagger is the industry standard for automating API documentation, ensuring that developers and stakeholders have an up-to-date reference for your Node.js applications.

This guide provides a step-by-step approach to integrating Swagger into a TypeScript-based Node.js project, ensuring seamless API documentation generation.

Setting Up a Node.js Project with TypeScript

Before integrating Swagger, ensure you have a Node.js project set up with TypeScript.

Step 1: Initialize Your Project

mkdir my-nodejs-project
cd my-nodejs-project
npm init -y

Step 2: Install TypeScript

npm install typescript --save-dev
npx tsc --init

This initializes TypeScript and generates a tsconfig.json file.

Installing Required Dependencies

To integrate Swagger into your project, install the following dependencies:

npm install swagger-autogen swagger-ui-express
npm install -D @types/swagger-ui-express

Update tsconfig.json

Modify the TypeScript configuration to enable importing JSON files:

"resolveJsonModule": true

Add Swagger Script to package.json

"scripts": {
  "swagger": "ts-node src/swagger.ts"
}

This script generates Swagger documentation automatically.

Setting Up API Routes

Create a User Routes File (src/routes/user.routes.ts)

Define your API endpoints here. For example:

import express from 'express';
const router = express.Router();

router.get('/users', (req, res) => {
  res.json({ message: 'List of users' });
});

export default router;

Create an Index Route File (src/routes/index.ts)

Import and register the user routes in this file:

import express from 'express';
import userRoutes from './user.routes';

const router = express.Router();

router.use('/users', userRoutes);

export default router;

Generating API Documentation with Swagger

Create swagger.ts in src/

import swaggerAutogen from 'swagger-autogen';

const doc = {
  info: {
    version: 'v1.0.0',
    title: 'LexBridge API',
    description: 'LexBridge is a seamless platform that connects clients with verified legal experts, offering secure communication, easy appointment booking, transparent pricing, and comprehensive legal services all in one place.'
  },
  host: `localhost:${process.env.PORT || 8080}`,
  basePath: '/',
  schemes: ['http', 'https'],
};

const outputFile = './swagger-output.json';
const endpointsFiles = ['src/routes/index.ts'];

swaggerAutogen()(outputFile, endpointsFiles, doc);

This script generates swagger-output.json, which contains the API documentation.

Configuring Express Application

Create src/app.ts

import express from 'express';
import cors from 'cors';
import routes from './routes';
import swaggerUi from 'swagger-ui-express';
import swaggerDocument from './swagger-output.json';

const app = express();

app.use(cors({ origin: process.env.CORS_ORIGIN, credentials: true }));
app.use(express.json({ limit: '16kb' }));
app.use(express.urlencoded({ extended: true, limit: '16kb' }));
app.use(express.static('public'));

// Mount API routes under /api/v1 prefix
app.use('/api/v1', routes);

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

export default app;

Starting the Server

Create src/index.ts

import app from './app';

const PORT = process.env.PORT || 8080;

app.listen(PORT, () => {
  console.log(`