Are Server Sent Events possible with Hono? #1355
Replies: 4 comments 1 reply
-
You can't do it directly. But, you can utilize Streams API, which might allow you to achieve something similar. Refer to the following documentation: https://developer.mozilla.org/en-US/docs/Web/API/Streams_API |
Beta Was this translation helpful? Give feedback.
-
example of sse import { Hono } from 'hono';
import { html } from 'hono/html';
/// sse sample application
export const sse = new Hono();
// sse sample
sse.get('/api/events', async (c) => {
let eventCount = 0;
// create a stream that emits events every 500ms to
// simulate some real-time data source
const stream = new ReadableStream({
start(controller) {
controller.enqueue('data: stream started\n\n');
},
async pull(controller) {
controller.enqueue(`id: ${eventCount}\n`);
controller.enqueue(`data: event #${eventCount}\n\n`);
eventCount++;
return new Promise((r) => setTimeout(r, 500));
},
cancel() {
console.log('stream cancelled');
},
});
return c.body(stream, {
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
Connection: 'keep-alive',
},
});
});
sse.get('/sse', async (c) => {
const pageHtml = html`
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>server-sent events - hono</title>
</head>
<body>
<h1>Server-sent events</h1>
<button onclick="source.close()">Stop event stream</button>
<ul id="events"></ul>
<script>
const events = document.getElementById('events');
const source = new EventSource('/api/events');
source.onmessage = (event) => {
events.innerHTML += '<li>' + event.data + '</li>';
};
</script>
</body>
</html>
`;
return c.html(pageHtml);
}); |
Beta Was this translation helpful? Give feedback.
-
Here's how we're using SSE with Hono for dev server live refresh in Hwy. Works great! https://github.com/hwy-js/hwy/blob/main/packages/dev/src/refresh-middleware.ts |
Beta Was this translation helpful? Give feedback.
-
It will be introduced in this PR: #1504 Will merged and new version including this will be released later. |
Beta Was this translation helpful? Give feedback.
-
I can't get SSE to work with Hono. Usually in Express of Fastify you'd be able to do
res.write()
which doesn't kill the connection. Is that possible?Beta Was this translation helpful? Give feedback.
All reactions