0270

BE

[Node.js] Swagger를 이용한 Node.js API 문서화, 이렇게 하면 끝!

시작하며

백엔드 API를 개발하다 보면 API 명세 관리가 쉽지 않다.

특히 팀원이나 프론트엔드 개발자가 API를 테스트하려면 Postman 설정을 공유해야 하고, 문서를 따로 작성해야 한다.

이 문제를 해결해주는 도구가 바로 Swagger(OpenAPI) 이다.

Swagger를 적용하면,

  • /docs에서 API 명세를 바로 확인 가능

  • 토큰 인증이 필요한 API도 브라우저에서 즉시 테스트 가능

  • Prisma 모델과 함께 사용하면 DB 구조와 API를 깔끔하게 관리

아래는 Express + Node.js + Prisma 환경에서 Swagger를 빠르게 붙이는 방법이다.

1. 필수 패키지 설치

JavaScript
npm i express cors helmet morgan dotenv
npm i swagger-ui-express swagger-jsdoc
npm i @prisma/client

API 서버 개발에 필요한 기본 패키지를 설치해야 한다.

  • express로 서버를 만들고,

  • cors로 프론트엔드와의 요청을 허용하고,

  • helmet으로 보안 헤더를 적용하고,

  • morgan으로 요청 로그를 확인하며,

  • dotenv로 환경변수를 관리한다.

  • 또한, swagger-ui-express + swagger-jsdoc으로 Swagger 문서를 구성하고, DB 연동을 위해 @prisma/client를 설치한다.

2. Swagger 설정 파일 만들기 (src/swagger.js)

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

const swaggerDefinition = {
  openapi: '3.0.3',
  info: {
    title: 'API 문서',
    version: '1.0.0',
    description: 'Express + Prisma + Swagger 예시'
  },
  servers: [{ url: '/' }],
  components: {
    securitySchemes: {
      Authorization: { type: 'http', scheme: 'bearer', bearerFormat: 'JWT' }
    }
  },
  security: [{ Authorization: [] }] // 모든 API에 Authorization 적용
};

const options = {
  definition: swaggerDefinition,
  apis: ['./src/routes/**/*.js'], // JSDoc 읽을 경로
};

module.exports = {
  swaggerUi,
  swaggerSpec: swaggerJSDoc(options)
};

Swagger 문서의 기본 정보를 정의해야 한다.

  • OpenAPI 버전, API 제목·버전·설명을 설정하고,

  • API 요청 기본 URL을 지정하며,

  • JWT Bearer 인증 스키마를 정의한다.

  • 마지막으로, swagger-jsdoc이 읽어야 할 라우트 경로(apis)를 지정해 JSDoc 주석을 기반으로 문서를 생성하도록 한다.

3. Express 서버에 Swagger 연결 (src/server.js)

TypeScript
const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const morgan = require('morgan');
const dotenv = require('dotenv');

const { swaggerUi, swaggerSpec } = require('./swagger');
const authRoutes = require('./routes/auth');

dotenv.config();
const app = express();

// 미들웨어
app.use(cors({
  origin: process.env.CORS_ORIGIN || 'http://localhost:3000',
  credentials: true,
  allowedHeaders: ['Content-Type', 'Authorization']
}));
app.use(express.json());
app.use(helmet());
app.use(morgan('dev'));

// Swagger UI
app.use('/docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));

// API 라우트
app.use('/api/auth', authRoutes);

// 기본 에러 핸들러
app.use((req, res) => res.status(404).json({ message: 'Not Found' }));

const PORT = process.env.PORT || 4000;
app.listen(PORT, () => {
  console.log(`? Server: http://localhost:${PORT}`);
  console.log(`? Swagger: http://localhost:${PORT}/docs`);
});

Express 서버를 초기화하고 Swagger UI를 연결해야 한다.

  • cors, helmet, morgan 등 필수 미들웨어를 설정하고,

  • /docs 경로로 Swagger UI를 접근할 수 있도록 연결하며,

  • 실제 API 라우트를 /api/auth로 등록한다.

  • 마지막으로, 서버 실행 시 Swagger 문서 접속 URL도 함께 콘솔에 표시한다.

4. 라우트에 JSDoc으로 API 문서화 (src/routes/auth.js)

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

/**
 * @openapi
 * /api/auth/me:
 *   get:
 *     summary: 내 정보 조회
 *     tags: [Auth]
 *     responses:
 *       200:
 *         description: 유저 정보 반환
 *       401:
 *         description: 인증 실패
 */
router.get('/me', (req, res) => {
  // 예시: Authorization 헤더에서 토큰 추출
  const authHeader = req.headers.authorization;
  if (!authHeader) return res.status(401).json({ error: 'No token' });
  res.json({ name: '홍길동', email: 'test@example.com' });
});

module.exports = router;

Swagger가 읽을 수 있도록 API에 JSDoc 주석을 추가해야 한다.

  • @openapi 키워드로 OpenAPI 형식의 설명을 작성하고,

  • API URL, HTTP 메서드, 요약, 태그, 응답 상태 코드를 명시한다.

  • 이렇게 하면 Swagger UI에서 자동으로 문서화되어, 개발자들이 API의 요청/응답 구조를 한눈에 확인하고 테스트할 수 있다.

5. Swagger에서 Bearer 토큰 테스트하기

  1. http://localhost:4000/docs 접속

  2. 우측 Authorize 버튼 클릭

  3. 토큰 입력란에 토큰만 입력 (Bearer는 자동으로 붙음)

  4. GET /api/auth/meTry it outExecute 실행

6. 자주 발생하는 문제

문제

원인

해결

Authorize 했는데 헤더에 토큰이 안 붙음

스키마 이름 불일치

components.securitySchemessecurity의 이름 동일하게

Failed to fetch

CORS 미설정 또는 서버 URL 불일치

cors()에서 Authorization 허용, Swagger servers.url 확인

항상 401

토큰 만료 또는 입력 형식 오류

토큰만 입력, Bearer는 직접 안 붙임

마무리하며

Swagger를 붙이면 API 문서와 테스트 환경을 한 번에 제공할 수 있어, 프론트엔드와의 협업 효율이 크게 올라간다.

특히 Bearer 토큰 인증을 Swagger에서 바로 테스트 가능하게 하면, Postman 없이도 모든 팀원이 실시간으로 API를 검증할 수 있다.

다음 단계로는 Prisma 모델 → Swagger 스키마 자동화를 추가하면 DB 구조와 API 문서가 완벽히 동기화된 개발 환경을 만들 수 있다.