grafana/k6 · error · InvalidAccessError

InvalidAccessError: Failed to execute 'close' on 'WebSocket'

Error message

InvalidAccessError: Failed to execute 'close' on 'WebSocket': The close code must be either 1000, or between 3000 and 4999. %d is neither

What it means

Close-code validation in webSocket.close: before initiating the closing handshake, the requested code is checked against isValidClientCloseCode, which accepts only 1000 or codes in the 3000–4999 range (per RFC 6455, codes 1001–2999 are reserved for protocol/server/browser use and cannot be set by client scripts). The %d shows the rejected code; the message deliberately mimics the browser DOMException InvalidAccessError.

Source

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

	// 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 w.readyState == CLOSED || w.readyState == CLOSING {
		return nil
	}

	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,
		)
	}

	if !isValidCloseReason(reason) {
		return errors.New(
			`SyntaxError: Failed to execute 'close' on 'WebSocket': The message must not be greater than 123 bytes`,
		)
	}

	if code == 0 {
		code = websocket.CloseNormalClosure
	}

	w.readyState = CLOSING
	w.closeCode = code

View on GitHub (pinned to 165bb3c1a4)

Solutions

  1. Use code 1000 for a normal closure
  2. Use a custom application code between 3000 and 4999
  3. Omit the code entirely (ws.close()) to close with the default 1000
  4. Never send reserved codes such as 1001, 1002, or 2000–2999 from the client
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at internal/js/modules/k6/websockets/websockets.go:773 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of grafana/k6@165bb3c1a4 (2026-08-18). Data as JSON: /api/errors/8369a5cc50fcc451. Report an issue: GitHub.