nuxt / rfcs

RFCs for changes to Nuxt.js
99 stars 2 forks source link

@nuxt/sse: Server-sent Events for Nuxt #36

Closed atinux closed 3 years ago

atinux commented 5 years ago

Introduction

Introducing a Server-sent events module for Nuxt to let serverMiddleware and functions to send events to the Nuxt app.

An instance will be available with nuxt.$sse to send events.

nuxt.config.js:

import fetch from 'node-fetch'

export default {
  hooks: {
   ready(nuxt) {
      setInterval(async () => {
         const tweets = await fetch(`https://api.example.com/tweets?from=${Date.now()-2000}`).then(res => res.json())
         tweets.forEach(tweet => nuxt.$sse.broadcast('tweet', tweet))
      }, 2000)
    }
  }
}

On the app side, it will expose a $sse instance with .on('eventName', fn).

pages/tweets.vue:

<template>
  <ul>
     <li v-for="tweet of tweets">...</li>
  </ul>
</template>

<script>
export default {
  async asyncData() {
     const tweets = await fetch('/api/tweets').then(res => res.json())

     return { tweets }
  }},
  mounted() {
    this.$sse.on('tweet', (tweet) => this.tweets.unshift(tweet))
  }
}
</script>

How does it work?

@nuxt/sse will:

  1. Create a serverMiddleware on /_nuxt/sse (see more here)
  2. Inject nuxt.$sse
  3. Inject $sse in the Nuxt app on client-side with this.addPlugin + auto connect + customisable with a custom endpoint

With this system, modules author could inject this module to add some realtime data to the Nuxt app easily šŸš€

PS: 0 breaking change šŸ˜‡

DreaMinder commented 5 years ago

Woah, it looks awesome! But one thing should be kept in mind: SSE is kind of abandoned technology: https://github.com/whatwg/html/issues/2177#issuecomment-332071504

Maybe someday it will need to be rewritten to Fetch API implementation (according to the link). For example to enable auth-headers support.

atinux commented 5 years ago

That's pretty sad, I see really nice progress with SSE and great advantages VS sockets.

There is also a promising project: https://github.com/dunglas/mercure

Amaurgit commented 4 years ago

So, no nuxt/sse ? :) I got a :

EventSource's response has a MIME type ("application/json") that is not "text/event-stream". Aborting the connection.

because of the webpack HMR I guess. Any update on this ? :)

atinux commented 3 years ago

I think this may not be added because of serverless support.

linqFR commented 3 years ago

Hello @Atinux

any doc anywhere about sse?

atinux commented 3 years ago

This is tricky since it depends of a Node.js server, take a look at tutorials for node such as https://www.digitalocean.com/community/tutorials/nodejs-server-sent-events-build-realtime-app

lewebsimple commented 2 years ago

Just wanted to link this issue with my current progress at using SSE in Nuxt3. Basically I'm stuck because unjs/h3 seems to close the connection no matter what I do.

See this issue and reproduction repository for details.