Which WebSocket Close Code Should I Use?
WebSocket connections are closed with a Close frame containing a numeric code and optional reason string. Choosing the right close code helps clients understand whether to reconnect, report an error, or simply move on. This tree covers normal closure, protocol violations, policy enforcement, and server-side errors.
Decision Steps
Is the connection closing for a normal, expected reason (both sides are done and agreed to close)?
Is an endpoint going away — e.g., server restarting, browser tab closing, or client navigating away?
Did the remote endpoint violate the WebSocket protocol (e.g., invalid opcode, incorrect framing, bad handshake)?
Did the endpoint receive a data type it cannot handle (e.g., binary data when only text is expected)?
Is the connection being terminated due to a policy violation (e.g., authentication failure, forbidden message content, rate limit)?
Did the endpoint receive a message that exceeds the allowed message size limit?