A simple Server-Sent Events (SSE) library for Laravel apps.
Try it now without installing Laravel:
./start.sh
# Or manually: php -S localhost:8000 server.phpThen open http://localhost:8000 in your browser!
See QUICKSTART.md for more details.
- Easy integration with Laravel
- Fluent API for sending events
- Support for event types and IDs
- Auto-reconnection handling
- Connection status monitoring
- JSON and text event support
- Keep-alive comments
- Configurable retry times
- Multiple usage patterns
Install via Composer:
composer require nerdofcode/laravel-sseThe package will automatically register its service provider.
php artisan vendor:publish --tag=sse-configThis will create config/sse.php where you can configure default settings.
use LaravelSSE\Facades\SSE;
Route::get('/stream', function () {
return SSE::create(function () {
return ['time' => now()->toDateTimeString()];
}, 1); // Sends event every 1 second
});use LaravelSSE\SSE;
Route::get('/stream', function (SSE $sse) {
return $sse->stream(function (SSE $sse) {
$counter = 0;
while ($sse->isConnected() && $counter < 10) {
$sse->json(['count' => ++$counter]);
sleep(1);
}
});
});Route::get('/stream', function () {
return app('sse')->stream(function ($sse) {
$sse->message('Hello World!');
});
});Create a custom SSE stream with full control:
SSE::stream(function (SSE $sse) {
while ($sse->isConnected()) {
$sse->event('data', 'event-name', 'event-id');
sleep(1);
}
});Create a simple auto-streaming SSE response:
SSE::create(function () {
return ['data' => 'value'];
}, 2); // Send every 2 secondsSend a custom event:
$sse->event('Message content', 'message', '123');Send a simple message (alias for event with data only):
$sse->message('Hello World', '123');Send JSON data:
$sse->json(['user' => 'John', 'status' => 'active'], 'user-update', '456');Send a comment (keeps connection alive):
$sse->comment('Keep-alive');Set reconnection retry time:
SSE::setRetry(5000)->stream(...);Set default event ID:
SSE::setEventId('stream-1')->stream(...);Add custom header:
SSE::setHeader('X-Custom', 'value')->stream(...);Set maximum execution time (0 = unlimited):
SSE::setExecutionTime(300)->stream(...);Check if client is still connected:
while ($sse->isConnected()) {
// Send events
}Stop the stream:
$sse->stop();const eventSource = new EventSource('/stream');
// Listen to all messages
eventSource.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log('Received:', data);
};
// Listen to specific event types
eventSource.addEventListener('custom-event', (event) => {
const data = JSON.parse(event.data);
console.log('Custom event:', data);
});
// Handle errors
eventSource.onerror = (error) => {
console.error('SSE Error:', error);
};
// Close connection
eventSource.close();Route::get('/counter', function () {
return SSE::create(function () use (&$counter) {
static $counter = 0;
return ['count' => ++$counter];
});
});Route::get('/progress', function () {
return SSE::stream(function (SSE $sse) {
for ($i = 0; $i <= 100; $i += 10) {
$sse->json([
'progress' => $i,
'status' => $i < 100 ? 'processing' : 'complete'
], 'progress');
sleep(1);
}
});
});Route::get('/notifications', function (Request $request) {
$userId = $request->user()->id;
return SSE::stream(function (SSE $sse) use ($userId) {
$lastCheck = now();
while ($sse->isConnected()) {
$notifications = Notification::where('user_id', $userId)
->where('created_at', '>', $lastCheck)
->get();
foreach ($notifications as $notification) {
$sse->json($notification, 'notification', $notification->id);
}
$lastCheck = now();
sleep(2);
}
});
});The package includes a comprehensive test suite.
# Install dependencies
composer install
# Run all tests
composer test
# Run with coverage report
composer test-coverage
# Run specific test suite
./vendor/bin/phpunit tests/Unit
./vendor/bin/phpunit tests/Feature- ✅ SSE class methods and configuration
- ✅ Event formatting and output
- ✅ Service provider registration
- ✅ Facade functionality
- ✅ Integration tests for streaming
- ✅ Standalone SSE implementation
See tests/README.md for more details.
Edit config/sse.php:
return [
'retry' => env('SSE_RETRY', 3000), // Retry time in ms
'execution_time' => env('SSE_EXECUTION_TIME', 0), // Max execution time
];Or use .env:
SSE_RETRY=5000
SSE_EXECUTION_TIME=300- PHP >= 8.0
- Laravel >= 9.0
MIT License