넥스트 Next.js
15. Next.js 15에서 WebSocket과 실시간 데이터 처리
안녕하세요! 태마입니다.
Next.js 기초 강좌입니다.
강좌의 경우
1. 주제 간단 정리
2. 상세 주제 정리
으로 이루어져 있습니다.
넥스트 Next.js
포스팅 시작하겠습니다 :)
1. 주제 간단 정리
1. Next.js 15에서 실시간 데이터 처리가 중요한 이유
Next.js 애플리케이션에서 **실시간 데이터 업데이트(예: 채팅, 알림, 주식 가격 변동)**가 필요할 경우
WebSocket, Server-Sent Events(SSE), polling 등의 기술을 활용할 수 있다.
📌 실시간 데이터 처리 방식 비교
방식설명장점단점추천 사용 예시
Polling | 일정 간격마다 서버에 요청 | ✅ 간단한 구현 | ❌ 서버 부하 증가 | 간단한 데이터 업데이트 |
WebSocket | 양방향 통신 지원 | ✅ 빠른 데이터 전송 | ❌ 연결 유지 비용 발생 | 채팅, 알림 시스템 |
SSE (Server-Sent Events) | 서버가 클라이언트로 단방향 푸시 | ✅ 가볍고 효율적 | ❌ 양방향 통신 불가능 | 실시간 뉴스, 알림 |
GraphQL Subscriptions | WebSocket을 활용한 실시간 데이터 | ✅ GraphQL 기반 실시간 데이터 | ❌ 서버 설정 필요 | 대규모 실시간 서비스 |
📌 Next.js 15에서는 "WebSocket + Server Actions" 조합이 가장 많이 사용됨!
2. Next.js 15에서 기본적인 WebSocket 구현하기
✅ 1) WebSocket 서버 구현 (app/api/socket/route.ts)
import { WebSocketServer } from "ws";
const wss = new WebSocketServer({ noServer: true });
wss.on("connection", (ws) => {
console.log("새로운 클라이언트가 연결됨!");
ws.on("message", (message) => {
console.log("메시지 수신:", message.toString());
ws.send(`서버 응답: ${message}`);
});
ws.on("close", () => console.log("클라이언트 연결 종료됨"));
});
export async function GET(req: Request) {
if (req.headers.get("upgrade") !== "websocket") {
return new Response("웹소켓 연결이 아닙니다", { status: 400 });
}
const { socket, response } = Deno.upgradeWebSocket(req);
wss.emit("connection", socket);
return response;
}
📌 WebSocket 서버를 Next.js 15의 API Routes를 활용하여 구현 가능!
✅ 2) 클라이언트에서 WebSocket 연결 (app/components/WebSocketClient.tsx)
"use client";
import { useEffect, useState } from "react";
export default function WebSocketClient() {
const [messages, setMessages] = useState<string[]>([]);
const [message, setMessage] = useState("");
let socket: WebSocket | null = null;
useEffect(() => {
socket = new WebSocket("ws://localhost:3000/api/socket");
socket.onmessage = (event) => {
setMessages((prev) => [...prev, event.data]);
};
return () => socket?.close();
}, []);
const sendMessage = () => {
if (socket) {
socket.send(message);
setMessage("");
}
};
return (
<div>
<h2>📡 WebSocket 실시간 통신</h2>
<input value={message} onChange={(e) => setMessage(e.target.value)} placeholder="메시지 입력" />
<button onClick={sendMessage}>전송</button>
<ul>
{messages.map((msg, index) => (
<li key={index}>{msg}</li>
))}
</ul>
</div>
);
}
📌 클라이언트에서 WebSocket을 활용하여 실시간 메시지를 주고받을 수 있음!
✅ 3) WebSocket을 활용한 실시간 채팅 예제 (app/chat/page.tsx)
import WebSocketClient from "@/components/WebSocketClient";
export default function ChatPage() {
return (
<main>
<h1>💬 실시간 채팅</h1>
<WebSocketClient />
</main>
);
}
📌 WebSocket을 활용하여 실시간 채팅 기능 구현 가능!
✅ 여기까지 Next.js 15에서 기본적인 WebSocket을 구현하는 방법을 배웠습니다!
👉 "그렇다면, Next.js 15에서 실시간 데이터를 polling 없이 효율적으로 가져오려면?"
✅ 2부에서 Next.js 15의 Server Actions와 함께 WebSocket을 활용하는 방법을 배워봅시다!
2. 상세 주제 정리
1. Server Actions를 활용한 실시간 데이터 처리
Next.js 15에서는 Server Actions를 활용하여 클라이언트에서 실시간 데이터를 업데이트할 수 있다.
✅ 1) Server Actions로 데이터 업데이트 (app/actions.ts)
"use server";
import { revalidatePath } from "next/cache";
export async function updateData(data: string) {
console.log("서버에서 데이터 업데이트:", data);
revalidatePath("/realtime");
}
📌 Server Actions를 활용하여 데이터 변경 시 페이지를 자동으로 업데이트!
✅ 2) 실시간 데이터 페이지 구현 (app/realtime/page.tsx)
"use client";
import { useState } from "react";
import { updateData } from "@/actions";
export default function RealtimePage() {
const [data, setData] = useState("");
const handleSubmit = async () => {
await updateData(data);
setData("");
};
return (
<main>
<h1>🔄 실시간 데이터 업데이트</h1>
<input value={data} onChange={(e) => setData(e.target.value)} placeholder="데이터 입력" />
<button onClick={handleSubmit}>업데이트</button>
</main>
);
}
📌 사용자가 데이터를 입력하면 Server Actions를 통해 실시간 업데이트 가능!
2. Next.js 15에서 SSE(Server-Sent Events) 활용
✅ 1) SSE를 활용한 실시간 데이터 전송 (app/api/sse/route.ts)
export async function GET() {
const stream = new ReadableStream({
start(controller) {
let count = 0;
const interval = setInterval(() => {
count++;
controller.enqueue(`data: 업데이트 ${count}\n\n`);
if (count === 5) clearInterval(interval);
}, 1000);
},
});
return new Response(stream, {
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
},
});
}
📌 SSE를 활용하여 서버에서 클라이언트로 실시간 데이터를 전송 가능!
✅ 2) 클라이언트에서 SSE 데이터 수신 (app/components/SSEClient.tsx)
"use client";
import { useEffect, useState } from "react";
export default function SSEClient() {
const [updates, setUpdates] = useState<string[]>([]);
useEffect(() => {
const eventSource = new EventSource("/api/sse");
eventSource.onmessage = (event) => {
setUpdates((prev) => [...prev, event.data]);
};
return () => eventSource.close();
}, []);
return (
<div>
<h2>📡 SSE 실시간 업데이트</h2>
<ul>
{updates.map((update, index) => (
<li key={index}>{update}</li>
))}
</ul>
</div>
);
}
📌 SSE를 활용하면 서버에서 실시간 데이터를 전송하여 클라이언트에서 자동으로 업데이트 가능!
✅ 여기까지 Next.js 15에서 WebSocket, Server Actions, SSE를 활용한 실시간 데이터 처리 방법을 배웠습니다!
👉 "그렇다면, Next.js 15에서 GraphQL과 Apollo를 활용한 데이터 관리는 어떻게 할까?"
✅ 다음 회차에서 Next.js 15에서 GraphQL과 Apollo를 활용하는 방법을 배워봅시다!
'IT Developer > Next.js' 카테고리의 다른 글
Next.js 기초 <19. Next.js 15에서 유지보수 및 디버깅 전략> (0) | 2025.03.22 |
---|---|
Next.js 기초 <18. Next.js 15에서 Vercel 배포 및 CDN 최적화> (0) | 2025.03.21 |
Next.js 기초 <17. Next.js 15에서 성능 최적화 및 코드 스플리팅> (0) | 2025.03.20 |
Next.js 기초 <16. Next.js 15에서 GraphQL과 Apollo를 활용한 데이터 관리> (0) | 2025.03.19 |
Next.js 기초 <14. Next.js 15에서 애니메이션과 인터랙션 (Framer Motion, GSAP, Tailwind Animation)> (0) | 2025.03.17 |
Next.js 기초 <13. Next.js 15에서 이미지 최적화 (next/image, Dynamic Image Processing)> (0) | 2025.03.16 |
Next.js 기초 <12. Next.js 15에서 Form 처리 및 유효성 검사 (React Hook Form, Zod)> (0) | 2025.03.15 |
Next.js 기초 <11. Next.js 15에서 다국어(i18n) 및 다이나믹 로컬라이제이션 구현> (0) | 2025.03.14 |