Community코딩 & 개발github.com

aj-geddes/nodejs-express-server

미들웨어, 인증, 라우팅 및 데이터베이스 통합을 통해 프로덕션 수준의 Express.js 서버를 구축합니다. REST API 생성, 요청/응답 관리, 미들웨어 체인 구현 및 서버 로직 처리 시 사용하세요.

nodejs-express-server란 무엇인가요?

이 스킬은 Express.js를 사용하여 프로덕션에 바로 사용 가능한 REST API 서버를 구축하기 위한 포괄적인 가이드입니다. 미들웨어 구성, 인증, 라우팅, 데이터베이스 통합(예: MongoDB) 등 실제 서버 개발에 필요한 핵심 패턴을 다룹니다. 특히, 사용자 정의 미들웨어 체인을 설정하고 JWT 기반 인증을 구현하는 방법을 상세히 설명하며, CORS 설정, 오류 처리, 로깅 등 서버 운영에 필수적인 요소들을 포함합니다. 이 스킬은 Node.js 및 Express.js 기반 프로젝트에서 작업하는 개발자에게 유용하며, Cursor, Codex, Claude Code 등 다양한 AI 에이전트 플랫폼에서 활용할 수 있습니다. README 및 SKILL.md 문서를 기반으로 하여 실제 프로젝트에 즉시 적용 가능한 모범 사례를 제공합니다.

지원 대상~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/aj-geddes/useful-ai-prompts/tree/main/skills/nodejs-express-server

Installed? Explore more 코딩 & 개발 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

즐겨 사용하는 AI에게 물어보기

이 에이전트 스킬이 미리 로드된 새 채팅을 엽니다.

문서

nodejs-express-server은(는) 무엇을 하나요?

미들웨어, 인증, 라우팅 및 데이터베이스 통합을 통해 프로덕션 수준의 Express.js 서버를 구축합니다. REST API 생성, 요청/응답 관리, 미들웨어 체인 구현 및 서버 로직 처리 시 사용하세요.

개요

이 스킬은 Express.js 애플리케이션 개발을 위한 모범 사례와 패턴을 제공합니다. 주요 구성 요소는 다음과 같습니다:

  • 미들웨어 체인: 요청 로깅, 본문 구문 분석, CORS 등 기본 미들웨어 설정.
  • 인증: JWT 기반 사용자 인증 및 권한 부여.
  • 라우팅: 모듈식 라우트 구성.
  • 데이터베이스 통합: MongoDB 연결 및 스키마 정의.
  • 오류 처리: 중앙 집중식 오류 처리 미들웨어.

설정

npm init -y
npm install express mongoose cors dotenv jsonwebtoken bcryptjs

기본 서버 예제

const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
require('dotenv').config();

const app = express();

// 미들웨어
app.use(cors());
app.use(express.json());

// 데이터베이스 연결
mongoose.connect(process.env.MONGODB_URI)
  .then(() => console.log('MongoDB 연결 성공'))
  .catch(err => console.error('MongoDB 연결 오류:', err));

// 라우트
app.get('/api/health', (req, res) => {
  res.json({ status: 'OK', timestamp: new Date().toISOString() });
});

// 서버 시작
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
  console.log(`서버가 포트 ${PORT}에서 실행 중입니다.`);
});

미들웨어 체인 예제

// 사용자 정의 로깅 미들웨어
app.use((req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next();
});

// 인증 미들웨어
const authenticate = (req, res, next) => {
  const token = req.header('Authorization')?.replace('Bearer ', '');
  if (!token) {
    return res.status(401).json({ message: '인증 실패: 토큰이 필요합니다.' });
  }
  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    req.user = decoded;
    next();
  } catch (error) {
    res.status(401).json({ message: '인증 실패: 유효하지 않은 토큰입니다.' });
  }
};

// 보호된 라우트에 인증 미들웨어 적용
app.get('/api/profile', authenticate, (req, res) => {
  res.json({ user: req.user });
});

라우팅 예제

// routes/users.js
const express = require('express');
const router = express.Router();
const User = require('../models/User');

router.get('/', async (req, res) => {
  try {
    const users = await User.find();
    res.json(users);
  } catch (error) {
    res.status(500).json({ message: '사용자 조회 중 오류 발생', error });
  }
});

router.post('/register', async (req, res) => {
  try {
    const { name, email, password } = req.body;
    const user = new User({ name, email, password });
    await user.save();
    res.status(201).json({ message: '사용자 생성 성공', userId: user._id });
  } catch (error) {
    res.status(400).json({ message: '사용자 생성 중 오류 발생', error });
  }
});

module.exports = router;
// app.js - 메인 서버 파일
const userRoutes = require('./routes/users');
app.use('/api/users', userRoutes);

환경 변수

.env 파일을 생성하고 다음 변수를 설정하세요:

PORT=5000
MONGODB_URI=mongodb://localhost:27017/yourapp
JWT_SECRET=your_jwt_secret_key_change_this
NODE_ENV=development

오류 처리

// 중앙 집중식 오류 처리 미들웨어
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(err.status || 500).json({
    message: err.message || '내부 서버 오류',
    ...(process.env.NODE_ENV === 'development' && { stack: err.stack })
  });
});

스킬 사용 방법

이 스킬은 다음 상황에 유용합니다:

  • REST API 구축
  • 요청/응답 처리
  • 미들웨어 체인 구현
  • 데이터베이스 통합
  • 인증 및 권한 부여
  • 오류 처리
  • 서버 로직 관리

Individual skills in this repo

This repo contains 11 individual skills — each has its own dedicated page.

aj-geddes/android-kotlin-development

Develop native Android apps with Kotlin. Covers MVVM with Jetpack, Compose for modern UI, Retrofit for API calls, Room for local storage, and navigation architecture.

aj-geddes/ansible-automation

Infrastructure automation and configuration management using Ansible playbooks, roles, and inventory. Use for deploying applications, patching, and managing servers.

aj-geddes/architecture-diagrams

Create system architecture diagrams using Mermaid, PlantUML, C4 model, flowcharts, and sequence diagrams. Use when documenting architecture, system design, data flows, or technical workflows.

aj-geddes/code-review-analysis

Perform comprehensive code reviews with best practices, security checks, and constructive feedback. Use when reviewing pull requests, analyzing code quality, checking for security vulnerabilities, or providing code improvement suggestions.

aj-geddes/flask-api-development

Develop lightweight Flask APIs with routing, blueprints, database integration, authentication, and request/response handling. Use when building RESTful APIs, microservices, or lightweight web services with Flask.

aj-geddes/ios-swift-development

Develop native iOS apps with Swift. Covers MVVM architecture, SwiftUI, URLSession for networking, Combine for reactive programming, and Core Data persistence.

aj-geddes/jenkins-pipeline

Build Jenkins declarative and scripted pipelines with stages, agents, parameters, and plugins. Implement multi-branch pipelines and deployment automation.

aj-geddes/markdown-documentation

Master markdown formatting, GitHub Flavored Markdown, README files, and documentation formatting. Use when writing markdown docs, READMEs, or formatting documentation.

aj-geddes/nginx-configuration

Configure Nginx web server for high-performance reverse proxy, load balancing, SSL/TLS, caching, and API gateway functionality.

aj-geddes/rest-api-design

Design RESTful APIs following best practices for resource modeling, HTTP methods, status codes, versioning, and documentation. Use when creating new APIs, designing endpoints, or improving existing API architecture.

aj-geddes/wireframe-prototyping

Create wireframes and interactive prototypes to visualize user interfaces and gather feedback early. Use tools and techniques to communicate design ideas before development.

관련 스킬