HTML Streaming

HTML Streaming support is a beta feature.

Breaking changes may be introduced in any version update; make to sure to pin your dependency to vite-plugin-ssr.

HTML Streams have first-class support.

// _deault.page.server.js

import { escapeInject, pipeNodeStream, pipeWebStream } from 'vite-plugin-ssr'
import {
  renderToNodeStream,
  renderToWebStream,
  pipeToNodeWritable,
  pipeToWebWritable
} from 'some-view-framework' // E.g. Vue or React

export { render }

async function render(pageContext) {
  const { Page } = pageContext

  const stream = renderToNodeStream(Page)

  // Or with a pipe:
  const stream = pipeNodeStream(writable => {
    pipeToNodeWritable(Page, writable)
  })

  // Or with a Web Stream:
  const stream = renderToWebStream(Page)
  // Or:
  const stream = pipeWebStream(writable => {
    pipeToWebWritable(Page, writable)
  })

  return escapeInject`<!DOCTYPE html>
    <html>
      <body>
        <div id="page-view">${stream}</div>
      </body>
    </html>`
}
// server.js

app.get("*", async (req, res, next) => {
  const pageContextInit = { url: req.url }
  const pageContext = await renderPage(pageContextInit)
  const { httpResponse } = pageContext
  if (!httpResponse) return next()

  httpResponse.bodyNodeStream.pipe(res)

  // Or with a pipe:
  httpResponse.bodyPipeToNodeWritable(res)

  // Or with a Web Stream:
  httpResponse.bodyWebStream.pipe(res)
  // Or:
  httpResponse.bodyPipeToWebWritable(res)

  // We can also convert the stream to a string by using `httpResponse.getBody()`
  const body = await httpResponse.getBody()
  res.send(body)
  /* Note that this won't work:
  const { body } = httpResponse
  res.send(body)
  */
})

Streams API Docs:

Examples:

Edit this page