Skip to content

Streaming support #396

Closed
Closed

Description

@harlan-zw

Describe the feature

Related: #27

Most SSR js frameworks are streamable, we should support the same functionality with Unhead.

There is workarounds available but we should have an official solution that is documented.

Solving the Head Issue in Streaming HTML with Unhead

The Problem

Streaming HTML is sending content to the browser as it's created rather than waiting for the entire page to be ready. This approach has significant benefits:

  • Faster time to first byte
  • Lower server memory overhead
  • Progressive browser rendering
  • Better user experience with visible progress

However, there's a core challenge with the <head> section:

  1. The <head> needs to be sent early in the response
  2. Many <head> elements (like <title>) depend on data that isn't immediately available
  3. Waiting for this data defeats the purpose of streaming

Out-of-Order Streaming: The Solution

Instead of blocking the entire stream waiting for <head> data, we can use an approach called "out-of-order streaming":

  1. Stream a placeholder <head> immediately
  2. Continue streaming the rest of the page
  3. Update the <head> content later when data becomes available

Additional information

  • Would you be willing to help implement this feature?

Activity

  1. added
    enhancement
    on Sep 7, 2024
  2. negezor commented on Sep 8, 2024

    @negezor
    Contributor

    The problem is that the whole application has to be pre-processed. Since we can't know what hooks/components will be called. The DOM elements themselves can only be inserted at the end of <body> or make a buffer to insert in <head>, which makes no sense in streaming. However, many web crawlers do not look beyond </head>, which makes SSR meaningless for SEO.

  3. harlan-zw commented on Sep 8, 2024

    @harlan-zw
    CollaboratorAuthor

    Yes, the idea is most likely a sync API for v2 that does not support hooks. I need to investigate it more but I believe we could just push the raw tags as json and resolve them client-side.

    The exact use case for this is a bit niche though and needs some more thought.

  4. birkskyum commented on Mar 31, 2025

    @birkskyum

    With unhead v2 out the door, i wonder, whats the status on streaming SSR? In TanStack Start (in beta), we're trying to find the best solution for controlling the head tags, and for e.g. Solid we currently use @solidjs/meta. If unhead can offer a consistent api across frameworks, i'd be happy to explore that.

  5. harlan-zw commented on Mar 31, 2025

    @harlan-zw
    CollaboratorAuthor

    We can solve it similarly to React (?), in which we delay stream chunks until we hit a suspense boundary. Using an arbitrary delay may be needed, though, as I don't think any framework exposes this at the ssr level (?).

    Here's a code sample in Vue or you can check out the vite-ssr-streaming-vue example.

    export async function headStream(res, vueStream, htmlStart, htmlEnd, head) {
      res.status(200).set({
        'Content-Type': 'text/html; charset=utf-8'
      })
    
      let bufferChunks = []
      let flushTimer = null
      let isStreaming = false 
    
      async function writeFirstChunk() {
        const s = Buffer.from(bufferChunks).toString('utf8')
        bufferChunks = []
        const headHtml = await renderSSRHead(head)
        res.write((htmlStart.replace('</head>', `${headHtml.headTags}</head>`) + s))
      }
    
      for await (const chunk of vueStream) {
        if (res.closed) break
    
        if (isStreaming) {
          res.write(chunk)
          continue
        }
    
        bufferChunks.push(...chunk)
    
        if (flushTimer) clearTimeout(flushTimer)
    
        flushTimer = setTimeout(async () => {
          isStreaming = true
          if (bufferChunks.length > 0) {
            await writeFirstChunk()
          }
        }, 3) // 3ms of not sending chunks - we must be in a Suspense boundary !
      }
    
      if (bufferChunks.length > 0) {
        await writeFirstChunk()
      }
    
      const headHtml = await renderSSRHead(head)
      res.write((htmlEnd.replace('</body>', `${headHtml.bodyTags}</body>`)))
      res.end()
    }

    The slightly more challenging part is what to do about head usage within Suspense boundaries, I don't think this is terribly difficult, just a bit unstable. We can simply render these tags inline (if we can safely avoid hydration errors) or they can be used outside of the <head> next to the </body> tag.

    It would just require some fixes to the DOM renderer to dedupe outside of where the tag was trying to be rendered (i.e <head>)

    As @negezor mentioned though, I don't think there's a foolproof way to handle streaming that is good for SEO. I'm not sure how a <title> or <meta> tag within a suspense would ever work 🤔

    Happy to look into these if it's blocking a framework integration.

  6. harlan-zw commented on Apr 1, 2025

    @harlan-zw
    CollaboratorAuthor

    I think likely meta frameworks can filter for bots and do non-streaming responses so this is probably a non-issue.

  7. birkskyum commented on Apr 11, 2025

    @birkskyum

    I think likely meta frameworks can filter for bots and do non-streaming responses so this is probably a non-issue.

    It is blocking - because supporting streaming is critical for most meta frameworks these days.

  8. harlan-zw commented on Apr 12, 2025

    @harlan-zw
    CollaboratorAuthor

    I'm saying that if SEO is an issue then the meta framework themselves can opt out based on user agent headers, it's not blocking the development of the feature.

  9. birkskyum commented on Jan 5, 2026

    @birkskyum
  10. harlan-zw commented on Jan 6, 2026

    @harlan-zw
    CollaboratorAuthor

    Yes, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementv2

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions