diff --git a/e2e/react-start/streaming-ssr/tests/fast-serial.spec.ts b/e2e/react-start/streaming-ssr/tests/fast-serial.spec.ts
index 339d6408ea..53e4d875b0 100644
--- a/e2e/react-start/streaming-ssr/tests/fast-serial.spec.ts
+++ b/e2e/react-start/streaming-ssr/tests/fast-serial.spec.ts
@@ -16,6 +16,21 @@ test.describe('Fast serialization (serialization completes before render)', () =
     expect(responseHtml).toContain('$_TSR.router')
     expect(responseHtml).toContain('$_TSR.e()')
     expect(responseHtml).toContain('$tsr-stream-barrier')
+
+    // Router scripts and end marker must be injected before closing tags.
+    const bodyCloseIndex = responseHtml.lastIndexOf('</body>')
+    const htmlCloseIndex = responseHtml.lastIndexOf('</html>')
+    const barrierIndex = responseHtml.indexOf('$tsr-stream-barrier')
+    const endMarkerIndex = responseHtml.indexOf('$_TSR.e()')
+
+    expect(bodyCloseIndex).toBeGreaterThan(-1)
+    expect(htmlCloseIndex).toBeGreaterThan(-1)
+    expect(barrierIndex).toBeGreaterThan(-1)
+    expect(endMarkerIndex).toBeGreaterThan(-1)
+
+    expect(barrierIndex).toBeLessThan(bodyCloseIndex)
+    expect(endMarkerIndex).toBeLessThan(bodyCloseIndex)
+    expect(endMarkerIndex).toBeLessThan(htmlCloseIndex)
   })
 
   test('all data is available immediately', async ({ page }) => {
diff --git a/e2e/react-start/streaming-ssr/tests/sync-only.spec.ts b/e2e/react-start/streaming-ssr/tests/sync-only.spec.ts
index a0060a07ee..31473e6a99 100644
--- a/e2e/react-start/streaming-ssr/tests/sync-only.spec.ts
+++ b/e2e/react-start/streaming-ssr/tests/sync-only.spec.ts
@@ -68,6 +68,21 @@ test('Sync-only route has bootstrap scripts in initial HTML', async ({
   // SSR should include the barrier script tag in the HTML (rendered by <Scripts />)
   // This is the critical marker transformStreamWithRouter can scan for.
   expect(responseHtml).toContain('$tsr-stream-barrier')
+
+  // Router scripts and end marker must be injected before closing tags.
+  const bodyCloseIndex = responseHtml.lastIndexOf('</body>')
+  const htmlCloseIndex = responseHtml.lastIndexOf('</html>')
+  const barrierIndex = responseHtml.indexOf('$tsr-stream-barrier')
+  const endMarkerIndex = responseHtml.indexOf('$_TSR.e()')
+
+  expect(bodyCloseIndex).toBeGreaterThan(-1)
+  expect(htmlCloseIndex).toBeGreaterThan(-1)
+  expect(barrierIndex).toBeGreaterThan(-1)
+  expect(endMarkerIndex).toBeGreaterThan(-1)
+
+  expect(barrierIndex).toBeLessThan(bodyCloseIndex)
+  expect(endMarkerIndex).toBeLessThan(bodyCloseIndex)
+  expect(endMarkerIndex).toBeLessThan(htmlCloseIndex)
 })
 
 test('Navigating to sync-only from home page', async ({ page }) => {
diff --git a/packages/router-core/package.json b/packages/router-core/package.json
index f61fe1f43e..b6692fed6f 100644
--- a/packages/router-core/package.json
+++ b/packages/router-core/package.json
@@ -31,6 +31,11 @@
     "test:build": "publint --strict && attw --ignore-rules no-resolution --pack .",
     "test:unit": "vitest",
     "test:unit:dev": "pnpm run test:unit --watch",
+    "bench:transform-stream": "vitest bench tests/transformStreamWithRouter.bench.ts",
+    "bench:transform-stream:prof": "pnpm dlx @platformatic/flame run --md-format=detailed ../../node_modules/vitest/vitest.mjs bench tests/transformStreamWithRouter.bench.ts",
+    "profile:transform-stream": "pnpm build && pnpm run profile:transform-stream:run:prof",
+    "profile:transform-stream:run": "node ./tests/transformStreamWithRouter.profile.mjs",
+    "profile:transform-stream:run:prof": "pnpm dlx @platformatic/flame run --delay=none --md-format=detailed ./tests/transformStreamWithRouter.profile.mjs",
     "build": "vite build"
   },
   "type": "module",
diff --git a/packages/router-core/src/ssr/ssr-server.ts b/packages/router-core/src/ssr/ssr-server.ts
index 8cea703eeb..9ebd513ffa 100644
--- a/packages/router-core/src/ssr/ssr-server.ts
+++ b/packages/router-core/src/ssr/ssr-server.ts
@@ -91,13 +91,8 @@ class ScriptBuffer {
   liftBarrier() {
     if (this._scriptBarrierLifted || this._cleanedUp) return
     this._scriptBarrierLifted = true
-    if (this._queue.length > 0 && !this._pendingMicrotask) {
-      this._pendingMicrotask = true
-      queueMicrotask(() => {
-        this._pendingMicrotask = false
-        this.injectBufferedScripts()
-      })
-    }
+    this._pendingMicrotask = false
+    this.injectBufferedScripts()
   }
 
   /**
@@ -274,15 +269,24 @@ export function attachRouterServerSsrUtils({
         : defaultSerovalPlugins
 
       const signalSerializationComplete = () => {
+        if (_serializationFinished) return
         _serializationFinished = true
+
+        const listeners = serializationFinishedListeners.slice()
+
+        for (const listener of listeners) {
+          try {
+            listener()
+          } catch (err) {
+            console.error('Serialization listener error:', err)
+          }
+        }
         try {
-          serializationFinishedListeners.forEach((l) => l())
           router.emit({ type: 'onSerializationFinished' })
         } catch (err) {
-          console.error('Serialization listener error:', err)
+          console.error('Error emitting onSerializationFinished:', err)
         } finally {
           serializationFinishedListeners.length = 0
-          renderFinishedListeners.length = 0
         }
       }
 
@@ -320,16 +324,19 @@ export function attachRouterServerSsrUtils({
     onSerializationFinished: (listener) =>
       serializationFinishedListeners.push(listener),
     setRenderFinished: () => {
-      // Wrap in try-catch to ensure scriptBuffer.liftBarrier() is always called
-      try {
-        renderFinishedListeners.forEach((l) => l())
-      } catch (err) {
-        console.error('Error in render finished listener:', err)
-      } finally {
-        // Clear listeners after calling them to prevent memory leaks
-        renderFinishedListeners.length = 0
+      const listeners = renderFinishedListeners.slice()
+      renderFinishedListeners.length = 0
+
+      for (const listener of listeners) {
+        try {
+          listener()
+        } catch (err) {
+          console.error('Error in render finished listener:', err)
+        }
       }
+
       scriptBuffer.liftBarrier()
+      scriptBuffer.flush()
     },
     takeBufferedScripts() {
       const scripts = scriptBuffer.takeAll()
@@ -396,7 +403,7 @@ export function getOrigin(request: Request) {
 // chromium treats search params differently than paths, i.e. "|" is not encoded in search params.
 export function getNormalizedURL(url: string | URL, base?: string | URL) {
   // ensure backslashes are encoded correctly in the URL
-  if (typeof url === 'string') url = url.replace('\\', '%5C')
+  if (typeof url === 'string') url = url.replace(/\\/g, '%5C')
 
   const rawUrl = new URL(url, base)
   const { path: decodedPathname, handledProtocolRelativeURL } = decodePath(
diff --git a/packages/router-core/src/ssr/transformStreamWithRouter.ts b/packages/router-core/src/ssr/transformStreamWithRouter.ts
index 99fe436256..2ac6292c5c 100644
--- a/packages/router-core/src/ssr/transformStreamWithRouter.ts
+++ b/packages/router-core/src/ssr/transformStreamWithRouter.ts
@@ -1,5 +1,6 @@
 import { ReadableStream } from 'node:stream/web'
 import { Readable } from 'node:stream'
+import { isAscii } from 'node:buffer'
 import { TSR_SCRIPT_BARRIER_ID } from './constants'
 import type { AnyRouter } from '../router'
 
@@ -21,7 +22,7 @@ export function transformPipeableStreamWithRouter(
 
 // Use string constants for simple indexOf matching
 const BODY_END_TAG = '</body>'
-const HTML_END_TAG = '</html>'
+const SCRIPT_END_TAG = '</script>'
 
 // Minimum length of a valid closing tag: </a> = 4 characters
 const MIN_CLOSING_TAG_LENGTH = 4
@@ -30,9 +31,6 @@ const MIN_CLOSING_TAG_LENGTH = 4
 const DEFAULT_SERIALIZATION_TIMEOUT_MS = 60000
 const DEFAULT_LIFETIME_TIMEOUT_MS = 60000
 
-// Module-level encoder (stateless, safe to reuse)
-const textEncoder = new TextEncoder()
-
 /**
  * Finds the position just after the last valid HTML closing tag in the string.
  *
@@ -97,6 +95,128 @@ function findLastClosingTagEnd(str: string): number {
   return -1
 }
 
+type StreamPhase = 'streaming' | 'appDone' | 'finished'
+type BarrierPhase = 'locked' | 'lifted'
+type TailPhase = 'normal' | 'afterBody'
+
+type StreamLifecycle = {
+  stream: ReadableStream<Uint8Array>
+  setReader: (reader: ReadableStreamDefaultReader | undefined) => void
+  isClosed: () => boolean
+  isCleanedUp: () => boolean
+  safeEnqueue: (chunk: string | Uint8Array) => void
+  safeClose: () => void
+  safeError: (error: unknown) => void
+  cleanup: () => void
+}
+
+function createStreamLifecycle(opts: {
+  router: AnyRouter
+  lifetimeMs: number
+  withLifetimeTimeout?: boolean
+  onCleanup?: () => void
+}): StreamLifecycle {
+  const withLifetimeTimeout = opts.withLifetimeTimeout ?? true
+  let cleanedUp = false
+  let isStreamClosed = false
+  let controller: ReadableStreamDefaultController<Uint8Array> | undefined
+  let appReader: ReadableStreamDefaultReader | undefined
+  let lifetimeTimeoutHandle: ReturnType<typeof setTimeout> | undefined
+
+  const cancelActiveReader = (reason?: unknown) => {
+    const activeReader = appReader
+    appReader = undefined
+    void activeReader?.cancel(reason).catch(() => {
+      // ignore
+    })
+  }
+
+  const safeEnqueue = (chunk: string | Uint8Array) => {
+    if (isStreamClosed) return
+    if (typeof chunk === 'string') {
+      controller?.enqueue(Buffer.from(chunk, 'utf8'))
+    } else {
+      controller?.enqueue(chunk)
+    }
+  }
+
+  const safeClose = () => {
+    if (isStreamClosed) return
+    isStreamClosed = true
+    try {
+      controller?.close()
+    } catch {
+      // ignore
+    }
+  }
+
+  const safeError = (error: unknown) => {
+    if (isStreamClosed) return
+    isStreamClosed = true
+    try {
+      controller?.error(error)
+    } catch {
+      // ignore
+    }
+  }
+
+  const cleanup = () => {
+    if (cleanedUp) return
+    cleanedUp = true
+
+    cancelActiveReader()
+
+    if (lifetimeTimeoutHandle !== undefined) {
+      clearTimeout(lifetimeTimeoutHandle)
+      lifetimeTimeoutHandle = undefined
+    }
+
+    try {
+      opts.onCleanup?.()
+    } catch {
+      // ignore
+    }
+
+    opts.router.serverSsr?.cleanup()
+  }
+
+  const stream = new ReadableStream<Uint8Array>({
+    start(c) {
+      controller = c
+    },
+    cancel(reason) {
+      isStreamClosed = true
+      cancelActiveReader(reason)
+      cleanup()
+    },
+  })
+
+  if (withLifetimeTimeout) {
+    lifetimeTimeoutHandle = setTimeout(() => {
+      if (!cleanedUp && !isStreamClosed) {
+        console.warn(
+          `SSR stream transform exceeded maximum lifetime (${opts.lifetimeMs}ms), forcing cleanup`,
+        )
+        safeError(new Error('Stream lifetime exceeded'))
+        cleanup()
+      }
+    }, opts.lifetimeMs)
+  }
+
+  return {
+    stream,
+    setReader: (reader) => {
+      appReader = reader
+    },
+    isClosed: () => isStreamClosed,
+    isCleanedUp: () => cleanedUp,
+    safeEnqueue,
+    safeClose,
+    safeError,
+    cleanup,
+  }
+}
+
 export function transformStreamWithRouter(
   router: AnyRouter,
   appStream: ReadableStream,
@@ -115,111 +235,77 @@ export function transformStreamWithRouter(
   // Take any HTML that was buffered before we started listening
   const initialBufferedHtml = router.serverSsr?.takeBufferedHtml()
 
+  const lifetimeMs = opts?.lifetimeMs ?? DEFAULT_LIFETIME_TIMEOUT_MS
+
   // True passthrough: if serialization already finished and nothing buffered,
   // we can avoid any decoding/scanning while still honoring cleanup + setRenderFinished.
   if (serializationAlreadyFinished && !initialBufferedHtml) {
-    let cleanedUp = false
-    let controller: ReadableStreamDefaultController<Uint8Array> | undefined
-    let isStreamClosed = false
-    let lifetimeTimeoutHandle: ReturnType<typeof setTimeout> | undefined
-
-    const cleanup = () => {
-      if (cleanedUp) return
-      cleanedUp = true
-
-      if (lifetimeTimeoutHandle !== undefined) {
-        clearTimeout(lifetimeTimeoutHandle)
-        lifetimeTimeoutHandle = undefined
-      }
-
-      router.serverSsr?.cleanup()
-    }
-
-    const safeClose = () => {
-      if (isStreamClosed) return
-      isStreamClosed = true
-      try {
-        controller?.close()
-      } catch {
-        // ignore
-      }
-    }
-
-    const safeError = (error: unknown) => {
-      if (isStreamClosed) return
-      isStreamClosed = true
-      try {
-        controller?.error(error)
-      } catch {
-        // ignore
-      }
-    }
-
-    const lifetimeMs = opts?.lifetimeMs ?? DEFAULT_LIFETIME_TIMEOUT_MS
-    lifetimeTimeoutHandle = setTimeout(() => {
-      if (!cleanedUp && !isStreamClosed) {
-        console.warn(
-          `SSR stream transform exceeded maximum lifetime (${lifetimeMs}ms), forcing cleanup`,
-        )
-        safeError(new Error('Stream lifetime exceeded'))
-        cleanup()
-      }
-    }, lifetimeMs)
-
-    const stream = new ReadableStream<Uint8Array>({
-      start(c) {
-        controller = c
-      },
-      cancel() {
-        isStreamClosed = true
-        cleanup()
-      },
+    const lifecycle = createStreamLifecycle({
+      router,
+      lifetimeMs,
+      withLifetimeTimeout: true,
     })
 
     ;(async () => {
       const reader = appStream.getReader()
+      lifecycle.setReader(reader)
       try {
         while (true) {
           const { done, value } = await reader.read()
           if (done) break
-          if (cleanedUp || isStreamClosed) return
-          controller?.enqueue(value as unknown as Uint8Array)
+          if (lifecycle.isCleanedUp() || lifecycle.isClosed()) return
+
+          if (typeof value === 'string') {
+            lifecycle.safeEnqueue(value)
+          } else {
+            lifecycle.safeEnqueue(value as Uint8Array)
+          }
         }
 
-        if (cleanedUp || isStreamClosed) return
+        if (lifecycle.isCleanedUp() || lifecycle.isClosed()) return
 
         router.serverSsr?.setRenderFinished()
-        safeClose()
-        cleanup()
+        lifecycle.safeClose()
+        lifecycle.cleanup()
       } catch (error) {
-        if (cleanedUp) return
+        if (lifecycle.isCleanedUp()) return
         console.error('Error reading appStream:', error)
         router.serverSsr?.setRenderFinished()
-        safeError(error)
-        cleanup()
+        lifecycle.safeError(error)
+        lifecycle.cleanup()
       } finally {
-        reader.releaseLock()
+        lifecycle.setReader(undefined)
       }
     })().catch((error) => {
-      if (cleanedUp) return
+      if (lifecycle.isCleanedUp()) return
       console.error('Error in stream transform:', error)
-      safeError(error)
-      cleanup()
+      lifecycle.safeError(error)
+      lifecycle.cleanup()
     })
 
-    return stream
+    return lifecycle.stream
+  }
+
+  type TransformState = {
+    streamPhase: StreamPhase
+    barrierPhase: BarrierPhase
+    tailPhase: TailPhase
+    serializationDone: boolean
+  }
+
+  const state: TransformState = {
+    streamPhase: 'streaming',
+    barrierPhase: 'locked',
+    tailPhase: 'normal',
+    serializationDone: serializationAlreadyFinished,
   }
 
   let stopListeningToInjectedHtml: (() => void) | undefined
   let stopListeningToSerializationFinished: (() => void) | undefined
   let serializationTimeoutHandle: ReturnType<typeof setTimeout> | undefined
-  let lifetimeTimeoutHandle: ReturnType<typeof setTimeout> | undefined
-  let cleanedUp = false
-
-  let controller: ReadableStreamDefaultController<any>
-  let isStreamClosed = false
 
   const textDecoder = new TextDecoder()
+  let usedBinaryDecoder = false
 
   // concat'd router HTML; avoids array joins on each flush
   let pendingRouterHtml = initialBufferedHtml ?? ''
@@ -227,90 +313,41 @@ export function transformStreamWithRouter(
   // between-chunk text buffer; keep bounded to avoid unbounded memory
   let leftover = ''
 
-  // captured closing tags from </body> onward
+  // captured closing tags and trailing tail from </body> onward
   let pendingClosingTags = ''
 
   // conservative cap: enough to hold any partial closing tag + a bit
   const MAX_LEFTOVER_CHARS = 2048
 
-  let isAppRendering = true
-  let streamBarrierLifted = false
-  let serializationFinished = serializationAlreadyFinished
-
-  function safeEnqueue(chunk: string | Uint8Array) {
-    if (isStreamClosed) return
-    if (typeof chunk === 'string') {
-      controller.enqueue(textEncoder.encode(chunk))
-    } else {
-      controller.enqueue(chunk)
-    }
-  }
-
-  function safeClose() {
-    if (isStreamClosed) return
-    isStreamClosed = true
-    try {
-      controller.close()
-    } catch {
-      // ignore
-    }
-  }
-
-  function safeError(error: unknown) {
-    if (isStreamClosed) return
-    isStreamClosed = true
-    try {
-      controller.error(error)
-    } catch {
-      // ignore
-    }
-  }
-
-  /**
-   * Cleanup with guards; must be idempotent.
-   */
-  function cleanup() {
-    if (cleanedUp) return
-    cleanedUp = true
-
-    try {
-      stopListeningToInjectedHtml?.()
-      stopListeningToSerializationFinished?.()
-    } catch {
-      // ignore
-    }
-    stopListeningToInjectedHtml = undefined
-    stopListeningToSerializationFinished = undefined
-
-    if (serializationTimeoutHandle !== undefined) {
-      clearTimeout(serializationTimeoutHandle)
-      serializationTimeoutHandle = undefined
-    }
-    if (lifetimeTimeoutHandle !== undefined) {
-      clearTimeout(lifetimeTimeoutHandle)
-      lifetimeTimeoutHandle = undefined
-    }
-
-    pendingRouterHtml = ''
-    leftover = ''
-    pendingClosingTags = ''
+  const lifecycle = createStreamLifecycle({
+    router,
+    lifetimeMs,
+    withLifetimeTimeout: true,
+    onCleanup: () => {
+      try {
+        stopListeningToInjectedHtml?.()
+        stopListeningToSerializationFinished?.()
+      } catch {
+        // ignore
+      }
+      stopListeningToInjectedHtml = undefined
+      stopListeningToSerializationFinished = undefined
 
-    router.serverSsr?.cleanup()
-  }
+      if (serializationTimeoutHandle !== undefined) {
+        clearTimeout(serializationTimeoutHandle)
+        serializationTimeoutHandle = undefined
+      }
 
-  const stream = new ReadableStream({
-    start(c) {
-      controller = c
-    },
-    cancel() {
-      isStreamClosed = true
-      cleanup()
+      pendingRouterHtml = ''
+      leftover = ''
+      pendingClosingTags = ''
     },
   })
 
-  function flushPendingRouterHtml() {
+  function flushPendingRouterHtml(force = false) {
     if (!pendingRouterHtml) return
-    safeEnqueue(pendingRouterHtml)
+    if (!force && state.barrierPhase === 'locked') return
+    lifecycle.safeEnqueue(pendingRouterHtml)
     pendingRouterHtml = ''
   }
 
@@ -323,8 +360,8 @@ export function transformStreamWithRouter(
    * Finish only when app done and serialization complete.
    */
   function tryFinish() {
-    if (isAppRendering || !serializationFinished) return
-    if (cleanedUp || isStreamClosed) return
+    if (state.streamPhase === 'streaming' || !state.serializationDone) return
+    if (lifecycle.isCleanedUp() || lifecycle.isClosed()) return
 
     if (serializationTimeoutHandle !== undefined) {
       clearTimeout(serializationTimeoutHandle)
@@ -332,48 +369,39 @@ export function transformStreamWithRouter(
     }
 
     // Flush any remaining bytes in the TextDecoder
-    const decoderRemainder = textDecoder.decode()
-
-    if (leftover) safeEnqueue(leftover)
-    if (decoderRemainder) safeEnqueue(decoderRemainder)
-    flushPendingRouterHtml()
-    if (pendingClosingTags) safeEnqueue(pendingClosingTags)
-
-    safeClose()
-    cleanup()
+    const decoderRemainder = usedBinaryDecoder ? textDecoder.decode() : ''
+
+    if (leftover) lifecycle.safeEnqueue(leftover)
+    if (decoderRemainder) lifecycle.safeEnqueue(decoderRemainder)
+    flushPendingRouterHtml(true)
+    if (pendingClosingTags) lifecycle.safeEnqueue(pendingClosingTags)
+    state.streamPhase = 'finished'
+    lifecycle.safeClose()
+    lifecycle.cleanup()
   }
 
-  // Safety net: cleanup even if consumer never reads
-  const lifetimeMs = opts?.lifetimeMs ?? DEFAULT_LIFETIME_TIMEOUT_MS
-  lifetimeTimeoutHandle = setTimeout(() => {
-    if (!cleanedUp && !isStreamClosed) {
-      console.warn(
-        `SSR stream transform exceeded maximum lifetime (${lifetimeMs}ms), forcing cleanup`,
-      )
-      safeError(new Error('Stream lifetime exceeded'))
-      cleanup()
-    }
-  }, lifetimeMs)
-
   if (!serializationAlreadyFinished) {
     stopListeningToInjectedHtml = router.subscribe('onInjectedHtml', () => {
-      if (cleanedUp || isStreamClosed) return
+      if (lifecycle.isCleanedUp() || lifecycle.isClosed()) return
       const html = router.serverSsr?.takeBufferedHtml()
       if (!html) return
 
-      // If we've already captured </body> (pendingClosingTags), we must keep appending
-      // so injection stays before the stored closing tags.
-      if (isAppRendering || leftover || pendingClosingTags) {
+      if (
+        state.barrierPhase === 'locked' ||
+        state.streamPhase === 'streaming' ||
+        leftover ||
+        state.tailPhase === 'afterBody'
+      ) {
         appendRouterHtml(html)
       } else {
-        safeEnqueue(html)
+        lifecycle.safeEnqueue(html)
       }
     })
 
     stopListeningToSerializationFinished = router.subscribe(
       'onSerializationFinished',
       () => {
-        serializationFinished = true
+        state.serializationDone = true
         tryFinish()
       },
     )
@@ -382,61 +410,123 @@ export function transformStreamWithRouter(
   // Transform the appStream
   ;(async () => {
     const reader = appStream.getReader()
+    lifecycle.setReader(reader)
     try {
       while (true) {
         const { done, value } = await reader.read()
         if (done) break
 
-        if (cleanedUp || isStreamClosed) return
+        if (lifecycle.isCleanedUp() || lifecycle.isClosed()) return
+
+        const rawUint8Chunk = value instanceof Uint8Array ? value : undefined
 
-        const text =
-          value instanceof Uint8Array
-            ? textDecoder.decode(value, { stream: true })
-            : String(value)
+        if (
+          rawUint8Chunk &&
+          !leftover &&
+          !pendingRouterHtml &&
+          state.tailPhase === 'normal' &&
+          state.barrierPhase === 'lifted'
+        ) {
+          if (rawUint8Chunk.indexOf(60) === -1) {
+            lifecycle.safeEnqueue(rawUint8Chunk)
+            continue
+          }
+        }
+
+        let text: string
+        if (typeof value === 'string') {
+          text = value
+        } else if (ArrayBuffer.isView(value)) {
+          const view = value as Uint8Array
+          if (!isAscii(view)) {
+            usedBinaryDecoder = true
+            text = textDecoder.decode(view, { stream: true })
+          } else {
+            text = Buffer.from(
+              view.buffer,
+              view.byteOffset,
+              view.byteLength,
+            ).toString('utf8')
+          }
+        } else {
+          text = String(value)
+        }
 
         // Fast path: most chunks have no pending left-over.
         const chunkString = leftover ? leftover + text : text
 
-        if (!streamBarrierLifted) {
-          if (chunkString.includes(TSR_SCRIPT_BARRIER_ID)) {
-            streamBarrierLifted = true
-            router.serverSsr?.liftScriptBarrier()
+        const barrierMarkerIndex =
+          state.barrierPhase === 'locked'
+            ? chunkString.indexOf(TSR_SCRIPT_BARRIER_ID)
+            : -1
+
+        if (barrierMarkerIndex !== -1) {
+          const barrierScriptClosedInChunk =
+            chunkString.indexOf(SCRIPT_END_TAG, barrierMarkerIndex) !== -1
+
+          state.barrierPhase = 'lifted'
+          router.serverSsr?.liftScriptBarrier()
+
+          const barrierChunkBodyEndIndex = chunkString.indexOf(BODY_END_TAG)
+          if (barrierChunkBodyEndIndex !== -1) {
+            lifecycle.safeEnqueue(
+              chunkString.slice(0, barrierChunkBodyEndIndex),
+            )
+            pendingClosingTags = chunkString.slice(barrierChunkBodyEndIndex)
+            state.tailPhase = 'afterBody'
+          } else {
+            lifecycle.safeEnqueue(chunkString)
           }
+
+          if (barrierScriptClosedInChunk) {
+            flushPendingRouterHtml()
+          }
+
+          leftover = ''
+          continue
         }
 
-        // If we already saw </body>, everything else is part of tail; buffer it.
-        if (pendingClosingTags) {
+        if (state.tailPhase === 'afterBody') {
           pendingClosingTags += chunkString
           leftover = ''
           continue
         }
 
         const bodyEndIndex = chunkString.indexOf(BODY_END_TAG)
-        const htmlEndIndex = chunkString.indexOf(HTML_END_TAG)
 
-        if (
-          bodyEndIndex !== -1 &&
-          htmlEndIndex !== -1 &&
-          bodyEndIndex < htmlEndIndex
-        ) {
+        if (bodyEndIndex !== -1) {
+          lifecycle.safeEnqueue(chunkString.slice(0, bodyEndIndex))
           pendingClosingTags = chunkString.slice(bodyEndIndex)
-          safeEnqueue(chunkString.slice(0, bodyEndIndex))
+          state.tailPhase = 'afterBody'
           flushPendingRouterHtml()
           leftover = ''
           continue
         }
 
+        // Fast non-mutating passthrough in normal path: no pending injected HTML,
+        // no buffered carry-over, and no structural rewrite needed for this chunk.
+        if (!pendingRouterHtml && !leftover) {
+          if (rawUint8Chunk) {
+            lifecycle.safeEnqueue(rawUint8Chunk)
+          } else {
+            lifecycle.safeEnqueue(chunkString)
+          }
+          continue
+        }
+
         const lastClosingTagEnd = findLastClosingTagEnd(chunkString)
 
         if (lastClosingTagEnd > 0) {
-          safeEnqueue(chunkString.slice(0, lastClosingTagEnd))
+          lifecycle.safeEnqueue(chunkString.slice(0, lastClosingTagEnd))
           flushPendingRouterHtml()
 
           leftover = chunkString.slice(lastClosingTagEnd)
           if (leftover.length > MAX_LEFTOVER_CHARS) {
             // Ensure bounded memory even if a consumer streams long text sequences
             // without any closing tags. This may reduce injection granularity but is correct.
-            safeEnqueue(leftover.slice(0, leftover.length - MAX_LEFTOVER_CHARS))
+            lifecycle.safeEnqueue(
+              leftover.slice(0, leftover.length - MAX_LEFTOVER_CHARS),
+            )
             leftover = leftover.slice(-MAX_LEFTOVER_CHARS)
           }
         } else {
@@ -445,7 +535,7 @@ export function transformStreamWithRouter(
           const combined = chunkString
           if (combined.length > MAX_LEFTOVER_CHARS) {
             const flushUpto = combined.length - MAX_LEFTOVER_CHARS
-            safeEnqueue(combined.slice(0, flushUpto))
+            lifecycle.safeEnqueue(combined.slice(0, flushUpto))
             leftover = combined.slice(flushUpto)
           } else {
             leftover = combined
@@ -453,41 +543,41 @@ export function transformStreamWithRouter(
         }
       }
 
-      if (cleanedUp || isStreamClosed) return
+      if (lifecycle.isCleanedUp() || lifecycle.isClosed()) return
 
-      isAppRendering = false
+      state.streamPhase = 'appDone'
       router.serverSsr?.setRenderFinished()
 
-      if (serializationFinished) {
+      if (state.serializationDone) {
         tryFinish()
       } else {
         const timeoutMs = opts?.timeoutMs ?? DEFAULT_SERIALIZATION_TIMEOUT_MS
         serializationTimeoutHandle = setTimeout(() => {
-          if (!cleanedUp && !isStreamClosed) {
+          if (!lifecycle.isCleanedUp() && !lifecycle.isClosed()) {
             console.error('Serialization timeout after app render finished')
-            safeError(
+            lifecycle.safeError(
               new Error('Serialization timeout after app render finished'),
             )
-            cleanup()
+            lifecycle.cleanup()
           }
         }, timeoutMs)
       }
     } catch (error) {
-      if (cleanedUp) return
+      if (lifecycle.isCleanedUp()) return
       console.error('Error reading appStream:', error)
-      isAppRendering = false
+      state.streamPhase = 'appDone'
       router.serverSsr?.setRenderFinished()
-      safeError(error)
-      cleanup()
+      lifecycle.safeError(error)
+      lifecycle.cleanup()
     } finally {
-      reader.releaseLock()
+      lifecycle.setReader(undefined)
     }
   })().catch((error) => {
-    if (cleanedUp) return
+    if (lifecycle.isCleanedUp()) return
     console.error('Error in stream transform:', error)
-    safeError(error)
-    cleanup()
+    lifecycle.safeError(error)
+    lifecycle.cleanup()
   })
 
-  return stream
+  return lifecycle.stream
 }
diff --git a/packages/router-core/tests/getNormalizedURL.test.ts b/packages/router-core/tests/getNormalizedURL.test.ts
index d459c8b418..3e9ff186a4 100644
--- a/packages/router-core/tests/getNormalizedURL.test.ts
+++ b/packages/router-core/tests/getNormalizedURL.test.ts
@@ -125,4 +125,18 @@ describe('getNormalizedURL', () => {
       expect(normalizedUrl.url.hash).toBe(expectedHash)
     },
   )
+
+  test('should encode all backslashes in pathname', () => {
+    const normalized = getNormalizedURL('https://example.com/path\\a\\b\\c')
+    expect(normalized.url.pathname).toBe('/path%5Ca%5Cb%5Cc')
+  })
+
+  test('should encode backslashes in pathname while preserving query and hash', () => {
+    const normalized = getNormalizedURL(
+      'https://example.com/path\\a?x=1&y=2#section',
+    )
+    expect(normalized.url.pathname).toBe('/path%5Ca')
+    expect(normalized.url.search).toBe('?x=1&y=2')
+    expect(normalized.url.hash).toBe('#section')
+  })
 })
diff --git a/packages/router-core/tests/ssr-server-idempotency.test.ts b/packages/router-core/tests/ssr-server-idempotency.test.ts
new file mode 100644
index 0000000000..c83e5368f6
--- /dev/null
+++ b/packages/router-core/tests/ssr-server-idempotency.test.ts
@@ -0,0 +1,82 @@
+import { describe, expect, it, vi } from 'vitest'
+
+vi.mock('seroval', async (importOriginal) => {
+  const actual = await importOriginal<typeof import('seroval')>()
+
+  return {
+    ...actual,
+    crossSerializeStream: (_value: unknown, options: any) => {
+      options.onDone()
+      options.onError?.(new Error('forced duplicate completion'))
+    },
+    getCrossReferenceHeader: () => '',
+  }
+})
+
+import { attachRouterServerSsrUtils } from '../src/ssr/ssr-server'
+
+describe('ssr-server serialization completion idempotency', () => {
+  it('emits onSerializationFinished only once when serializer signals done then error', async () => {
+    const emit = vi.fn()
+    const consoleErrorSpy = vi
+      .spyOn(console, 'error')
+      .mockImplementation(() => undefined)
+
+    const router = {
+      options: {
+        ssr: {},
+        dehydrate: async () => undefined,
+      },
+      state: {
+        matches: [],
+      },
+      isShell: () => false,
+      emit,
+    } as any
+
+    attachRouterServerSsrUtils({ router, manifest: undefined })
+
+    let listenerCalls = 0
+    router.serverSsr.onSerializationFinished(() => {
+      listenerCalls++
+    })
+
+    await router.serverSsr.dehydrate()
+
+    const serializationEmits = emit.mock.calls.filter(
+      ([event]) => event?.type === 'onSerializationFinished',
+    )
+
+    expect(listenerCalls).toBe(1)
+    expect(serializationEmits).toHaveLength(1)
+    expect(router.serverSsr.isSerializationFinished()).toBe(true)
+
+    consoleErrorSpy.mockRestore()
+  })
+
+  it('does not clear render-finished listeners when serialization completes first', async () => {
+    const router = {
+      options: {
+        ssr: {},
+        dehydrate: async () => undefined,
+      },
+      state: {
+        matches: [],
+      },
+      isShell: () => false,
+      emit: vi.fn(),
+    } as any
+
+    attachRouterServerSsrUtils({ router, manifest: undefined })
+
+    let called = false
+    router.serverSsr.onRenderFinished(() => {
+      called = true
+    })
+
+    await router.serverSsr.dehydrate()
+    router.serverSsr.setRenderFinished()
+
+    expect(called).toBe(true)
+  })
+})
diff --git a/packages/router-core/tests/ssr-server.test.ts b/packages/router-core/tests/ssr-server.test.ts
new file mode 100644
index 0000000000..4f659efe98
--- /dev/null
+++ b/packages/router-core/tests/ssr-server.test.ts
@@ -0,0 +1,66 @@
+import { describe, expect, it, vi } from 'vitest'
+import { attachRouterServerSsrUtils } from '../src/ssr/ssr-server'
+
+function createMinimalRouter() {
+  return {
+    options: {
+      ssr: {},
+      dehydrate: async () => undefined,
+    },
+    state: {
+      matches: [],
+    },
+    isShell: () => false,
+    emit: () => {},
+  }
+}
+
+describe('ssr-server', () => {
+  it('flushes initial script buffer synchronously on render finish', () => {
+    const router = createMinimalRouter() as any
+    attachRouterServerSsrUtils({ router, manifest: undefined })
+
+    router.serverSsr.setRenderFinished()
+    const html = router.serverSsr.takeBufferedHtml()
+
+    expect(html).toContain('<script')
+    expect(html).toContain('$_TSR')
+  })
+
+  it('continues calling render-finished listeners after one throws', () => {
+    const router = createMinimalRouter() as any
+    attachRouterServerSsrUtils({ router, manifest: undefined })
+    const consoleErrorSpy = vi
+      .spyOn(console, 'error')
+      .mockImplementation(() => undefined)
+
+    let called = false
+    router.serverSsr.onRenderFinished(() => {
+      throw new Error('listener failed')
+    })
+    router.serverSsr.onRenderFinished(() => {
+      called = true
+    })
+
+    router.serverSsr.setRenderFinished()
+
+    expect(called).toBe(true)
+    expect(consoleErrorSpy).toHaveBeenCalled()
+    consoleErrorSpy.mockRestore()
+  })
+
+  it('flushes scripts enqueued during render-finished listeners', () => {
+    const router = createMinimalRouter() as any
+    attachRouterServerSsrUtils({ router, manifest: undefined })
+
+    router.serverSsr.onRenderFinished(() => {
+      router.serverSsr.injectScript('window.__render_listener_script__=1')
+    })
+
+    router.serverSsr.setRenderFinished()
+    const html = router.serverSsr.takeBufferedHtml()
+
+    expect(html).toContain('window.__render_listener_script__=1')
+    expect(html).toContain('<script')
+  })
+})
diff --git a/packages/router-core/tests/transformStreamWithRouter.bench.ts b/packages/router-core/tests/transformStreamWithRouter.bench.ts
new file mode 100644
index 0000000000..8272070b3d
--- /dev/null
+++ b/packages/router-core/tests/transformStreamWithRouter.bench.ts
@@ -0,0 +1,153 @@
+import { ReadableStream } from 'node:stream/web'
+import { bench, describe } from 'vitest'
+import { TSR_SCRIPT_BARRIER_ID } from '../src/ssr/constants'
+import { transformStreamWithRouter } from '../src/ssr/transformStreamWithRouter'
+
+type RouterMockOptions = {
+  serializationFinished?: boolean
+  initialBufferedHtml?: string
+}
+
+function createRouterMock(options?: RouterMockOptions) {
+  const listeners = new Map<string, Set<() => void>>()
+  let bufferedHtml = options?.initialBufferedHtml ?? ''
+  let serializationFinished = options?.serializationFinished ?? false
+
+  const router = {
+    subscribe(event: string, listener: () => void) {
+      const set = listeners.get(event) ?? new Set<() => void>()
+      set.add(listener)
+      listeners.set(event, set)
+      return () => {
+        set.delete(listener)
+      }
+    },
+    emit(event: string) {
+      listeners.get(event)?.forEach((listener) => listener())
+    },
+    serverSsr: {
+      isSerializationFinished() {
+        return serializationFinished
+      },
+      takeBufferedHtml() {
+        if (!bufferedHtml) return undefined
+        const html = bufferedHtml
+        bufferedHtml = ''
+        return html
+      },
+      injectHtml(html: string) {
+        bufferedHtml += html
+        router.emit('onInjectedHtml')
+      },
+      setRenderFinished() {
+        serializationFinished = true
+        router.emit('onSerializationFinished')
+      },
+      liftScriptBarrier() {},
+      cleanup() {},
+    },
+  }
+
+  return router as any
+}
+
+const encoder = new TextEncoder()
+
+function createChunkedStream(
+  chunks: Array<string | Uint8Array>,
+  onEnqueue?: (index: number) => void,
+) {
+  return new ReadableStream<string | Uint8Array>({
+    start(controller) {
+      for (let i = 0; i < chunks.length; i++) {
+        controller.enqueue(chunks[i]!)
+        onEnqueue?.(i)
+      }
+      controller.close()
+    },
+  })
+}
+
+async function consumeStream(stream: ReadableStream<Uint8Array>) {
+  const reader = stream.getReader()
+  let totalBytes = 0
+  while (true) {
+    const { done, value } = await reader.read()
+    if (done) break
+    totalBytes += value.byteLength
+  }
+  return totalBytes
+}
+
+function makeHtmlChunk(size: number) {
+  const body = 'x'.repeat(Math.max(0, size - 64))
+  return `<div class="row"><span>${body}</span></div>`
+}
+
+describe('transformStreamWithRouter bench - fast path', () => {
+  const binaryChunks = Array.from({ length: 120 }, () =>
+    encoder.encode(makeHtmlChunk(4096)),
+  )
+
+  const stringChunks = Array.from({ length: 120 }, () => makeHtmlChunk(4096))
+
+  bench('fast path - uint8 chunks', async () => {
+    const router = createRouterMock({ serializationFinished: true })
+    const appStream = createChunkedStream(binaryChunks)
+    const transformed = transformStreamWithRouter(router, appStream)
+    await consumeStream(transformed)
+  })
+
+  bench('fast path - string chunks', async () => {
+    const router = createRouterMock({ serializationFinished: true })
+    const appStream = createChunkedStream(stringChunks)
+    const transformed = transformStreamWithRouter(router, appStream)
+    await consumeStream(transformed)
+  })
+})
+
+describe('transformStreamWithRouter bench - streaming path', () => {
+  const headChunk = '<html><body><main><div>content</div>'
+  const barrierChunk = `<script id="${TSR_SCRIPT_BARRIER_ID}"></script>`
+  const tailChunk = '</main></body></html>'
+
+  bench('barrier + initial buffered html', async () => {
+    const router = createRouterMock({
+      serializationFinished: false,
+      initialBufferedHtml: '<script>window.__initial=1</script>',
+    })
+
+    const appStream = createChunkedStream([
+      encoder.encode(headChunk),
+      encoder.encode(barrierChunk),
+      encoder.encode(tailChunk),
+    ])
+
+    const transformed = transformStreamWithRouter(router, appStream)
+    await consumeStream(transformed)
+  })
+
+  bench('barrier + incremental injected html', async () => {
+    const router = createRouterMock({ serializationFinished: false })
+
+    const appStream = createChunkedStream(
+      [
+        encoder.encode(headChunk),
+        encoder.encode(barrierChunk),
+        encoder.encode(makeHtmlChunk(2048)),
+        encoder.encode(makeHtmlChunk(2048)),
+        encoder.encode(tailChunk),
+      ],
+      (index) => {
+        if (index <= 3) {
+          router.serverSsr.injectHtml(
+            `<script>window.__bench_chunk_${index}=1</script>`,
+          )
+        }
+      },
+    )
+
+    const transformed = transformStreamWithRouter(router, appStream)
+    await consumeStream(transformed)
+  })
+})
diff --git a/packages/router-core/tests/transformStreamWithRouter.profile.mjs b/packages/router-core/tests/transformStreamWithRouter.profile.mjs
new file mode 100644
index 0000000000..7fa63aee48
--- /dev/null
+++ b/packages/router-core/tests/transformStreamWithRouter.profile.mjs
@@ -0,0 +1,148 @@
+// @ts-nocheck
+import { ReadableStream } from 'node:stream/web'
+import { transformStreamWithRouter } from '../dist/esm/ssr/transformStreamWithRouter.js'
+import { TSR_SCRIPT_BARRIER_ID } from '../dist/esm/ssr/constants.js'
+
+function createRouterMock(options = {}) {
+  const listeners = new Map()
+  let bufferedHtml = options.initialBufferedHtml ?? ''
+  let serializationFinished = options.serializationFinished ?? false
+
+  const router = {
+    subscribe(event, listener) {
+      const set = listeners.get(event) ?? new Set()
+      set.add(listener)
+      listeners.set(event, set)
+      return () => {
+        set.delete(listener)
+      }
+    },
+    emit(event) {
+      listeners.get(event)?.forEach((listener) => listener())
+    },
+    serverSsr: {
+      isSerializationFinished() {
+        return serializationFinished
+      },
+      takeBufferedHtml() {
+        if (!bufferedHtml) return undefined
+        const html = bufferedHtml
+        bufferedHtml = ''
+        return html
+      },
+      injectHtml(html) {
+        bufferedHtml += html
+        router.emit('onInjectedHtml')
+      },
+      setRenderFinished() {
+        serializationFinished = true
+        router.emit('onSerializationFinished')
+      },
+      liftScriptBarrier() {},
+      cleanup() {},
+    },
+  }
+
+  return router
+}
+
+const encoder = new TextEncoder()
+
+function createChunkedStream(chunks, onEnqueue) {
+  return new ReadableStream({
+    start(controller) {
+      for (let i = 0; i < chunks.length; i++) {
+        controller.enqueue(chunks[i])
+        onEnqueue?.(i)
+      }
+      controller.close()
+    },
+  })
+}
+
+async function consumeStream(stream) {
+  const reader = stream.getReader()
+  let totalBytes = 0
+  while (true) {
+    const { done, value } = await reader.read()
+    if (done) break
+    totalBytes += value.byteLength
+  }
+  return totalBytes
+}
+
+function makeHtmlChunk(size) {
+  const body = 'x'.repeat(Math.max(0, size - 64))
+  return `<div class="row"><span>${body}</span></div>`
+}
+
+async function runFastPathWorkload(iterations = 500) {
+  const binaryChunks = Array.from({ length: 120 }, () =>
+    encoder.encode(makeHtmlChunk(4096)),
+  )
+
+  let total = 0
+  for (let i = 0; i < iterations; i++) {
+    const router = createRouterMock({ serializationFinished: true })
+    const appStream = createChunkedStream(binaryChunks)
+    const transformed = transformStreamWithRouter(router, appStream)
+    total += await consumeStream(transformed)
+  }
+
+  return total
+}
+
+async function runStreamingWorkload(iterations = 300) {
+  const headChunk = '<html><body><main><div>content</div>'
+  const barrierChunk = `<script id="${TSR_SCRIPT_BARRIER_ID}"></script>`
+  const tailChunk = '</main></body></html>'
+
+  let total = 0
+  for (let i = 0; i < iterations; i++) {
+    const router = createRouterMock({ serializationFinished: false })
+
+    const appStream = createChunkedStream(
+      [
+        encoder.encode(headChunk),
+        encoder.encode(barrierChunk),
+        encoder.encode(makeHtmlChunk(2048)),
+        encoder.encode(makeHtmlChunk(2048)),
+        encoder.encode(tailChunk),
+      ],
+      (index) => {
+        if (index <= 3) {
+          router.serverSsr.injectHtml(
+            `<script>window.__profile_chunk_${index}=1</script>`,
+          )
+        }
+      },
+    )
+
+    const transformed = transformStreamWithRouter(router, appStream)
+    total += await consumeStream(transformed)
+  }
+
+  return total
+}
+
+async function main() {
+  const fast = await runFastPathWorkload()
+  const streaming = await runStreamingWorkload()
+  process.stdout.write(
+    JSON.stringify(
+      {
+        mode: 'transformStreamWithRouter.profile',
+        fast,
+        streaming,
+        total: fast + streaming,
+      },
+      null,
+      2,
+    ) + '\n',
+  )
+}
+
+main().catch((error) => {
+  console.error(error)
+  process.exitCode = 1
+})
diff --git a/packages/router-core/tests/transformStreamWithRouter.test.ts b/packages/router-core/tests/transformStreamWithRouter.test.ts
new file mode 100644
index 0000000000..84bfb0bb9c
--- /dev/null
+++ b/packages/router-core/tests/transformStreamWithRouter.test.ts
@@ -0,0 +1,364 @@
+import { ReadableStream } from 'node:stream/web'
+import { describe, expect, it, vi } from 'vitest'
+import { transformStreamWithRouter } from '../src/ssr/transformStreamWithRouter'
+
+function createRouterMock(options?: {
+  serializationFinished?: boolean
+  initialBufferedHtml?: string
+}) {
+  const listeners = new Map<string, Set<() => void>>()
+  let bufferedHtml = options?.initialBufferedHtml ?? ''
+  let serializationFinished = options?.serializationFinished ?? false
+  let cleanedUp = false
+  let setRenderFinishedCalls = 0
+
+  const router = {
+    subscribe(event: string, listener: () => void) {
+      const set = listeners.get(event) ?? new Set<() => void>()
+      set.add(listener)
+      listeners.set(event, set)
+      return () => {
+        set.delete(listener)
+      }
+    },
+    emit({ type }: { type: string }) {
+      listeners.get(type)?.forEach((listener) => listener())
+    },
+    serverSsr: {
+      isSerializationFinished() {
+        return serializationFinished
+      },
+      takeBufferedHtml() {
+        if (!bufferedHtml) return undefined
+        const html = bufferedHtml
+        bufferedHtml = ''
+        return html
+      },
+      injectHtml(html: string) {
+        bufferedHtml += html
+        router.emit({ type: 'onInjectedHtml' })
+      },
+      setRenderFinished() {
+        setRenderFinishedCalls++
+        serializationFinished = true
+        router.emit({ type: 'onSerializationFinished' })
+      },
+      liftScriptBarrier() {},
+      cleanup() {
+        cleanedUp = true
+      },
+    },
+  }
+
+  return {
+    router: router as any,
+    wasCleanedUp() {
+      return cleanedUp
+    },
+    getSetRenderFinishedCalls() {
+      return setRenderFinishedCalls
+    },
+  }
+}
+
+async function readAll(stream: ReadableStream<Uint8Array | string>) {
+  const reader = stream.getReader()
+  const decoder = new TextDecoder()
+  let result = ''
+  while (true) {
+    const { done, value } = await reader.read()
+    if (done) break
+    if (typeof value === 'string') {
+      result += value
+    } else {
+      result += decoder.decode(value, { stream: true })
+    }
+  }
+  result += decoder.decode()
+  return result
+}
+
+describe('transformStreamWithRouter', () => {
+  it('propagates cancel to underlying source in fast path', async () => {
+    const { router, wasCleanedUp } = createRouterMock({
+      serializationFinished: true,
+    })
+    const encoder = new TextEncoder()
+    let canceled = false
+
+    const appStream = new ReadableStream<Uint8Array>({
+      start(controller) {
+        controller.enqueue(encoder.encode('<html><body>hello</body></html>'))
+      },
+      cancel() {
+        canceled = true
+      },
+    })
+
+    const transformed = transformStreamWithRouter(router, appStream)
+    const reader = transformed.getReader()
+
+    await reader.read()
+    await reader.cancel('test cancel')
+    await Promise.resolve()
+
+    expect(canceled).toBe(true)
+    expect(wasCleanedUp()).toBe(true)
+  })
+
+  it('inserts router html before closing tags when </body> and </html> are split across chunks', async () => {
+    const { router } = createRouterMock({
+      serializationFinished: false,
+    })
+    const encoder = new TextEncoder()
+
+    const appStream = new ReadableStream<Uint8Array>({
+      start(controller) {
+        controller.enqueue(
+          encoder.encode(
+            '<html><body><div>content</div><script id="$tsr-stream-barrier"></script></body>',
+          ),
+        )
+        router.serverSsr.injectHtml('<script>window.__injected=1</script>')
+        controller.enqueue(encoder.encode('</html>'))
+        controller.close()
+      },
+    })
+
+    const transformed = transformStreamWithRouter(router, appStream)
+    const html = await readAll(transformed)
+
+    const injectedIndex = html.indexOf('<script>window.__injected=1</script>')
+    const bodyEndIndex = html.indexOf('</body>')
+    const htmlEndIndex = html.indexOf('</html>')
+
+    expect(injectedIndex, html).toBeGreaterThan(-1)
+    expect(bodyEndIndex, html).toBeGreaterThan(-1)
+    expect(htmlEndIndex, html).toBeGreaterThan(-1)
+    expect(injectedIndex).toBeLessThan(htmlEndIndex)
+    expect(injectedIndex).toBeGreaterThanOrEqual(0)
+  })
+
+  it('propagates cancel to underlying source in normal path', async () => {
+    const { router, wasCleanedUp } = createRouterMock({
+      serializationFinished: false,
+    })
+    let canceled = false
+
+    const appStream = new ReadableStream<Uint8Array>({
+      pull() {
+        // Keep stream open
+      },
+      cancel() {
+        canceled = true
+      },
+    })
+
+    const transformed = transformStreamWithRouter(router, appStream)
+    const reader = transformed.getReader()
+
+    await reader.cancel('normal-path-cancel')
+    await Promise.resolve()
+
+    expect(canceled).toBe(true)
+    expect(wasCleanedUp()).toBe(true)
+  })
+
+  it('encodes string chunks in fast path', async () => {
+    const { router } = createRouterMock({
+      serializationFinished: true,
+    })
+
+    const appStream = new ReadableStream<string>({
+      start(controller) {
+        controller.enqueue('<html><body>hello-string</body></html>')
+        controller.close()
+      },
+    })
+
+    const transformed = transformStreamWithRouter(router, appStream)
+    const html = await readAll(transformed)
+
+    expect(html).toContain('hello-string')
+    expect(html).toContain('</body>')
+  })
+
+  it('calls setRenderFinished in fast path when app stream completes', async () => {
+    const { router, getSetRenderFinishedCalls } = createRouterMock({
+      serializationFinished: true,
+    })
+    const encoder = new TextEncoder()
+
+    const appStream = new ReadableStream<Uint8Array>({
+      start(controller) {
+        controller.enqueue(encoder.encode('<html><body>done</body></html>'))
+        controller.close()
+      },
+    })
+
+    const transformed = transformStreamWithRouter(router, appStream)
+    const html = await readAll(transformed)
+
+    expect(html).toContain('done')
+    expect(getSetRenderFinishedCalls()).toBe(1)
+  })
+
+  it('flushes pendingRouterHtml when barrier and </body> land in the same chunk', async () => {
+    // when the barrier script and </body> appear in the same chunk,
+    // scripts buffered in pendingRouterHtml (e.g. from initialBufferedHtml) must be
+    // emitted immediately — not deferred to tryFinish(). They must appear between
+    // the barrier content and </body>, not after </body>.
+    const { router } = createRouterMock({
+      serializationFinished: false,
+      initialBufferedHtml: '<script>window.__initial_buffered__=1</script>',
+    })
+    const encoder = new TextEncoder()
+
+    const appStream = new ReadableStream<Uint8Array>({
+      start(controller) {
+        // Barrier and </body> are in the SAME chunk
+        controller.enqueue(
+          encoder.encode(
+            '<html><body><div>content</div>' +
+              '<script id="$tsr-stream-barrier"></script>' +
+              '</body></html>',
+          ),
+        )
+        controller.close()
+      },
+    })
+
+    router.serverSsr.setRenderFinished()
+
+    const transformed = transformStreamWithRouter(router, appStream)
+    const html = await readAll(transformed)
+
+    const initialScriptIndex = html.indexOf(
+      '<script>window.__initial_buffered__=1</script>',
+    )
+    const bodyEndIndex = html.indexOf('</body>')
+
+    expect(initialScriptIndex, html).toBeGreaterThan(-1)
+    expect(bodyEndIndex, html).toBeGreaterThan(-1)
+    // Scripts must appear BEFORE </body>
+    expect(initialScriptIndex).toBeLessThan(bodyEndIndex)
+  })
+
+  it('flushes pendingRouterHtml when barrier has no </body> in same chunk', async () => {
+    // when the barrier is found but </body> is in a later chunk,
+    // scripts buffered before the barrier should be flushed immediately after
+    // emitting the barrier chunk rather than waiting for tryFinish().
+    const { router } = createRouterMock({
+      serializationFinished: false,
+      initialBufferedHtml: '<script>window.__pre_barrier__=1</script>',
+    })
+    const encoder = new TextEncoder()
+
+    const appStream = new ReadableStream<Uint8Array>({
+      start(controller) {
+        // Barrier chunk — no </body> yet
+        controller.enqueue(
+          encoder.encode(
+            '<html><body><div>content</div>' +
+              '<script id="$tsr-stream-barrier"></script>',
+          ),
+        )
+        // </body> arrives in a later chunk
+        controller.enqueue(encoder.encode('</body></html>'))
+        controller.close()
+      },
+    })
+
+    router.serverSsr.setRenderFinished()
+
+    const transformed = transformStreamWithRouter(router, appStream)
+    const html = await readAll(transformed)
+
+    const preBarrierScriptIndex = html.indexOf(
+      '<script>window.__pre_barrier__=1</script>',
+    )
+    const bodyEndIndex = html.indexOf('</body>')
+
+    expect(preBarrierScriptIndex, html).toBeGreaterThan(-1)
+    expect(bodyEndIndex, html).toBeGreaterThan(-1)
+    // Scripts must appear BEFORE </body>
+    expect(preBarrierScriptIndex).toBeLessThan(bodyEndIndex)
+  })
+
+  it('does not inject pendingRouterHtml into an open split barrier tag', async () => {
+    const { router } = createRouterMock({
+      serializationFinished: false,
+      initialBufferedHtml: '<script>window.__split_barrier__=1</script>',
+    })
+    const encoder = new TextEncoder()
+
+    const appStream = new ReadableStream<Uint8Array>({
+      start(controller) {
+        controller.enqueue(
+          encoder.encode(
+            '<html><body><div>content</div><script id="$tsr-stream-barrier"',
+          ),
+        )
+        controller.enqueue(encoder.encode('></script></body></html>'))
+        controller.close()
+      },
+    })
+
+    router.serverSsr.setRenderFinished()
+
+    const transformed = transformStreamWithRouter(router, appStream)
+    const html = await readAll(transformed)
+
+    const barrierMarkerIndex = html.indexOf('$tsr-stream-barrier')
+    const barrierTagCloseIndex = html.indexOf('>', barrierMarkerIndex)
+    const splitBarrierScriptIndex = html.indexOf(
+      '<script>window.__split_barrier__=1</script>',
+    )
+    const bodyEndIndex = html.indexOf('</body>')
+
+    expect(barrierMarkerIndex, html).toBeGreaterThan(-1)
+    expect(barrierTagCloseIndex, html).toBeGreaterThan(-1)
+    expect(splitBarrierScriptIndex, html).toBeGreaterThan(-1)
+    expect(bodyEndIndex, html).toBeGreaterThan(-1)
+
+    expect(splitBarrierScriptIndex).toBeGreaterThan(barrierTagCloseIndex)
+    expect(splitBarrierScriptIndex).toBeLessThan(bodyEndIndex)
+  })
+
+  it('cancels underlying source on lifetime timeout cleanup', async () => {
+    vi.useFakeTimers()
+
+    const { router } = createRouterMock({
+      serializationFinished: false,
+    })
+
+    let canceled = false
+
+    const appStream = new ReadableStream<Uint8Array>({
+      pull() {
+        // Keep open forever to force lifetime timeout path
+      },
+      cancel() {
+        canceled = true
+      },
+    })
+
+    const transformed = transformStreamWithRouter(router, appStream, {
+      lifetimeMs: 10,
+    })
+
+    try {
+      const reader = transformed.getReader()
+      const readExpectation = expect(reader.read()).rejects.toThrow(
+        'Stream lifetime exceeded',
+      )
+
+      await vi.advanceTimersByTimeAsync(11)
+
+      await readExpectation
+      expect(canceled).toBe(true)
+    } finally {
+      vi.useRealTimers()
+    }
+  })
+})
