今日已更新 166 条资讯 | 累计 40611 条内容
关于我们

Next.js App Router — WebSockets via Client Islands

Nainik Mehta 2026年09月01日 17:37 3 次阅读 来源:Dev.to

The Challenge: Realtime in the Age of Server Components The paradigm shift toward React Server Components (RSC) and the Next.js App Router has fundamentally changed how we architect web applications. We are now defaulting to server-side rendering, which is fantastic for performance, SEO, and initial load times. However, a common friction point arises when we need to inject high-frequency, bidirectional realtime data into these server-rendered pages. Too often, developers fall into the trap of importing heavy socket libraries directly into their server components or wrapping their entire application in massive context providers, effectively bloating the client bundle and negating the performance gains of the App Router. The Solution: The "Client Island" Pattern Instead of fighting the architecture, we can embrace "Client Islands"—a pattern where we isolate the stateful, client-side logic into a tiny, focused leaf component. By keeping the WebSocket management strictly client-side, we ensure that our server-rendered pages remain lightweight, fast, and cacheable. Implementing the WebSocket Island The goal is to keep the WebSocket connection lifecycle outside of the rendering flow. We utilize useEffect to manage the connection, ensuring it only runs on the client, and we tap into data fetching libraries like TanStack Query or SWR to surgically update the UI. ' use client ' ; import { useEffect } from ' react ' ; import { useQueryClient } from ' @tanstack/react-query ' ; export function RealtimeSync ({ token }) { const queryClient = useQueryClient (); useEffect (() => { const ws = new WebSocket ( `wss://realtime.example.com?token= ${ token } ` ); ws . onmessage = ( event ) => { const data = JSON . parse ( event . data ); queryClient . setQueryData ([ ' items ' ], data ); }; return () => ws . close (); }, [ token , queryClient ]); return null ; // This component renders nothing, just manages the side effect } Persistence via RootLayout To prevent the connection from dropp

本文内容来源于互联网,版权归原作者所有
查看原文