Skip to content

How to stream text with NextJS v14 from server component to client component ? #67501

Answered by mutasim77
aestheticsdata asked this question in Help
Discussion options

You must be logged in to vote

I had a tiny demo example for this streaming data. Here, I will provide it, and you can play with it. Using the same idea, you can do it with ChatGPT api as well. Here's how to set it up:
Creat a new API route app/api/stream/route.ts and add this:

import { NextResponse } from 'next/server'

export async function GET() {
  const response = await fetch('https://baconipsum.com/api/?type=all-meat&paras=3&start-with-lorem=1&format=json')
  const data = await response.json()
  const text = data.join(' ')

  const encoder = new TextEncoder()
  const stream = new ReadableStream({
    async start(controller) {
      const words = text.split(' ')
      for (let word of words) {
        const chunk = 

Replies: 1 comment 4 replies

Comment options

You must be logged in to vote
4 replies
@aestheticsdata
Comment options

@aestheticsdata
Comment options

@mutasim77
Comment options

@aestheticsdata
Comment options

Answer selected by aestheticsdata
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Help
Labels
None yet
2 participants