DEV Community

Sadhan Sarker
Sadhan Sarker

Posted on

Event Stream - Server-Send Events

Server-Sent Events is a web API for subscribing to a data stream sent by a server. This opens up a network request to the server so we can stream. Think of it like a Promise that never resolves. Easily implementable using native JavaScript or reactive programming to fetch Event Stream Data.



Laravel-Backend Application Source:

// HomeController.php
// import at the begining
use Symfony\Component\HttpFoundation\StreamedResponse;


class HomeController extends Controller

    public function getEventStream() {

        $random_string = chr(rand(65, 90)) . chr(rand(65, 90)) . chr(rand(65, 90));
        $data = [
            'message' => $random_string,
            'name' => 'Sadhan Sarker',
            'time' => date('h:i:s'),
            'id' => rand(10, 100),

        $response = new StreamedResponse();
        $response->setCallback(function () use ($data){

             echo 'data: ' . json_encode($data) . "\n\n";
             //echo "retry: 100\n\n"; // no retry would default to 3 seconds.
             //echo "data: Hello There\n\n";

        $response->headers->set('Content-Type', 'text/event-stream');
        $response->headers->set('X-Accel-Buffering', 'no');
        $response->headers->set('Cach-Control', 'no-cache');


// Application routes `web.php`

Route::get('/getEventStream', 'HomeController@getEventStream');

JavaScript-Frontend Application

// javascript

let evtSource = new EventSource("/getEventStream", {withCredentials: true});

evtSource.onmessage = function (e) {
 let data = JSON.parse(;

Live Project Demo:

Demo Application

Source Code:

Source Code

Top comments (4)

goopter profile image

I have a question, in the controller, how can you add an event listener to listen to the event from Laravel application for the record update notification? so when there's an event received, we can trigger the SSE to send change to the frontend

badpaybad profile image
mesadhan profile image
Sadhan Sarker

Don't worries Internet Edge will be chromium base very soon, microsoft working on Internet Edge.

mesadhan profile image
Sadhan Sarker

yep šŸ¤“