Skip to main content
This guide explains how to use Sonamu’s SSE endpoints in the frontend. You can receive real-time events using the browser’s EventSource API.

EventSource API

A built-in browser API for managing SSE connections.

Basic Usage

// Create SSE connection
const source = new EventSource('/stream/notifications?userId=1');

// Register event listener
source.addEventListener('notification', (event) => {
  const data = JSON.parse(event.data);
  console.log('Notification:', data);
});

// Connection end event
source.addEventListener('end', () => {
  source.close();
});

// Error handling
source.onerror = (error) => {
  console.error('SSE Error:', error);
  source.close();
};

React Integration

Basic Hook

import { useEffect, useState } from 'react';

function useSSE<T>(url: string, eventName: string) {
  const [data, setData] = useState<T | null>(null);
  const [error, setError] = useState<Error | null>(null);
  const [isConnected, setIsConnected] = useState(false);

  useEffect(() => {
    const source = new EventSource(url);

    source.onopen = () => {
      setIsConnected(true);
    };

    source.addEventListener(eventName, (event) => {
      try {
        const parsed = JSON.parse(event.data);
        setData(parsed);
      } catch (err) {
        setError(err as Error);
      }
    });

    source.addEventListener('end', () => {
      source.close();
      setIsConnected(false);
    });

    source.onerror = (err) => {
      setError(new Error('SSE connection failed'));
      setIsConnected(false);
      source.close();
    };

    return () => {
      source.close();
      setIsConnected(false);
    };
  }, [url, eventName]);

  return { data, error, isConnected };
}

Usage Example

function NotificationList() {
  const { data: notification, isConnected } = useSSE<{
    id: number;
    message: string;
  }>('/stream/notifications?userId=1', 'notification');

  return (
    <div>
      <div>Status: {isConnected ? 'Connected' : 'Disconnected'}</div>
      {notification && (
        <div>
          <strong>#{notification.id}</strong>: {notification.message}
        </div>
      )}
    </div>
  );
}

Practical Examples

1. Real-time Notifications

import { useEffect, useState } from 'react';

type Notification = {
  id: number;
  type: 'like' | 'comment' | 'follow';
  message: string;
  createdAt: string;
};

function NotificationCenter({ userId }: { userId: number }) {
  const [notifications, setNotifications] = useState<Notification[]>([]);
  const [isConnected, setIsConnected] = useState(false);

  useEffect(() => {
    const source = new EventSource(
      `/stream/notifications?userId=${userId}`
    );

    source.onopen = () => {
      setIsConnected(true);
    };

    source.addEventListener('notification', (event) => {
      const notification = JSON.parse(event.data) as Notification;
      setNotifications(prev => [notification, ...prev].slice(0, 10));

      // Browser notification
      if (Notification.permission === 'granted') {
        new Notification(notification.message);
      }
    });

    source.addEventListener('end', () => {
      source.close();
      setIsConnected(false);
    });

    source.onerror = () => {
      setIsConnected(false);
      source.close();
    };

    return () => {
      source.close();
    };
  }, [userId]);

  return (
    <div>
      <div className="status">
        {isConnected ? '🟢 Connected' : '🔴 Disconnected'}
      </div>
      <div className="notifications">
        {notifications.map(noti => (
          <div key={noti.id} className={`notification ${noti.type}`}>
            <span>{noti.message}</span>
            <time>{new Date(noti.createdAt).toLocaleTimeString()}</time>
          </div>
        ))}
      </div>
    </div>
  );
}

2. Task Progress

import { useEffect, useState } from 'react';

type Progress = {
  current: number;
  total: number;
  percentage: number;
};

function TaskProgress({ taskId }: { taskId: number }) {
  const [progress, setProgress] = useState<Progress | null>(null);
  const [isComplete, setIsComplete] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const source = new EventSource(`/stream/taskProgress?taskId=${taskId}`);

    source.addEventListener('progress', (event) => {
      const data = JSON.parse(event.data) as Progress;
      setProgress(data);
    });

    source.addEventListener('complete', (event) => {
      const data = JSON.parse(event.data);
      setIsComplete(true);
      source.close();
    });

    source.addEventListener('error', (event) => {
      const data = JSON.parse(event.data);
      setError(data.message);
      source.close();
    });

    source.addEventListener('end', () => {
      source.close();
    });

    return () => {
      source.close();
    };
  }, [taskId]);

  if (error) {
    return <div className="error">Error: {error}</div>;
  }

  if (isComplete) {
    return <div className="success">Task completed!</div>;
  }

  return (
    <div className="progress-bar">
      <div
        className="progress-fill"
        style={{ width: `${progress?.percentage || 0}%` }}
      />
      <span>{progress?.current || 0} / {progress?.total || 0}</span>
    </div>
  );
}

