JavaScript Web Sockets
JavaScript Web Sockets Interview with follow-up questions
1. What is a WebSocket in JavaScript and how is it different from HTTP?
A WebSocket is a protocol that provides a full-duplex, persistent communication channel over a single TCP connection. After an initial HTTP handshake (the Upgrade request that switches the connection to the WebSocket protocol), both client and server can send messages at any time over the same open socket.
const socket = new WebSocket('wss://example.com/chat');
socket.addEventListener('open', () => socket.send('hello'));
socket.addEventListener('message', (e) => console.log(e.data));
How it differs from HTTP:
- HTTP is request/response and stateless — the client must ask before the server can answer. WebSockets are bidirectional: the server can push to the client without a request.
- HTTP opens (logically) a connection per exchange; a WebSocket stays open, avoiding repeated handshake overhead — ideal for real-time apps (chat, live feeds, multiplayer).
Context interviewers like: use wss:// (TLS) in production. If you only need one-way server→client updates, Server-Sent Events are simpler. Libraries like Socket.IO add reconnection, heartbeats, and fallbacks on top of raw WebSockets.
Follow-up 1
Can you explain how a WebSocket connection is established?
To establish a WebSocket connection, the client sends a WebSocket handshake request to the server. The server responds with a WebSocket handshake response, and if successful, the connection is established. The handshake request and response are HTTP-based, but once the connection is established, the protocol switches to the WebSocket protocol.
Follow-up 2
What are some use cases for WebSockets?
WebSockets are commonly used in applications that require real-time data updates or bi-directional communication. Some use cases for WebSockets include real-time chat applications, collaborative editing tools, real-time gaming, stock market tickers, and live sports updates.
Follow-up 3
How would you handle errors in a WebSocket connection?
In a WebSocket connection, errors can occur due to various reasons such as network issues or server-side errors. To handle errors, you can listen for the 'error' event on the WebSocket object and handle the error accordingly. You can also listen for the 'close' event to detect when the connection is closed unexpectedly.
Follow-up 4
Can you explain how to send and receive messages using WebSockets?
To send a message using WebSockets, you can use the 'send' method on the WebSocket object. For example, webSocket.send('Hello, server!'); To receive messages, you can listen for the 'message' event on the WebSocket object and handle the received message in the event handler. For example,
webSocket.addEventListener('message', function(event) {
var message = event.data;
console.log('Received message: ' + message);
});
2. How can you close a WebSocket connection in JavaScript?
Call the close() method on the WebSocket instance. Optionally pass a close code and a human-readable reason so the other side knows why:
const socket = new WebSocket('wss://example.com');
// Graceful close with a normal-closure code and reason
socket.close(1000, 'Work complete');
Things interviewers expect:
close()initiates the closing handshake; the connection moves toCLOSING(readyState 2) thenCLOSED(3).- Listen for the
closeevent to react — it gives youevent.code,event.reason, andevent.wasClean:
socket.addEventListener('close', (event) => {
console.log(event.code, event.reason, event.wasClean);
});
- Use code 1000 for a normal closure; custom application codes go in the 3000–4999 range.
- Calling
close()while stillCONNECTINGis fine — the connection aborts once established. - Clean up listeners and, if you need resilience, implement reconnection with backoff (or use a library like Socket.IO that handles it).
Follow-up 1
What happens when a WebSocket connection is closed?
When a WebSocket connection is closed, the following events occur:
- The
oncloseevent is triggered on the WebSocket object. - The WebSocket connection is closed and can no longer send or receive messages.
- The
oncloseevent handler, if defined, is called.
It is important to handle the onclose event to perform any necessary cleanup or reconnection logic.
Follow-up 2
How can you handle the 'onclose' event?
To handle the 'onclose' event in JavaScript, you can define an event handler function and assign it to the onclose property of the WebSocket object. Here is an example:
const socket = new WebSocket('ws://example.com');
// Define the 'onclose' event handler
socket.onclose = function(event) {
console.log('WebSocket connection closed');
// Perform any necessary cleanup or reconnection logic
};
Follow-up 3
What are the reasons for a WebSocket connection to close?
There are several reasons for a WebSocket connection to close:
- The server or client explicitly closes the connection using the
close()method. - The server or client encounters an error and closes the connection.
- The server or client detects a timeout or network issue and closes the connection.
- The server or client receives a close frame from the other party indicating the intention to close the connection.
It is important to handle the 'onclose' event and check the event.code and event.reason properties to determine the reason for the connection closure.
3. What are the ready states of a WebSocket?
The readyState property reports the connection's current state as one of four numeric constants:
CONNECTING(0) — the connection is being established (initial state afternew WebSocket(...)).OPEN(1) — connected and ready tosend()/receive data.CLOSING(2) — the closing handshake is in progress.CLOSED(3) — the connection is closed or could not be opened.
const socket = new WebSocket('wss://example.com');
if (socket.readyState === WebSocket.OPEN) {
socket.send('hi');
}
Gotcha interviewers test: the socket is not ready immediately after construction — readyState is CONNECTING until the open event fires. Calling send() before then throws an InvalidStateError. The safe pattern is to send inside the open handler (or guard with readyState === WebSocket.OPEN). Use the named constants (WebSocket.OPEN) rather than the raw numbers for readability.
Follow-up 1
Can you explain each ready state and its significance?
Sure! Here is an explanation of each ready state and its significance:
CONNECTING (0): This state indicates that the WebSocket connection is being established. It is the initial state when you create a new WebSocket object.
OPEN (1): This state indicates that the WebSocket connection has been established and is ready to send and receive data. You can start sending and receiving messages in this state.
CLOSING (2): This state indicates that the WebSocket connection is in the process of closing. It means that the connection is being closed, but it is not closed yet. You can still send and receive messages in this state.
CLOSED (3): This state indicates that the WebSocket connection has been closed or could not be opened. Once the connection is closed, you cannot send or receive messages anymore.
Follow-up 2
How would you check the current ready state of a WebSocket?
To check the current ready state of a WebSocket, you can access the readyState property of the WebSocket object. The readyState property returns an integer value representing the current state of the WebSocket connection. Here is an example:
const socket = new WebSocket('wss://example.com');
console.log(socket.readyState);
The readyState property can have one of the following values:
0(CONNECTING): The WebSocket connection is being established.1(OPEN): The WebSocket connection has been established and is ready to send and receive data.2(CLOSING): The WebSocket connection is in the process of closing.3(CLOSED): The WebSocket connection has been closed or could not be opened.
Follow-up 3
What happens when a WebSocket transitions from one state to another?
When a WebSocket transitions from one state to another, certain events are triggered. Here is a summary of what happens:
When a WebSocket transitions from the
CONNECTINGstate to theOPENstate, theopenevent is triggered. This event indicates that the WebSocket connection has been successfully established.When a WebSocket transitions from the
OPENstate to theCLOSINGstate, thecloseevent is triggered. This event indicates that the WebSocket connection is being closed.When a WebSocket transitions from the
CLOSINGstate to theCLOSEDstate, thecloseevent is triggered again. This event indicates that the WebSocket connection has been closed.If there is an error during the WebSocket connection, the
errorevent is triggered, regardless of the current state.
It is important to handle these events appropriately to ensure the proper functioning of your WebSocket application.
4. How can you secure a WebSocket connection?
Use the secure WSS protocol (wss://) instead of plain ws://. WSS runs WebSocket traffic over TLS, so the handshake and all messages are encrypted — protecting against eavesdropping and tampering on the wire, just as HTTPS does for HTTP.
// Encrypted — required in production and on any HTTPS page
const socket = new WebSocket('wss://example.com/socket');
What this involves and what interviewers expect beyond "use wss":
- The server needs a valid TLS certificate;
wss://typically terminates TLS the same way your HTTPS server does. - A page served over HTTPS can't open a
ws://connection (mixed content is blocked) — you must usewss://.
Transport encryption isn't the whole story. Also:
- Authenticate the connection — validate a token/session during the handshake (cookies or a token in the connect URL/subprotocol); WebSockets don't enforce auth for you.
- Validate the
Originheader server-side to mitigate cross-site hijacking (CSWSH). - Validate and rate-limit every incoming message — never trust client input.
Follow-up 1
What is WebSocket Secure (WSS) and how does it work?
WebSocket Secure (WSS) is the encrypted version of the WebSocket protocol (WS). It provides secure communication over the internet by using Transport Layer Security (TLS) or Secure Sockets Layer (SSL) to encrypt the data transmitted between the client and the server.
When a client wants to establish a secure WebSocket connection using WSS, it sends a WebSocket handshake request to the server over a secure HTTPS connection. The server responds with a WebSocket handshake response, and if the handshake is successful, the client and server can start exchanging data over the secure WebSocket connection.
To use WSS, the server needs to have a valid SSL/TLS certificate installed. The certificate is used to authenticate the server and establish a secure connection with the client. The client also verifies the server's certificate to ensure that it is connecting to the correct server.
Follow-up 2
What are the potential security risks with WebSockets?
While WebSockets provide a powerful and efficient way to enable real-time communication between the client and the server, there are some potential security risks that need to be considered:
Cross-Site WebSocket Hijacking (CSWSH): This is a type of attack where an attacker tricks a user's browser into making unintended WebSocket connections to a malicious server. This can lead to unauthorized access to sensitive data or actions on behalf of the user.
Cross-Origin Resource Sharing (CORS) vulnerabilities: If WebSocket connections are not properly secured, they can be vulnerable to Cross-Origin Resource Sharing (CORS) attacks. This can allow an attacker to bypass the same-origin policy and access sensitive data from other domains.
Denial of Service (DoS) attacks: WebSockets can be used to launch Denial of Service (DoS) attacks by flooding the server with a large number of WebSocket connections or sending excessive amounts of data.
To mitigate these risks, it is important to implement proper security measures such as authentication, authorization, and input validation on the server-side, as well as secure WebSocket connection configurations.
Follow-up 3
How can you prevent cross-site WebSocket hijacking?
To prevent Cross-Site WebSocket Hijacking (CSWSH), you can implement the following measures:
Validate the Origin header: The server should validate the
Originheader of the WebSocket handshake request to ensure that it matches the expected origin. This helps prevent unauthorized WebSocket connections from other domains.Use CSRF tokens: Implement Cross-Site Request Forgery (CSRF) protection by using CSRF tokens. The server should generate a unique CSRF token for each user session and include it in the WebSocket handshake request. The client should send the CSRF token along with each WebSocket message, and the server should validate the token to ensure that the request is not forged.
Implement secure session management: Use secure session management techniques to prevent session hijacking. This includes using secure cookies, enforcing secure session handling practices, and regularly rotating session IDs.
By implementing these measures, you can significantly reduce the risk of cross-site WebSocket hijacking and enhance the security of your WebSocket connections.
5. Can you explain how to use the WebSocket API in JavaScript?
Create a WebSocket instance with the server URL, then attach event listeners and use send() to communicate:
const socket = new WebSocket('wss://example.com/chat');
socket.addEventListener('open', () => {
socket.send(JSON.stringify({ type: 'join', room: 'general' }));
});
socket.addEventListener('message', (event) => {
const data = JSON.parse(event.data);
console.log('received', data);
});
socket.addEventListener('error', (e) => console.error('WS error', e));
socket.addEventListener('close', (e) => console.log('closed', e.code));
The four events: open (connected), message (data arrived, on event.data), error, and close. You can use addEventListener (preferred — multiple handlers) or the onopen/onmessage/onerror/onclose properties.
Gotchas worth raising:
- Only
send()onceopenhas fired (orreadyState === WebSocket.OPEN), else it throws. - Messages are strings or binary (
Blob/ArrayBuffer) — serialize objects withJSON.stringify. - Sockets drop; add reconnection with backoff and heartbeat/ping-pong, or use Socket.IO for that out of the box.
Follow-up 1
What are the methods and properties of the WebSocket object?
The WebSocket object has several methods and properties that you can use to interact with the WebSocket server:
WebSocket(url): Constructor that creates a new WebSocket object.WebSocket.readyState: Property that represents the current state of the WebSocket connection.WebSocket.send(data): Method that sends data to the WebSocket server.WebSocket.close(): Method that closes the WebSocket connection.WebSocket.onopen: Event handler that is called when the WebSocket connection is established.WebSocket.onmessage: Event handler that is called when a message is received from the WebSocket server.WebSocket.onerror: Event handler that is called when an error occurs in the WebSocket connection.WebSocket.onclose: Event handler that is called when the WebSocket connection is closed.
Follow-up 2
How would you handle the 'onopen', 'onmessage', and 'onerror' events?
To handle the 'onopen', 'onmessage', and 'onerror' events, you can assign event handler functions to the corresponding properties of the WebSocket object. For example:
const socket = new WebSocket('ws://example.com');
socket.onopen = function(event) {
console.log('WebSocket connection established.');
};
socket.onmessage = function(event) {
console.log('Received message:', event.data);
};
socket.onerror = function(event) {
console.error('WebSocket error:', event);
};
Follow-up 3
Can you give an example of creating a WebSocket, sending a message, and receiving a message?
Sure! Here's an example of how to create a WebSocket, send a message, and receive a message:
const socket = new WebSocket('ws://example.com');
socket.onopen = function(event) {
console.log('WebSocket connection established.');
socket.send('Hello, server!');
};
socket.onmessage = function(event) {
console.log('Received message:', event.data);
};
Live mock interview
Mock interview: JavaScript Web Sockets
- Read your scene and goals
- Talk it out; goals tick off live
- Get a score and stronger lines
Your voice and your AI key never touch our servers; the key stays in this browser and is sent only to Google. Only your round scores are saved to track progress.