Skip to content

Invalid state: Controller is already closed #239

Closed

Description

@magne4000

What version of Hono are you using?

4.7.6

What runtime/platform is your app running on? (with version if possible)

node v20.14.0

What steps can reproduce the bug?

  • Create an handler that sends a Response with a ReadableStream body
  • Close it on client side before it finishes

Repro: https://github.com/magne4000/repro-hono-streaming
pnpm dev then open /, refresh in quick succession, this will cause the error.

What is the expected behavior?

This should not lead to a crash

What do you see instead?

If a client closes the connection, it should be handled quietly

Additional information

TypeError [ERR_INVALID_STATE]: Invalid state: Controller is already closed
    at ReadableStreamDefaultController.enqueue (node:internal/webstreams/readablestream:1074:13)
    at Timeout.pushRandomData (/home/magne/workspace/repro/hono-streaming/src/index.ts:38:20)
    at listOnTimeout (node:internal/timers:573:17)
    at process.processTimers (node:internal/timers:514:7) {
  code: 'ERR_INVALID_STATE'
}

Related issue using Hono with Vike: vikejs/vike#2334

Activity

  1. nitedani commented on Apr 15, 2025

    @nitedani

    I've been looking into this issue and have some thoughts on the optimal solution.

    First, I was able to reproduce and fix the issue in my own code by adding proper error handling around the stream controller operations:

    function pushRandomData() {
      // Check if already closed with a flag
      if (isClosed) return;
      
      // Generate and enqueue data
      controller.enqueue(data);
      
      // Schedule next push
      timeoutId = setTimeout(pushRandomData, 50);
    }
    
    // Add the cancel callback to ReadableStream
    cancel() {
      isClosed = true;
    },
    
    // Or listen for client disconnection
    c.req.raw.signal.addEventListener('abort', () => {
      isClosed = true;
    });

    While this works, I believe Hono should provide a safety net at the framework level to prevent server crashes when streams are closed unexpectedly. The ideal solution would:

    • Prevent crashes: Catch "controller already closed" errors at the framework level to prevent the entire server from crashing
    • Provide warnings: Log warnings instead of crashing so developers are aware of the issue
    • Signal disconnections: Make it easier for developers to detect when clients disconnect so they can clean up resources (timers, database connections, etc.)

    This approach maintains a good separation of concerns:

    • Hono handles crash prevention (framework responsibility)
    • Developers handle resource cleanup (application responsibility)

    This would improve developer experience while still encouraging proper resource management. Even if Hono gracefully handles closed stream errors, developers should still implement proper cleanup to avoid wasting server resources on disconnected clients.

    Would the Hono team consider implementing this kind of safety mechanism in the core framework?

  2. deleted a comment from on Apr 17, 2025
  3. yusukebe commented on Apr 26, 2025

    @yusukebe
    Member

    @magne4000 @nitedani

    This is not a hono core issue. This is because this problem occurs even without using hono.

    import { serve } from '@hono/node-server'
    
    const app = {
      fetch: () => {
        const randomDataStream = new ReadableStream({
          //...
        })
        return new Response(randomDataStream)
      }
    }
    
    serve(
      {
        fetch: app.fetch,
        port: 3000
      },
      (info) => {
        console.log(`Server is running on http://localhost:${info.port}`)
      }
    )

    So, hono should not handle this.

    It's my opinion. It would be ideal if the JS runtime handled it. For example, if you run it on Wrangler/workerd and Cloudflare, it does not throw an error and does not crash.

    Anyway, this is not a bug.

  4. magne4000 commented on Apr 28, 2025

    @magne4000
    Author

    I would argue that this is a @hono/node-server bug then.

  5. yusukebe commented on Apr 28, 2025

    @yusukebe
    Member

    Okay. I'll transfer this issue to the @hono/node-server repo.

  6. transferred this issue fromhonojs/honoon Apr 28, 2025
  7. usualoma commented on Jul 16, 2025

    @usualoma
    Member

    In deno serve, cancel() is called in the same way as in node-server, and an error occurs in queue().

    In bun and wrangler, cancel() is not called.

    Based on these situations, I think it would be better not to call cancel() in node-server either, but I think this is not a bug, but rather a question of which specification is more convenient.

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions