> ## Documentation Index
> Fetch the complete documentation index at: https://docs.loremstock.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Node.js API Documentation with JSDoc and Swagger

> Generate API documentation using JSDoc annotations, serve interactive Swagger UI with swagger-jsdoc, publish Postman collections, and write READMEs and changelogs.

Documentation is as critical as the code itself. Without good documentation, developers cannot onboard, APIs cannot be consumed, and future maintainers cannot understand decisions. This page covers JSDoc for code-level documentation, Swagger/OpenAPI for interactive API reference, and best practices for READMEs and changelogs.

## Why Document Your API

<CardGroup cols={2}>
  <Card title="Faster Onboarding" icon="rocket">
    New team members make their first successful API call in minutes, not days.
  </Card>

  <Card title="API Contracts" icon="file-text">
    Frontend and backend teams agree on endpoints, payloads, and error responses before writing code.
  </Card>

  <Card title="Better Testing" icon="check">
    QA engineers and integration partners use docs to build test suites.
  </Card>

  <Card title="Maintenance" icon="wrench">
    Six months from now, documented edge cases save hours of debugging.
  </Card>
</CardGroup>

## Types of Documentation

| Type            | Purpose                                       | Where it lives              |
| --------------- | --------------------------------------------- | --------------------------- |
| Inline comments | Explain a specific line or block              | Inside .js files            |
| JSDoc           | Describe functions, parameters, return values | Above function declarations |
| API reference   | Complete endpoint docs                        | Swagger UI at /api-docs     |
| README          | Project overview and setup                    | README.md at root           |
| Changelog       | History of changes                            | CHANGELOG.md at root        |
| Error codes     | HTTP status and error message reference       | README or dedicated page    |

## JSDoc

JSDoc is a markup language for annotating JavaScript. It generates structured HTML documentation from specially formatted comments.

```bash theme={null}
npm install --save-dev jsdoc
```

### JSDoc Annotations Reference

| Annotation                  | Purpose                | Example                                     |
| --------------------------- | ---------------------- | ------------------------------------------- |
| `@param {type} name - desc` | Describe a parameter   | `@param {string} email - User's email`      |
| `@returns {type} desc`      | Describe return value  | `@returns {Promise<Object>} Created user`   |
| `@typedef {Object} Name`    | Define a custom type   | `@typedef {Object} User`                    |
| `@example`                  | Show usage example     | `@example createUser({ email: 'a@b.com' })` |
| `@throws {type} when`       | Document an exception  | `@throws {Error} If email is taken`         |
| `@async`                    | Mark as async function | `@async`                                    |
| `@deprecated`               | Mark as deprecated     | `@deprecated Use createUserV2 instead`      |

### Annotated Function Example

```javascript theme={null}
/**
 * Create a new user in the database.
 *
 * @async
 * @param {Object} userData - User creation data.
 * @param {string} userData.email - Unique email address.
 * @param {string} userData.password - Plaintext password (hashed before storage).
 * @param {string} [userData.role='user'] - Optional role. Defaults to 'user'.
 * @returns {Promise<Object>} The newly created user (without password field).
 * @throws {Error} If the email is already registered.
 *
 * @example
 * const user = await createUser({ email: 'alice@example.com', password: 'pass123' });
 * console.log(user._id);
 */
async function createUser(userData) {
  const user = new User(userData);
  await user.save();
  return user.toObject({ versionKey: false, transform: (doc, ret) => { delete ret.password; return ret; } });
}
```

### Generate HTML Docs

```json theme={null}
// jsdoc.json
{
  "source": {
    "include": ["./src"],
    "includePattern": "\\.js$",
    "exclude": ["./node_modules"]
  },
  "opts": {
    "destination": "./docs/jsdoc",
    "recurse": true
  },
  "plugins": ["plugins/markdown"]
}
```

```bash theme={null}
npx jsdoc -c jsdoc.json
# Opens docs/jsdoc/index.html
```

## Swagger / OpenAPI

OpenAPI is the specification standard for describing REST APIs in YAML or JSON. Swagger is the tooling ecosystem around it.

### Install

```bash theme={null}
npm install swagger-jsdoc swagger-ui-express
```

### Setup in app.js

```javascript theme={null}
const express = require('express');
const swaggerJsdoc = require('swagger-jsdoc');
const swaggerUi = require('swagger-ui-express');

const app = express();

const swaggerOptions = {
  definition: {
    openapi: '3.0.0',
    info: {
      title: 'SWDBD401 Backend API',
      version: '1.0.0',
      description: 'Backend API for the SWDBD401 course application'
    },
    servers: [
      { url: 'http://localhost:3000/api/v1', description: 'Local development' },
      { url: 'https://api.yourdomain.com/api/v1', description: 'Production' }
    ],
    components: {
      securitySchemes: {
        bearerAuth: {
          type: 'http',
          scheme: 'bearer',
          bearerFormat: 'JWT'
        }
      }
    }
  },
  apis: ['./routes/*.js']   // Where to scan for @swagger comments
};

const specs = swaggerJsdoc(swaggerOptions);
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(specs));

app.listen(3000, () => console.log('Docs at http://localhost:3000/api-docs'));
```

### Documenting a Route

Place `@swagger` comments above or near the route handler:

```javascript theme={null}
/**
 * @swagger
 * /users:
 *   post:
 *     summary: Create a new user
 *     description: Registers a new user account.
 *     tags: [Users]
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             required: [email, password]
 *             properties:
 *               email:
 *                 type: string
 *                 format: email
 *                 example: alice@example.com
 *               password:
 *                 type: string
 *                 minLength: 8
 *                 example: SecurePass123!
 *               role:
 *                 type: string
 *                 enum: [user, admin]
 *                 default: user
 *     responses:
 *       201:
 *         description: User created successfully
 *       400:
 *         description: Validation error
 *       409:
 *         description: Email already exists
 *     security:
 *       - bearerAuth: []
 */
router.post('/', userController.createUser);
```

