Skip to main content
This guide explains how to use Sonamu’s SSE endpoints in the frontend. Sonamu provides a built-in useSSEStream hook in sonamu.shared.ts, so you typically don’t need to work with EventSource directly.

Built-in useSSEStream Hook

When you create a Sonamu project, sonamu.shared.ts includes the useSSEStream hook. It provides connection management, automatic retries, and locale header forwarding out of the box.

API

Parameters: Options: Return value (SSEStreamState):

Usage Example

useSSEStream automatically sends the Accept-Language header, allowing the server to return locale-aware responses.

EventSource API (Direct Usage)

A built-in browser API for managing SSE connections.

Basic Usage

Manual React Implementation

Below shows how to work with EventSource directly without useSSEStream. Use this when you need fine-grained control not provided by the built-in hook.

Custom Hook

Usage Example

Practical Examples

1. Real-time Notifications

2. Task Progress

3. Live Feed

4. Multiple Event Handling

5. Auto Reconnection

Vue Integration

Authentication Handling

Note: When using CORS, credentials: 'include' is not needed (automatic)

Bearer Token Authentication

Since EventSource does not support custom headers, use URL parameters:
Server side:

Error Handling

Connection Failure

Timeout Handling

Debugging

Browser Developer Tools

Logging

Important Notes

Important considerations when using SSE on the client:
  1. Connection cleanup: Always call close() when component unmounts
  2. Event name matching: Server and client event names must be identical
  3. JSON parsing: Data is always transmitted as strings
  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
  6. Memory leaks: Clean up old data
  7. CORS configuration: Server CORS settings required when using from different domains

Polyfill (IE Support)

For legacy browser support like IE 11:

Next Steps

SSE Setup

Configure the SSE plugin

Creating SSE Endpoints

Build SSE APIs with the @stream decorator