3. Live Feed

import { useEffect, useState } from 'react';

type Post = {
  id: number;
  title: string;
  author: string;
  createdAt: string;
};

function LiveFeed() {
  const [posts, setPosts] = useState<Post[]>([]);

  useEffect(() => {
    const source = new EventSource('/stream/newPosts');

    source.addEventListener('newPost', (event) => {
      const post = JSON.parse(event.data) as Post;

      // Add new post to the top
      setPosts(prev => [post, ...prev]);

      // Show notification
      showToast(`New post: ${post.title}`);
    });

    source.addEventListener('end', () => {
      source.close();
    });

    return () => {
      source.close();
    };
  }, []);

  return (
    <div className="live-feed">
      <h2>Live Feed 📡</h2>
      {posts.map(post => (
        <article key={post.id}>
          <h3>{post.title}</h3>
          <p>by {post.author}</p>
          <time>{new Date(post.createdAt).toLocaleString()}</time>
        </article>
      ))}
    </div>
  );
}

4. Multiple Event Handling

import { useEffect, useState } from 'react';

type Message = {
  id: number;
  text: string;
  sender: string;
};

type TypingStatus = {
  userId: number;
  isTyping: boolean;
};

function ChatRoom({ roomId }: { roomId: number }) {
  const [messages, setMessages] = useState<Message[]>([]);
  const [typingUsers, setTypingUsers] = useState<number[]>([]);

  useEffect(() => {
    const source = new EventSource(`/stream/chatRoom?roomId=${roomId}`);

    // Message event
    source.addEventListener('message', (event) => {
      const message = JSON.parse(event.data) as Message;
      setMessages(prev => [...prev, message]);
    });

    // Typing status event
    source.addEventListener('typing', (event) => {
      const data = JSON.parse(event.data) as TypingStatus;
      setTypingUsers(prev =>
        data.isTyping
          ? [...prev, data.userId]
          : prev.filter(id => id !== data.userId)
      );
    });

    // Join event
    source.addEventListener('joined', (event) => {
      const data = JSON.parse(event.data);
      showToast(`${data.username} joined the room`);
    });

    // Leave event
    source.addEventListener('left', (event) => {
      const data = JSON.parse(event.data);
      showToast(`User ${data.userId} left the room`);
    });

    source.addEventListener('end', () => {
      source.close();
    });

    return () => {
      source.close();
    };
  }, [roomId]);

  return (
    <div className="chat-room">
      <div className="messages">
        {messages.map(msg => (
          <div key={msg.id}>
            <strong>{msg.sender}:</strong> {msg.text}
          </div>
        ))}
      </div>
      {typingUsers.length > 0 && (
        <div className="typing-indicator">
          {typingUsers.length} user(s) typing...
        </div>
      )}
    </div>
  );
}

5. Auto Reconnection

import { useEffect, useState, useRef } from 'react';

function useSSEWithReconnect<T>(
  url: string,
  eventName: string,
  maxRetries = 5
) {
  const [data, setData] = useState<T | null>(null);
  const [isConnected, setIsConnected] = useState(false);
  const retriesRef = useRef(0);

  useEffect(() => {
    let source: EventSource | null = null;
    let reconnectTimeout: NodeJS.Timeout | null = null;

    const connect = () => {
      source = new EventSource(url);

      source.onopen = () => {
        setIsConnected(true);
        retriesRef.current = 0;  // Reset retry counter
      };

      source.addEventListener(eventName, (event) => {
        const parsed = JSON.parse(event.data);
        setData(parsed);
      });

      source.addEventListener('end', () => {
        source?.close();
        setIsConnected(false);
      });

      source.onerror = () => {
        source?.close();
        setIsConnected(false);

        // Attempt reconnection
        if (retriesRef.current < maxRetries) {
          retriesRef.current += 1;
          const delay = Math.min(1000 * Math.pow(2, retriesRef.current), 30000);

          reconnectTimeout = setTimeout(() => {
            console.log(`Reconnecting... (${retriesRef.current}/${maxRetries})`);
            connect();
          }, delay);
        } else {
          console.error('Max retries reached. Giving up.');
        }
      };
    };

    connect();

    return () => {
      source?.close();
      if (reconnectTimeout) {
        clearTimeout(reconnectTimeout);
      }
    };
  }, [url, eventName, maxRetries]);

  return { data, isConnected };
}

// Usage
function ReconnectingNotifications() {
  const { data, isConnected } = useSSEWithReconnect<{
    message: string;
  }>('/stream/notifications?userId=1', 'notification');

  return (
    <div>
      <div>Status: {isConnected ? 'Connected' : 'Reconnecting...'}</div>
      {data && <div>{data.message}</div>}
    </div>
  );
}

