Table of Contents
Hono Server Sent Events
How to Server Sent Events with Hono
Example
let sseConnections = new Set<any>();
app.get("/sse", async (c) => {
return streamSSE(c, async (stream) => {
sseConnections.add(stream);
stream.onAbort(() => {
sseConnections.delete(stream);
});
// keep connection alive
while (true) {
await stream.writeSSE({
event: "ping",
data: "pong",
retry: 5000,
});
await stream.sleep(30000);
}
});
});
app.get("/sse/send", async (c) => {
for (const connection of sseConnections) {
await connection.writeSSE({
data: "It is " + new Date().toISOString(),
event: "time-update",
});
}
return c.text("ok");
});
Related snippets
Authorization with Pundit
Pundit is a simple and powerful authorization library that allows you to define policies for your application.
Authorization with ts-pattern
A simple example on how to use ts-pattern to authorize actions
Basic Permissions Class
A simple class to manage permissions
Drizzle ratelimit
Basic ratelimiting example with drizzle