Skip to content

Usage recipes

Better SSE can be used with any web-server framework that uses the underlying Node HTTP module. This section shows example usage with some popular HTTP frameworks.

Feel free to submit a PR with a minimal example for another framework!

HTTP

server.ts
import { createServer } from "http";
import { createSession } from "better-sse";
const server = createServer(async (req, res) => {
switch (req.url) {
case "/sse": {
const session = await createSession(req, res);
session.push("Hello world!");
break;
}
default: {
res.writeHead(404).end();
}
}
});
server.listen(8080);

Express

server.ts
import express from "express";
import { createSession } from "better-sse";
const app = express();
app.get("/sse", async (req, res) => {
const session = await createSession(req, res);
session.push("Hello world!");
});
app.listen(8080);

Koa

server.ts
import Koa from "koa";
import Router from "@koa/router";
import { createSession } from "better-sse";
const app = new Koa();
const router = new Router();
router.get( "/sse", async (ctx) => {
// Prevent Koa sending a response and closing the connection
ctx.respond = false;
const session = await createSession(ctx.req, ctx.res);
session.push("Hello world!");
});
app.use(router.routes());
app.listen(8080);

Nest

Assuming you are using @nestjs/platform-express (the default).

server.ts
import { Controller, Get, Req, Res } from "@nestjs/common";
import { Request, Response } from "express";
import { createSession } from "better-sse";
@Controller()
export class SseController {
@Get("sse")
async sse(@Req() req: Request, @Res() res: Response) {
const sse = await createSession(req, res);
sse.push("Hello world!");
}
}

Fastify

server.ts
import Fastify from "fastify";
import { createSession } from "better-sse";
const fastify = Fastify();
fastify.get("/sse", async (request, reply) => {
const session = await createSession(request.raw, reply.raw);
session.push("Hello world!");
});
fastify.listen({ port: 8080 });

Adonis

server.ts
import router from "@adonisjs/core/services/router";
import { createSession } from "better-sse";
router.get("/sse", async ({ request, response }) => {
const session = await createSession(request.request, response.response);
session.push("Hello world!");
});

Hapi

server.ts
import Hapi from "@hapi/hapi";
import { createSession } from "better-sse";
const init = async () => {
const server = Hapi.server({
port: 8080,
host: "localhost",
});
server.route({
method: "GET",
path: "/sse",
handler: async ({ raw }, { abandon }) => {
const session = await createSession(raw.req, raw.res);
session.push("Hello world!");
return abandon;
},
});
await server.start();
};
init();