diff --git a/docs/1.getting-started/6.data-fetching.md b/docs/1.getting-started/6.data-fetching.md index 32976b1f29..84b36df3bf 100644 --- a/docs/1.getting-started/6.data-fetching.md +++ b/docs/1.getting-started/6.data-fetching.md @@ -623,3 +623,37 @@ const { data } = await useFetch('/api/superjson', { }) ``` + +## Recipes + +### Consuming SSE (Server Sent Events) via POST request + +::tip +If you're consuming SSE via GET request, you can use [`EventSource`](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) or VueUse composable [`useEventSource`](https://vueuse.org/core/useEventSource/). +:: + +When consuming SSE via POST request, you need to handle the connection manually. Here's how you can do it: + +```ts +// Make a POST request to the SSE endpoint +const response = await $fetch('/chats/ask-ai', { + method: 'POST', + body: { + query: "Hello AI, how are you?", + }, + responseType: 'stream', +}) + +// Create a new ReadableStream from the response with TextDecoderStream to get the data as text +const reader = response.pipeThrough(new TextDecoderStream()).getReader() + +// Read the chunk of data as we get it +while (true) { + const { value, done } = await reader.read() + + if (done) + break + + console.log('Received:', value) +} +```