How to Build a Notification System: Claude Code 활용 가이드
build a notification system: Claude Code 활용. 실용적인 코드 예시와 단계별 가이드를 포함합니다.
알림システムの구축をClaude Code로 효율화하기
Web앱における알림は、토스트표시からプッシュ알림、실시간업데이트まで多岐にわたります。Claude Code를 활용하면 이것らを통합した알림基盤を短시간で구축할 수 있습니다。
토스트알림컴포넌트の구현
まずは앱内で使う토스트알림を作ります。
> 라이브러리を使わずに토스트알림컴포넌트をReactで作って。
> success/error/warning/infoの4種類。自動で消える。스택표시대응。
import { createContext, useContext, useState, useCallback, type ReactNode } from "react";
type ToastType = "success" | "error" | "warning" | "info";
interface Toast {
id: string;
type: ToastType;
message: string;
}
interface ToastContextType {
addToast: (type: ToastType, message: string) => void;
}
const ToastContext = createContext<ToastContextType | null>(null);
const TOAST_STYLES: Record<ToastType, string> = {
success: "bg-green-500 text-white",
error: "bg-red-500 text-white",
warning: "bg-yellow-500 text-black",
info: "bg-blue-500 text-white",
};
const TOAST_ICONS: Record<ToastType, string> = {
success: "✓",
error: "✕",
warning: "⚠",
info: "ℹ",
};
export function ToastProvider({ children }: { children: ReactNode }) {
const [toasts, setToasts] = useState<Toast[]>([]);
const addToast = useCallback((type: ToastType, message: string) => {
const id = crypto.randomUUID();
setToasts((prev) => [...prev, { id, type, message }]);
setTimeout(() => {
setToasts((prev) => prev.filter((t) => t.id !== id));
}, 4000);
}, []);
return (
<ToastContext.Provider value={{ addToast }}>
{children}
<div className="fixed bottom-4 right-4 flex flex-col gap-2 z-50">
{toasts.map((toast) => (
<div
key={toast.id}
className={`px-4 py-3 rounded-lg shadow-lg flex items-center gap-2 animate-slide-in ${TOAST_STYLES[toast.type]}`}
>
<span>{TOAST_ICONS[toast.type]}</span>
<span>{toast.message}</span>
<button
onClick={() => setToasts((prev) => prev.filter((t) => t.id !== toast.id))}
className="ml-2 opacity-70 hover:opacity-100"
>
✕
</button>
</div>
))}
</div>
</ToastContext.Provider>
);
}
export function useToast() {
const context = useContext(ToastContext);
if (!context) throw new Error("useToast must be used within ToastProvider");
return context;
}
WebSocket에 의한실시간알림
서버からの실시간알림を受け取る仕組みも구축할 수 있습니다。
// Server side(Node.js + ws)
import { WebSocketServer, WebSocket } from "ws";
interface Client {
ws: WebSocket;
userId: string;
}
const clients: Client[] = [];
const wss = new WebSocketServer({ port: 8080 });
wss.on("connection", (ws, req) => {
const userId = new URL(req.url!, `http://${req.headers.host}`).searchParams.get("userId");
if (!userId) return ws.close();
clients.push({ ws, userId });
ws.on("close", () => {
const index = clients.findIndex((c) => c.ws === ws);
if (index !== -1) clients.splice(index, 1);
});
});
// 特定사용자への알림전송
export function sendNotification(userId: string, notification: object) {
clients
.filter((c) => c.userId === userId)
.forEach((c) => c.ws.send(JSON.stringify(notification)));
}
// Client sideのフック
import { useEffect, useRef, useCallback } from "react";
interface Notification {
id: string;
type: string;
title: string;
body: string;
}
export function useNotifications(userId: string, onNotification: (n: Notification) => void) {
const wsRef = useRef<WebSocket | null>(null);
const connect = useCallback(() => {
const ws = new WebSocket(`ws://localhost:8080?userId=${userId}`);
ws.onmessage = (event) => {
const notification = JSON.parse(event.data);
onNotification(notification);
};
ws.onclose = () => {
setTimeout(connect, 3000); // Reconnect
};
wsRef.current = ws;
}, [userId, onNotification]);
useEffect(() => {
connect();
return () => wsRef.current?.close();
}, [connect]);
}
알림の永続化と既読관리
알림をDBに저장して既読관리する機能も추가할 수 있습니다。
// Prisma스키마から自動でAPI생성を依頼
// schema.prisma の内容をClaude Code가 読み取って구현
import { db } from "@/lib/database";
export async function getNotifications(userId: string) {
return db.notification.findMany({
where: { userId },
orderBy: { createdAt: "desc" },
take: 50,
});
}
export async function markAsRead(notificationId: string) {
return db.notification.update({
where: { id: notificationId },
data: { readAt: new Date() },
});
}
export async function getUnreadCount(userId: string) {
return db.notification.count({
where: { userId, readAt: null },
});
}
Claude Code로の개발効率を上げるには生産性を3倍にする10のTips를 참고하세요.폼との연동에 대해서는폼유효성 검사설계も併せてご覧주세요。
정리
Claude Code를 활용하면 토스트알림、실시간알림、永続化まで含めた알림システム全体を효율적으로구축할 수 있습니다。自然言語で要件を伝え、段階的に機能를 추가해줘いくのがおすすめです。
공식 문서はClaude Codeから확인할 수 있습니다。
#Claude Code
#notification system
#WebSocket
#toast
#real-time
Related Posts
Advanced
Advanced
Claude Code MCP Server 설정 및 실전 활용 가이드
Claude Code의 MCP Server 기능을 종합적으로 소개합니다. 외부 도구 연결, 서버 설정, 실전 통합 사례까지 한 번에 알아보세요.
Advanced
Advanced
Claude Code Hooks 완전 정복: 자동 포맷팅, 자동 테스트 설정법
Claude Code Hooks로 자동 포맷팅과 자동 테스트를 설정하는 방법을 알아봅니다. 실용적인 설정 예제와 실전 활용 사례를 포함합니다.
Advanced
Advanced
CLAUDE.md 작성 완벽 가이드: 프로젝트 설정 베스트 프랙티스
효과적인 CLAUDE.md 파일 작성법을 상세히 소개합니다. 기술 스택, 컨벤션, 프로젝트 구조를 Claude Code에 전달하여 출력 품질을 극대화하세요.