Server-Sent Events (SSE)
Real-time server-to-client event streaming and consumption for building AI agents, live dashboards, and real-time notifications
New in BoxLang 1.7.0 - Server-Sent Events (SSE) enable real-time, unidirectional event streaming over HTTP. BoxLang provides two powerful SSE capabilities:
SSE Creation (
SSE()BIF) - Push events from your BoxLang server to clientsSSE Consumption (
http()BIF /bx:httpcomponent) - Connect to and consume SSE streams from remote servers (New in BoxLang 1.8.0)
🌐 What are Server-Sent Events?
Server-Sent Events is a standard web technology that allows servers to push data to web clients over HTTP. Unlike WebSockets (which are bidirectional), SSE provides a simple, efficient one-way communication channel, perfect for:
AI Agent Streaming - Stream AI responses token-by-token for better UX (creation & consumption)
Live Dashboards - Push real-time metrics and updates to dashboards (creation & consumption)
Progressive Loading - Load and display content as it becomes available (creation)
Real-Time Notifications - Push notifications without polling (creation)
Log Streaming - Stream server logs to browser console (creation)
Status Updates - Track long-running processes in real-time (creation & consumption)
Consuming Third-Party Streams - Connect to AI APIs (OpenAI, Claude), monitoring services, event feeds (consumption)
📋 Table of Contents
🔄 SSE Creation vs Consumption
BoxLang provides both sides of the SSE equation:
SSE Creation - SSE() BIF
SSE() BIFCreate SSE streams that push events to web browsers and clients:
Use cases:
Push real-time updates to your web UI
Stream AI responses from your BoxLang backend
Build live dashboards
Send notifications to connected clients
SSE Consumption - http() BIF / bx:http Component
http() BIF / bx:http ComponentNew in BoxLang 1.8.0 - Consume SSE streams from remote servers:
Use cases:
Consume AI streaming APIs (OpenAI, Claude, Gemini)
Connect to real-time monitoring feeds
Subscribe to third-party event streams
Integrate with microservices using SSE
📋 SSE() BIF - Creating Streams
The SSE() function establishes a Server-Sent Events connection and streams data to the client.
Syntax
Parameters
callback
function
Yes
-
Closure/lambda that receives the emitter object for sending events
async
boolean
No
false
Run callback in background thread (non-blocking)
retry
number
No
0
Client reconnect interval in milliseconds (0 = no reconnect)
keepAliveInterval
number
No
0
Auto-send keep-alive comments interval in milliseconds (0 = disabled)
timeout
number
No
0
Maximum execution time for async mode in milliseconds (0 = no timeout)
cors
string
No
""
CORS origin header (* for all origins, specific domain, or empty for none)
Emitter Methods
The callback function receives an emitter object with the following methods:
send( data, [event], [id] )
Send an SSE event to the client. Complex data is automatically serialized to JSON.
Parameters:
data(required) - Data to send (string, number, struct, array, etc.)event(optional) - Event type/name for client-side filteringid(optional) - Event ID for client-side tracking
comment( text )
Send an SSE comment (not visible to client, used for keep-alive).
close()
Gracefully close the SSE stream.
isClosed()
Check if the client has disconnected.
💡 Usage Examples
Basic Synchronous Streaming
AI Streaming with Async Execution
Cross-Origin Streaming
Live Dashboard Updates
Progress Tracking
Log Streaming
Real-Time Notifications
🎨 Client-Side JavaScript
Basic EventSource Usage
AI Streaming Example
Dashboard Updates Example
⚙️ Implementation Features
Automatic First-Byte Flush
BoxLang's SSE implementation automatically flushes the first byte to establish the connection quickly, ensuring minimal latency before streaming begins.
Large Data Chunking
Data larger than 32KB is automatically split into properly formatted SSE chunks, ensuring reliable delivery of large payloads.
Multi-Line Data Support
Complex data with newlines is automatically formatted according to SSE specification with proper data: line prefixing.
Client Disconnect Detection
The emitter automatically detects when clients disconnect, allowing your callback to gracefully stop processing with emitter.isClosed().
Proxy/Nginx Compatibility
Response headers are automatically configured to disable buffering in proxies (nginx, Apache) for true real-time delivery:
Keep-Alive Support
Configure automatic keep-alive comments to keep connections alive through proxies and firewalls:
🎯 Best Practices
When to Use SSE:
AI response streaming for better user experience
Real-time dashboard updates
Live log streaming
Progress tracking for long-running operations
Real-time notifications and alerts
One-way server-to-client communication (server pushes data)
Important Considerations:
Browser Compatibility: SSE is supported in all modern browsers (not IE11)
Connection Limits: Browsers limit concurrent SSE connections (typically 6 per domain)
Reconnection: Clients automatically reconnect - use
retryparameter to control intervalAsync Mode: Always use
async: truefor streams lasting more than a few secondsResource Management: Set
timeoutfor async streams to prevent orphaned threadsProxy Buffering: Ensure proxies/CDNs don't buffer SSE responses (headers handled automatically)
Memory Usage: Long-running streams consume server resources - monitor and limit as needed
Security: Implement authentication/authorization before establishing SSE connections
🔒 Security Considerations
Authentication
Always authenticate users before establishing SSE connections:
Authorization
Verify user permissions for the requested data stream:
CORS Configuration
Be specific with CORS origins in production:
Rate Limiting
Implement rate limiting to prevent abuse:
🔗 Related Resources
📚 Additional Examples
Multi-Channel Chat Streaming
Stock Price Updates
📥 SSE Consumption - Connecting to Remote Streams
New in BoxLang 1.8.0 - BoxLang now provides built-in support for consuming Server-Sent Events from remote servers using the http() BIF or bx:http component.
Why Consume SSE?
SSE consumption allows you to connect to external SSE endpoints and process events in real-time:
🤖 AI Streaming APIs - Consume token-by-token responses from OpenAI, Claude, Gemini, and other AI services
📊 Real-Time Data Feeds - Connect to stock tickers, weather updates, sports scores
🔔 Event Notifications - Subscribe to third-party notification services
📈 Monitoring Services - Receive alerts and metrics from monitoring platforms
🔄 Microservices - Integrate with SSE-based microservices architecture
Basic SSE Consumption
Using the http() BIF
http() BIFUsing the bx:http Component
bx:http ComponentSSE Event Structure
Each event received in the onChunk callback contains:
Callback Parameters
The onChunk callback receives five parameters:
event
struct
The SSE event (data, event, id, retry)
lastEventId
string
Most recent event ID (for reconnection)
httpResult
struct
HTTP result structure
httpClient
object
BoxHttpClient instance
response
object
Raw Java HttpResponse
Real-World SSE Consumption Examples
OpenAI Streaming Chat
Claude AI Streaming
Real-Time Stock Quotes
Server Monitoring Feed
GitHub Events Stream
Advanced SSE Consumption Patterns
Reconnection with Last Event ID
Multiple Event Types
Timeout and Error Handling
SSE Consumption Best Practices
Best Practices for SSE Consumption:
Always handle errors - Network failures will interrupt streams
Store
lastEventId- Use it to reconnect and resume from last eventImplement reconnection logic - Connections will drop, be ready to reconnect
Parse event types - Different event types require different handling
Handle stream termination signals - Look for
[DONE], empty data, or specific event typesSet appropriate timeouts - Long-lived streams need longer timeouts
Use try-catch for parsing - JSON parsing can fail on malformed data
Log connection state - Track connects, disconnects, and errors
Implement exponential backoff - Don't hammer failing endpoints
Monitor memory usage - Accumulating data can grow quickly
Important Considerations:
Unidirectional - SSE is server → client only (no client → server messages)
Network sensitive - Interruptions terminate the stream
Proxy buffering - Some proxies buffer responses (check your infrastructure)
Browser connection limits - Browsers limit concurrent SSE connections (typically 6 per domain)
Long-lived connections - Consumes server resources, monitor connection count
Error handling is critical - Always implement robust retry logic
Memory management - Process and discard events, don't accumulate indefinitely
Authentication - Include proper API keys/tokens in headers
🎯 Summary
Server-Sent Events in BoxLang provides a powerful, standards-based way to build real-time web applications with minimal complexity:
SSE Creation (
SSE()BIF) - Push events from BoxLang to web clients with automatic connection management, keep-alive, and client disconnect detectionSSE Consumption (
http()BIF /bx:httpcomponent) - Connect to and consume SSE streams from remote servers with built-in event parsing, reconnection support, and error handling
Whether you're building real-time dashboards, streaming AI responses, or integrating with third-party event feeds, BoxLang's SSE support makes it easy to create robust streaming experiences.
Last updated
Was this helpful?