Vue Integration

import { ref, onMounted, onUnmounted } from 'vue';

export function useSSE<T>(url: string, eventName: string) {
  const data = ref<T | null>(null);
  const isConnected = ref(false);
  let source: EventSource | null = null;

  onMounted(() => {
    source = new EventSource(url);

    source.onopen = () => {
      isConnected.value = true;
    };

    source.addEventListener(eventName, (event) => {
      data.value = JSON.parse(event.data);
    });

    source.addEventListener('end', () => {
      source?.close();
      isConnected.value = false;
    });

    source.onerror = () => {
      source?.close();
      isConnected.value = false;
    };
  });

  onUnmounted(() => {
    source?.close();
  });

  return { data, isConnected };
}

// Usage
// <script setup>
// const { data, isConnected } = useSSE('/stream/notifications', 'notification');
// </script>

Authentication Handling

// EventSource automatically sends cookies
const source = new EventSource('/stream/notifications');
Note: When using CORS, credentials: 'include' is not needed (automatic)

Bearer Token Authentication

Since EventSource does not support custom headers, use URL parameters:
const token = localStorage.getItem('token');
const source = new EventSource(`/stream/notifications?token=${token}`);
Server side:
@stream({
  type: 'sse',
  events: z.object({
    notification: z.string(),
  })
})
@api({ compress: false })
async *streamNotifications(token: string, ctx: Context) {
  // Verify token
  const user = await this.verifyToken(token);
  if (!user) {
    throw new Error('Unauthorized');
  }

  // ...
}

Error Handling

Connection Failure

const source = new EventSource('/stream/data');

source.onerror = (error) => {
  console.error('Connection failed:', error);

  // EventSource doesn't provide status codes
  // Instead, the server sends error events
};

// Handle server-sent error events
source.addEventListener('error', (event) => {
  const data = JSON.parse(event.data);
  console.error('Server error:', data.message);
  source.close();
});

Timeout Handling

const source = new EventSource('/stream/data');
let timeoutId: NodeJS.Timeout;

// Set timeout (30 seconds)
const resetTimeout = () => {
  clearTimeout(timeoutId);
  timeoutId = setTimeout(() => {
    console.log('Connection timeout');
    source.close();
  }, 30000);
};

source.addEventListener('message', () => {
  resetTimeout();
});

source.addEventListener('end', () => {
  clearTimeout(timeoutId);
  source.close();
});

Debugging

Browser Developer Tools

Network tab → Filter by EventStream type

Request:
  GET /stream/notifications?userId=1
  Accept: text/event-stream

Response:
  Content-Type: text/event-stream

EventStream tab:
  event: notification
  data: {"id": 1, "message": "Hello"}

  event: notification
  data: {"id": 2, "message": "World"}

  event: end
  data: END

Logging

const source = new EventSource('/stream/data');

source.onopen = () => {
  console.log('[SSE] Connected');
};

source.addEventListener('message', (event) => {
  console.log('[SSE] Message:', event.data);
});

source.addEventListener('end', () => {
  console.log('[SSE] End');
  source.close();
});

source.onerror = (error) => {
  console.error('[SSE] Error:', error);
};

Important Notes

Important considerations when using SSE on the client:
  1. Connection cleanup: Always call close() when component unmounts
    useEffect(() => {
      const source = new EventSource('/stream/data');
      return () => {
        source.close();  // Required!
      };
    }, []);
    
  2. Event name matching: Server and client event names must be identical
    // Server: sse.publish('notification', ...)
    // Client: source.addEventListener('notification', ...)
    
  3. JSON parsing: Data is always transmitted as strings
    source.addEventListener('data', (event) => {
      const data = JSON.parse(event.data);  // Parsing required
    });
    
  4. Browser limitations: Concurrent connection limit (6 per domain)
    • Solution: Reuse connections or use HTTP/2
  5. Reconnection handling: Implement auto-reconnection for network disconnections
    source.onerror = () => {
      setTimeout(() => {
        // Reconnection logic
      }, 1000);
    };
    
  6. Memory leaks: Clean up old data
    setNotifications(prev => prev.slice(0, 100));  // Max 100 items
    
  7. CORS configuration: Server CORS settings required when using from different domains
    // Server: cors: { origin: 'https://example.com' }
    

Polyfill (IE Support)

For legacy browser support like IE 11:
npm install event-source-polyfill
import { EventSourcePolyfill } from 'event-source-polyfill';

const source = new EventSourcePolyfill('/stream/data', {
  headers: {
    'Authorization': `Bearer ${token}`
  }
});

Next Steps