grafana/k6 · error · InvalidStateError

InvalidStateError

Error message

InvalidStateError

What it means

Thrown by send() and ping() on k6/experimental/websockets sockets when the connection is not in the OPEN state. assertStateOpen (internal/js/modules/k6/websockets/websockets.go:750) panics with a bare InvalidStateError whenever readyState is CONNECTING, CLOSING, or CLOSED, mirroring the browser API where sending or pinging a not-yet-open or already-closed socket is invalid.

Solutions

  1. Move sends into the open handler: ws.addEventListener('open', () => ws.send('hello'))
  2. Guard every send/ping call site: if (ws.readyState === WebSocket.OPEN) ws.send(...)
  3. Remember ping() follows the same rule — only ping an OPEN socket

Example fix

// before
const ws = new WebSocket('wss://example.com');
ws.send('hello'); // still CONNECTING → InvalidStateError

// after
const ws = new WebSocket('wss://example.com');
ws.addEventListener('open', () => ws.send('hello'));
Defensive patterns

Strategy: type-guard

Validate before calling

function sendWhenOpen(ws, data) {
  if (ws.readyState !== WebSocket.OPEN) {
    // drop or buffer; never call send()/ping() while CONNECTING/CLOSING/CLOSED
    return false;
  }
  ws.send(data);
  return true;
}

Type guard

function isOpen(ws) {
  return ws.readyState === WebSocket.OPEN; // 1
}

Try / catch

try {
  ws.send(payload);
} catch (err) {
  if (String(err.message) !== 'InvalidStateError') throw err;
  console.warn('socket not OPEN — requeue the payload in the open handler');
}

Prevention

When it happens

Trigger: Calling ws.send(...) or ws.ping() immediately after new WebSocket(url) — the constructor starts the connection in a background goroutine, so the socket is still CONNECTING; or calling them after close(), after a server-initiated close, or from a timer that outlived the connection.

Common situations: Migrating scripts from the legacy k6/ws module, where the setup callback only runs once the socket is open; sending from setTimeout/setInterval without checking state; VU iterations that reuse a closed socket handle.

Related errors


AI-assisted analysis of grafana/k6@3fcf5388d7 (2026-08-18). Data as JSON: /api/errors/a294ba84beae405a. Report an issue: GitHub.

Appendix: source

Thrown at internal/js/modules/k6/websockets/websockets.go:860

		TimeSeries: metrics.TimeSeries{
			Metric: w.builtinMetrics.WSPing,
			Tags:   w.tagsAndMeta.Tags,
		},
		Time:     pongTimestamp,
		Metadata: w.tagsAndMeta.Metadata,
		Value:    metrics.D(pongTimestamp.Sub(pingTimestamp)),
	})
}

// assertStateOpen checks if the websocket is in the OPEN state
// otherwise it throws an error (panic)
func (w *webSocket) assertStateOpen() {
	if w.readyState == OPEN {
		return
	}

	// TODO figure out if we should give different error while being closed/closed/connecting
	common.Throw(w.vu.Runtime(), errors.New("InvalidStateError"))
}

func isValidClientCloseCode(code int) bool {
	return code == 1000 || (code >= 3000 && code <= 4999)
}

func isValidCloseReason(reason string) bool {
	return len([]byte(reason)) <= 123
}

func (w *webSocket) close(code int, reason string) error {
	if code != 0 && !isValidClientCloseCode(code) {
		return fmt.Errorf(
			"InvalidAccessError: Failed to execute 'close' on 'WebSocket': "+
				"The close code must be either 1000, or between 3000 and 4999. %d is neither",
			code,
		)
	}

View on GitHub (pinned to 3fcf5388d7)