DEV Community

Sadhan Sarker
Sadhan Sarker

Posted on

2 1

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.

event-stream

Implementations:

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";
             ob_flush();
             flush();
             //sleep(10);
             usleep(200000);
        });

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

}



//-----------------
// Application routes `web.php`

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




Enter fullscreen mode Exit fullscreen mode

JavaScript-Frontend Application



// javascript

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

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

Enter fullscreen mode Exit fullscreen mode




Live Project Demo:

Demo Application

Source Code:

Source Code

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (4)

Collapse
 
goopter profile image
goopter

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

Collapse
 
badpaybad profile image
badpaybad
Collapse
 
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 🤓

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs