Back to Blog
·13 min

Building Real-Time Applications with WebSockets and Server-Sent Events

Real-time features transform static applications into dynamic, engaging experiences.

WebSocket Server with Socket.IO

      import { Server } from 'socket.io'

      const io = new Server(server, { cors: { origin: process.env.NEXT_PUBLIC_URL } })

      io.on('connection', (socket) => {
        socket.on('join_room', (roomId) => {
          socket.join(roomId)
          io.to(roomId).emit('user_joined', { userId: socket.data.userId })
        })

        socket.on('send_message', ({ roomId, content }) => {
          io.to(roomId).emit('new_message', {
            id: crypto.randomUUID(),
            content,
            senderId: socket.data.userId,
            timestamp: Date.now(),
          })
        })

        socket.on('typing', ({ roomId }) => {
          socket.to(roomId).emit('user_typing', { userId: socket.data.userId })
        })
      })

Server-Sent Events for Notifications

      // app/api/events/route.ts
      export async function GET(req: Request) {
        const stream = new ReadableStream({
          start(controller) {
            const encoder = new TextEncoder()
            const send = (event: string, data: any) => {
              controller.enqueue(encoder.encode(`event: ${event}
data: ${JSON.stringify(data)}

`))
            }

            const unsubscribe = subscribeToNotifications((notification) => {
              send('notification', notification)
            })

            req.signal.addEventListener('abort', () => {
              unsubscribe()
              controller.close()
            })
          },
        })

        return new Response(stream, {
          headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache' },
        })
      }

Presence System

Track online/offline status with heartbeat monitoring.

The Bottom Line

The Real-Time Chat from BreafIO provides WebSocket-based messaging. The RN Chat Messenger adds mobile real-time features. The Admin Dashboard Pro includes live notifications. The Analytics Dashboard shows real-time metrics, and the Collaborative Code Editor demonstrates real-time collaboration.

Ready to Build?

Get started with our production-ready starter kits and ship your project faster.

Browse Starter Kits