Visit `http://localhost:3000/api-docs` to see the interactive Swagger UI where you can test every endpoint.

## Postman Documentation

1. Build a Postman collection with all your API requests
2. Click the collection > `...` > **Publish Docs**
3. Postman generates a shareable URL with styled documentation
4. Keep it updated: after any API change, update the Postman request

Frontend developers can import the collection and start making requests immediately.

## README Best Practices

A standard README structure:

````markdown theme={null}
# SWDBD401 API

Backend API for the SWDBD401 Backend Application Development course.

## Prerequisites

- Node.js 20.x or higher
- MongoDB 6.x
- npm 10.x

## Installation

```bash
git clone https://github.com/yourusername/swdbd401-api.git
cd swdbd401-api
npm install
````

## Environment Setup

Copy the template and fill in your values:

```bash theme={null}
cp .env.example .env
```

Required variables: PORT, DB\_URI, JWT\_SECRET

## Running the Application

```bash theme={null}
npm run dev    # Development with hot reload
npm start      # Production
npm test       # Run tests
npm run docs   # Generate JSDoc
```

## API Overview

| Endpoint              | Method | Description  | Auth |
| --------------------- | ------ | ------------ | ---- |
| /health               | GET    | Health check | No   |
| /api/v1/auth/register | POST   | Register     | No   |
| /api/v1/auth/login    | POST   | Login        | No   |
| /api/v1/users         | GET    | List users   | JWT  |
| /api/v1/users/:id     | GET    | Get user     | JWT  |

Full interactive docs: [http://localhost:3000/api-docs](http://localhost:3000/api-docs)

## Contributing

1. Fork the repository
2. Create a branch: `git checkout -b feature/your-feature`
3. Commit: `git commit -m 'Add your feature'`
4. Push: `git push origin feature/your-feature`
5. Open a Pull Request

````text theme={null}

## CHANGELOG.md: Keep a Changelog Format

```markdown
# Changelog

All notable changes are documented here. Format: [Keep a Changelog](https://keepachangelog.com/)

## [1.2.0] - 2024-09-03

### Added
- JWT authentication with refresh token support
- Rate limiting on auth endpoints (5 attempts / 15 min)
- Swagger UI documentation at /api-docs

### Changed
- Updated Express from 4.18 to 4.19
- Replaced console.log with Winston structured logging

### Fixed
- Email validation now accepts plus-sign addressing
- Pagination now returns correct total count

### Security
- Patched jsonwebtoken CVE-2024-1234 by upgrading to v9.0.2
- Added helmet middleware for HTTP security headers

## [1.1.0] - 2024-06-01

### Added
- Pagination support on GET /users
- Role-based authorization middleware

## [1.0.0] - 2024-03-15

### Added
- Initial release: CRUD for users and posts
- JWT authentication
- MongoDB with Mongoose
````

| Section        | What to Include                |
| -------------- | ------------------------------ |
| **Added**      | New features, endpoints, pages |
| **Changed**    | Updates to existing behavior   |
| **Deprecated** | Features to be removed         |
| **Removed**    | Deleted endpoints or features  |
| **Fixed**      | Bug fixes                      |
| **Security**   | Vulnerability patches          |

## Error Code Reference Table

Include this in your README or API docs:

| HTTP Status | Code              | Description                    | Resolution                               |
| ----------- | ----------------- | ------------------------------ | ---------------------------------------- |
| 400         | VALIDATION\_ERROR | Request body failed validation | Check the errors array for field details |
| 401         | UNAUTHORIZED      | Missing or invalid token       | Include `Authorization: Bearer <token>`  |
| 403         | FORBIDDEN         | Token valid, but no permission | Contact admin for elevated access        |
| 404         | NOT\_FOUND        | Resource does not exist        | Check the ID and endpoint                |
| 409         | CONFLICT          | Duplicate unique field         | Change the conflicting value             |
| 422         | UNPROCESSABLE     | Semantically invalid request   | See errors array                         |
| 429         | RATE\_LIMITED     | Too many requests              | Wait and retry after the window          |
| 500         | SERVER\_ERROR     | Unexpected server error        | Retry; contact support if persistent     |

## Key Terms

| Term              | Definition                                                               |
| ----------------- | ------------------------------------------------------------------------ |
| **JSDoc**         | Markup language for annotating JavaScript code to generate documentation |
| **OpenAPI**       | Standard specification for describing REST APIs in YAML or JSON          |
| **Swagger**       | Tools ecosystem (swagger-jsdoc, swagger-ui-express) built around OpenAPI |
| **swagger-ui**    | Web interface rendering interactive docs from an OpenAPI spec            |
| **swagger-jsdoc** | Generates OpenAPI spec by scanning JSDoc comments in source files        |
| **README**        | Markdown file at repository root explaining purpose and setup            |
| **Changelog**     | File recording all notable changes organized by version and category     |

## Common Mistakes

<Accordion title="Not updating Swagger comments after changing routes">
  Outdated docs mislead consumers. Treat @swagger comments as part of the route. Review them in every code review.
</Accordion>

<Accordion title="Publishing protected endpoint docs without auth examples">
  If you omit `security: [{ bearerAuth: [] }]` from a protected route, developers test without tokens, get 401, and don't understand why.
</Accordion>

<Accordion title="Letting the changelog fall behind">
  A changelog only covering the last two releases is useless. Make updating it a required step in your release process alongside version bumping.
</Accordion>

<Accordion title="No README on public repositories">
  A repository without a README is uninviting and forces every new person to read all the source code. Even a minimal README with setup steps saves hours.
</Accordion>
