unjs / nitro

Next Generation Server Toolkit. Create web servers with everything you need and deploy them wherever you prefer.
https://nitro.unjs.io
MIT License
5.83k stars 492 forks source link

Add a Usage example for SSE in the docs #2374

Open martinszeltins opened 4 months ago

martinszeltins commented 4 months ago

Describe the feature

Currently in the docs there is a Usage example for how to create a WebSocket Nitro route: https://nitro.unjs.io/guide/websocket#usage but there is no example for server-sent events and how to create a Nuxt/Nitro route for that. There is an example in h3 docs but not in Nitro.

It would be very useful to create such usage example also for SSE (Server-sent events) just like WebSockets example.

Create a websocket handler in routes/_ws.ts

export default defineWebSocketHandler({
open(peer) { ... },
message(peer, message) { ... },
close(peer, event) { ... },
})

Additional information

martinszeltins commented 4 months ago

@pi0 This is what we talked about in this gist.

pi0 commented 4 months ago

Thanks for the issue ❤️ Feel free to contribute to the docs by making a PR.

martinszeltins commented 4 months ago

Thanks for the issue ❤️ Feel free to contribute to the docs by making a PR.

@pi0 To be honest, I am not entirely sure what the usage should be. You mentioned that the usage is the same as in h3 but in a Nuxt/Nitro server route there is usually some kind of an event handler like in the example of @Atinux SSE endpoint example with Nuxt 3 gist

// ~/server/api/sse.ts
export default defineEventHandler(async (event) => {
  // ...
})

And then the client can connect to the route endpoint

// client code
const sse = new EventSource('/api/sse')
pi0 commented 4 months ago

Simply like this https://stackblitz.com/edit/github-lku74j?file=server%2Froutes%2Findex.ts

And you can either render it directly or connect with an eventsource client.

you can also use useNitroApp().hooks to use global hooks but i guess for sake of example we probably don't want to complicate it.

martinszeltins commented 4 months ago

Simply like this stackblitz.com/edit/github-lku74j?file=server%2Froutes%2Findex.ts

And you can either render it directly or connect with an eventsource client.

you can also use useNitroApp().hooks to use global hooks but i guess for sake of example we probably don't want to complicate it.

Works like a charm, tested also with Nuxt. I will send in pull request to update the docs.

Pull Request: https://github.com/unjs/nitro/pull/2379

SelfhostedPro commented 4 months ago

Have an example of SSE working here in a real world app if that's beneficial at all:

https://github.com/SelfhostedPro/yacht-nuxt/blob/main/modules/notifications/runtime/server/composables/sse.ts

Has some stuff around Auth too and creating unique sessions for if you don't want all the events on every SSE connection.