Fix Error: WebSocket is not open: readyState 3 (CLOSED) in NestJS
This error occurs when NestJS tries to send a message through a WebSocket connection that has already been closed. Common causes include clients disconnecting unexpectedly, missing connection state checks, or sending after the server-side gateway is destroyed. Fix it by checking readyState before sending and handling disconnection events.
Reading the Stack Trace
Here's what each line means:
- at WebSocket.send (node_modules/ws/lib/websocket.js:439:19): The ws library rejected the send because the WebSocket connection has readyState CLOSED (3).
- at ChatGateway.broadcastMessage (src/gateways/chat.gateway.ts:32:18): Your broadcast function at line 32 iterates over all connected clients but one has already disconnected.
- at ChatGateway.handleMessage (src/gateways/chat.gateway.ts:22:10): The message handler triggers a broadcast to all clients, including those that have disconnected.
Common Causes
1. Broadcasting to disconnected clients
The gateway iterates over all stored client references without checking if each connection is still open.
broadcastMessage(message: string) {
this.server.clients.forEach((client) => {
client.send(message); // Client may be closed
});
}
2. Client disconnects during async operation
A database query or API call takes time, and the client disconnects before the response is ready to send.
@SubscribeMessage('getData')
async handleGetData(client: WebSocket) {
const data = await this.dataService.fetch(); // Takes 5s
client.send(JSON.stringify(data)); // Client disconnected during fetch
}
3. No handleDisconnect cleanup
The gateway does not implement handleDisconnect, so stale client references accumulate.
@WebSocketGateway()
export class ChatGateway {
private clients: Set<WebSocket> = new Set();
handleConnection(client: WebSocket) {
this.clients.add(client);
}
// Missing: handleDisconnect to remove closed clients
}
The Fix
Check each client's readyState before sending to ensure the connection is still open. Implement OnGatewayDisconnect to handle cleanup when clients disconnect. Extract broadcasting into a helper method that filters by connection state.
import { WebSocketGateway, SubscribeMessage, WebSocketServer } from '@nestjs/websockets';
import { Server, WebSocket } from 'ws';
@WebSocketGateway()
export class ChatGateway {
@WebSocketServer()
server: Server;
@SubscribeMessage('message')
handleMessage(client: WebSocket, payload: string) {
this.server.clients.forEach((c) => {
c.send(payload);
});
}
}
import { WebSocketGateway, SubscribeMessage, WebSocketServer, OnGatewayDisconnect } from '@nestjs/websockets';
import { Server, WebSocket } from 'ws';
import { Logger } from '@nestjs/common';
@WebSocketGateway()
export class ChatGateway implements OnGatewayDisconnect {
@WebSocketServer()
server: Server;
private readonly logger = new Logger(ChatGateway.name);
handleDisconnect(client: WebSocket) {
this.logger.log('Client disconnected');
}
@SubscribeMessage('message')
handleMessage(client: WebSocket, payload: string) {
this.broadcast(payload);
}
private broadcast(message: string) {
this.server.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
}
}
Testing the Fix
import { ChatGateway } from './chat.gateway';
import { WebSocket } from 'ws';
describe('ChatGateway', () => {
let gateway: ChatGateway;
beforeEach(() => {
gateway = new ChatGateway();
gateway.server = { clients: new Set() } as any;
});
it('sends to open clients only', () => {
const openClient = { readyState: WebSocket.OPEN, send: jest.fn() };
const closedClient = { readyState: WebSocket.CLOSED, send: jest.fn() };
gateway.server.clients.add(openClient as any);
gateway.server.clients.add(closedClient as any);
gateway.handleMessage(openClient as any, 'hello');
expect(openClient.send).toHaveBeenCalledWith('hello');
expect(closedClient.send).not.toHaveBeenCalled();
});
it('handles disconnect without error', () => {
const client = { readyState: WebSocket.CLOSED } as any;
expect(() => gateway.handleDisconnect(client)).not.toThrow();
});
});
Run your tests:
npm test
Pushing Through CI/CD
git checkout -b fix/nestjs-websocket-readystate,git add src/gateways/chat.gateway.ts src/gateways/__tests__/chat.gateway.spec.ts,git commit -m "fix: check WebSocket readyState before sending messages",git push origin fix/nestjs-websocket-readystate
Your CI config should look something like this:
name: CI
on:
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
- run: npm ci
- run: npm test -- --coverage
- run: npm run build
The Full Manual Process: 18 Steps
Here's every step you just went through to fix this one bug:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the root cause
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- Monitor production to confirm the error is resolved
Total time: 30-60 minutes. For one bug.
Or Let bugstack Fix It in Under 2 minutes
Every step above? bugstack does it automatically.
Step 1: Install the SDK
npm install bugstack-sdk
Step 2: Initialize
import { initBugStack } from 'bugstack-sdk'
initBugStack({ apiKey: process.env.BUGSTACK_API_KEY })
Step 3: There is no step 3.
bugstack handles everything from here:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- Deploys to production (or opens a PR for review)
Time from error to fix deployed: Under 2 minutes.
Human involvement: zero.
Try bugstack Free →No credit card. 5-minute setup. Cancel anytime.
Deploying the Fix (Manual Path)
- Add readyState checks before all WebSocket send operations.
- Implement handleDisconnect to clean up stale connections.
- Add error handling for send failures.
- Run tests to verify broadcast filters closed clients.
- Open a PR, merge after CI, and test with multiple clients in staging.
Frequently Asked Questions
BugStack runs the fix through your existing test suite, generates additional edge-case tests, and validates that no other modules are affected before marking it safe to deploy.
BugStack never pushes directly to production. Every fix goes through a pull request with full CI checks, so your team can review it before merging.
Socket.IO provides automatic reconnection, rooms, and namespaces out of the box. ws is lighter and faster but requires manual implementation of those features. Choose based on your needs.
Implement an exponential backoff strategy that attempts to reconnect when the connection closes unexpectedly. Most Socket.IO clients handle this automatically.