How to Implement Swagger API Documentation in Node.js (2025 Guide)
Implement Swagger API Documentation in Node.js (2025 Guide)
Building APIs without documentation is like shipping code without comments — it works, but it’s painful to maintain. That’s where Swagger (OpenAPI 3.0) comes in. It helps you create beautiful, interactive API documentation directly from your Node.js code.
In this guide, you’ll learn how to integrate Swagger with an Express.js project — step by step.
🚀 What Is Swagger (OpenAPI)?
Swagger (now known as OpenAPI Specification) is a toolset for describing, producing, and consuming RESTful APIs.
It allows developers to:
🧩 Step 1 — Initialize Your Node.js Project
mkdir node-swagger-api && cd node-swagger-api
npm init -y
npm install express swagger-ui-express swagger-jsdocCreate server.js:
const express = require('express');
const app = express();
app.use(express.json());
app.get('/api/v1/hello', (req, res) => {
res.json({ message: 'Hello Swagger!' });
});
app.listen(3000, () => console.log('Server running on http://localhost:3000'));Create a file swagger.js:
const swaggerJsdoc = require('swagger-jsdoc');
const swaggerUi = require('swagger-ui-express');
const options = {
definition: {
openapi: '3.0.0',
info: {
title: 'Node.js API Docs',
version: '1.0.0',
description: 'API documentation using Swagger in Node.js',
},
servers: [
{
url: 'http://localhost:3000',
},Add this inside server.js:
const { swaggerUi, swaggerSpec } = require('./swagger');
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));Now visit 👉 http://localhost:3000/api-docs — you’ll see your interactive documentation live.
🧱 Step 5 — Document an Example Route
Create a folder routes/ → add file user.js:
/**
* @swagger
* /api/v1/user:
* get:
* summary: Get user info
* responses:
* 200:
* description: Success
*/
app.get('/api/v1/user', (req, res) => {
res.json({ id: 1, name: 'John Doe' });
});With just a few lines, you now have a live API documentation portal your entire team can use.
🔑 Key Benefits
Use this in production with proper security (e.g., API key auth) and serve docs only in development.
Share this article
Enjoyed this article?
Support our work and help us create more free content for developers.
Stay Updated
Get the latest articles and updates delivered to your inbox.