files/en-us/web/api/websocketstream/close/index.md
{{APIRef("WebSockets API")}}{{SeeCompatTable}}{{AvailableInWorkers}}
The close() method of the
{{domxref("WebSocketStream")}} interface closes the WebSocket connection. The method optionally accepts an object containing a custom code and/or reason indicating why the connection was closed.
close()
close(options)
options {{optional_inline}}
closeCode {{optional_inline}}
CloseEvent status codes).reason {{optional_inline}}
reason string is 123 bytes. The string is automatically encoded as UTF-8 when the function is invoked.[!NOTE] Depending on the server setup and status code you use, the server may choose to ignore a custom code in favor of a valid code that is correct for the closing reason. Valid codes are 1000, and any code within the range 3000 to 4999, inclusive.
None (undefined).
SyntaxError {{domxref("DOMException")}}
reason is longer than the maximum allowed length of 123 bytes.const wsURL = "wss://127.0.0.1/";
const wss = new WebSocketStream(wsURL);
setTimeout(() => {
wss.close({
closeCode: 1000,
reason: "That's all folks",
});
}, 10000);
Not currently a part of any specification. See https://github.com/whatwg/websockets/pull/48 for standardization progress.
{{Compat}}