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:

  1. SSE Creation (SSE() BIF) - Push events from your BoxLang server to clients

  2. SSE Consumption (http() BIF / bx:http component) - 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

Create 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

New 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

Parameter
Type
Required
Default
Description

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 filtering

  • id (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

Performance Tips:

  • Use async: true for long-running streams to avoid blocking request threads

  • Set appropriate timeout values for async streams to prevent resource leaks

  • Use keepAliveInterval for long-lived connections (30-60 seconds recommended)

  • Check emitter.isClosed() frequently in loops to detect disconnects early

  • Implement proper error handling in callback functions

  • Consider rate limiting for high-frequency updates

  • Use event types to allow client-side filtering

🔒 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:

📚 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

Using the bx:http Component

SSE Event Structure

Each event received in the onChunk callback contains:

Callback Parameters

The onChunk callback receives five parameters:

Parameter
Type
Description

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


🎯 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 detection

  • SSE Consumption (http() BIF / bx:http component) - 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?