Skip to content

WebSocketStream throws internal error when cannot open an connection #4732

Description

@piotr-cz

Bug Description

WebSocketStream throws fatal error when it fails to open an connection

Reproducible By

import { WebSocketStream } from 'undici'

const stream = new WebSocketStream('https://not-a-ws-server.com/')

Expected Behavior

Package should not throw an error that is not possible to catch

Logs & Screenshots

TypeError: Cannot read properties of undefined (reading 'closingInfo')
    at #onSocketClose (xxx\node_modules\undici\lib\web\websocket\stream\websocketstream.js:373:33)
    at Object.onSocketClose (xxx\node_modules\undici\lib\web\websocket\stream\websocketstream.js:65:45)
    at failWebsocketConnection (xxx\node_modules\undici\lib\web\websocket\connection.js:318:13)
    at Object.processResponse (xxx\node_modules\undici\lib\web\websocket\connection.js:103:11)
    at xxx\node_modules\undici\lib\web\fetch\index.js:1078:19
    at node:internal/process/task_queues:151:7
    at AsyncResource.runInAsyncScope (node:async_hooks:214:14)
    at AsyncResource.runMicrotask (node:internal/process/task_queues:148:8)
    at process.processTicksAndRejections (node:internal/process/task_queues:105:5)

Environment

Windows, Node v24.4.0, undici v7.18.2

Additional context

This is because this.#parser is being set after connection has been established:

#onConnectionEstablished (response, parsedExtensions) {
this.#handler.socket = response.socket
const parser = new ByteParser(this.#handler, parsedExtensions)
parser.on('drain', () => this.#handler.onParserDrain())
parser.on('error', (err) => this.#handler.onParserError(err))
this.#parser = parser

but is being accessed before:

const result = this.#parser.closingInfo

This behavior has been introduced by #4521 and has also been described here: #3546 (comment)

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions