Server Sent Events

Hello guys! Sorry if this was asked before. I'm trying to implement an event emitter with SSE like this:
const emitter = new EventEmitter();

app.use("/sse/*", async (c, next) => {
c.header("Content-Type", "text/event-stream");
c.header("Cache-Control", "no-cache");
c.header("Connection", "keep-alive");
await next();
});

app.post('/message', async (c) => {
const message = 'test';
emitter.emit('message', message);
return c.json({message});
})

app.get('/sse', async (c) => {
return streamSSE(c, async (stream) => {

const handler = async (message: string) => {
await stream.writeSSE({
data: message,
event: "message"
});
}

stream.onAbort(() => {
console.log('Connection aborted');
})

emitter.on('message', handler);
})
})
const emitter = new EventEmitter();

app.use("/sse/*", async (c, next) => {
c.header("Content-Type", "text/event-stream");
c.header("Cache-Control", "no-cache");
c.header("Connection", "keep-alive");
await next();
});

app.post('/message', async (c) => {
const message = 'test';
emitter.emit('message', message);
return c.json({message});
})

app.get('/sse', async (c) => {
return streamSSE(c, async (stream) => {

const handler = async (message: string) => {
await stream.writeSSE({
data: message,
event: "message"
});
}

stream.onAbort(() => {
console.log('Connection aborted');
})

emitter.on('message', handler);
})
})
but it seems it goes directly in the onError on frontend because it closes the stream
2 Replies
Mihai Andrei
Mihai AndreiOP4mo ago
The fix seems to be to add this inside streamSSE:
let isAborted = false
stream.onAbort(() => {
isAborted = true;
})
while(!isAborted) {
await stream.sleep(500);
}
let isAborted = false
stream.onAbort(() => {
isAborted = true;
})
while(!isAborted) {
await stream.sleep(500);
}
Is this the expected way to use SSE in hono?
Mihai Andrei
Mihai AndreiOP4mo ago
I think i've found something related. It seems i need to use stream instead https://github.com/honojs/hono/issues/2993
GitHub
Stream should not be closed automatically · Issue #2993 · honojs/ho...
What version of Hono are you using? 4.4.6 What runtime/platform is your app running on? Bun What steps can reproduce the bug? Using either stream or streamSSE is not gonna work unless you're us...
Want results from more Discord servers?
Add your server