DEV Community

Yug Jadvani
Yug Jadvani

Posted on

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
Enter fullscreen mode Exit fullscreen mode

Step 2: Install TypeScript

npm install typescript --save-dev
npx tsc --init
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Update tsconfig.json

Modify the TypeScript configuration to enable importing JSON files:

"resolveJsonModule": true
Enter fullscreen mode Exit fullscreen mode

Add Swagger Script to package.json

"scripts": {
  "swagger": "ts-node src/swagger.ts"
}
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

Starting the Server

Create src/index.ts

import app from './app';

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

app.listen(PORT, () => {
  console.log(`🚀 Server is running on: http://localhost:${PORT}`);
  console.log(`📚 API Documentation: http://localhost:${PORT}/api-docs`);
});
Enter fullscreen mode Exit fullscreen mode

Generating API Documentation

Run the following command to generate Swagger documentation:

npm run swagger
Enter fullscreen mode Exit fullscreen mode

This command generates swagger-output.json, which Swagger UI will use to serve API documentation.

Conclusion

Integrating Swagger with Node.js and TypeScript automates API documentation, ensuring that it remains up-to-date with minimal effort. This setup provides:

  • Automated API documentation
  • Improved developer experience
  • Seamless API exploration via Swagger UI

With this approach, C-suite executives and senior developers can maintain high documentation standards, ensuring better collaboration, faster development cycles, and reduced onboarding time for new developers.


By implementing Swagger, companies can future-proof their API documentation while maintaining transparency across teams. If you're building scalable and enterprise-grade Node.js applications, Swagger is a must-have tool in your stack.

Top comments (0)