Skip to content

A hapijs server sent event (SSE) example #4521

Description

@wy193777

Module version

21.3.10

What documentation problem did you notice?

There is no hapijs SSE example. I recently figured it out but don't know where to put it. So I have it here:

'use strict';

const Hapi = require('@hapi/hapi');

const init = async () => {
    const server = Hapi.server({
        port: 3000,
        host: 'localhost'
    });

    // Route using raw.res for direct response handling
    server.route({
        method: 'GET',
        path: '/sse',
        handler: async (request, h) => {
            const res = request.raw.res;
            res.writeHead(200, { "Content-Type": "application/json" });

            const intervalId = setInterval(() => {
                res.write('this is a server sent event message');
            }, 1000);  // send a message every 1 second 
            const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
            await sleep(10000);  // mock a long running request handling

            res.end('This is a raw response using raw.res');
            return h.abandon; // Abandon Hapi's normal response flow because we used raw response
        }
    });

    await server.start();
    console.log('Server running on %s', server.info.uri);
};

process.on('unhandledRejection', (err) => {
    console.log(err);
    process.exit(1);
});

init();

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions