How It Works Features Pricing Blog Error Guides
Log In Start Free Trial
NestJS · TypeScript/React

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

Error: WebSocket is not open: readyState 3 (CLOSED) at WebSocket.send (node_modules/ws/lib/websocket.js:439:19) at ChatGateway.broadcastMessage (src/gateways/chat.gateway.ts:32:18) at ChatGateway.handleMessage (src/gateways/chat.gateway.ts:22:10) at WebSocketsController.pickResult (node_modules/@nestjs/websockets/web-sockets-controller.js:74:44) at /node_modules/@nestjs/websockets/web-sockets-controller.js:45:52 at WebSocket.emit (node:events:513:28) at Receiver.receiverOnMessage (node_modules/ws/lib/websocket.js:1184:20) at Receiver.dataMessage (node_modules/ws/lib/receiver.js:528:14) at Receiver.getData (node_modules/ws/lib/receiver.js:446:17) at Receiver.startLoop (node_modules/ws/lib/receiver.js:148:22)

Here's what each line means:

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.

Before (broken)
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);
    });
  }
}
After (fixed)
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:

  1. Notice the error alert or see it in your monitoring tool
  2. Open the error dashboard and read the stack trace
  3. Identify the file and line number from the stack trace
  4. Open your IDE and navigate to the file
  5. Read the surrounding code to understand context
  6. Reproduce the error locally
  7. Identify the root cause
  8. Write the fix
  9. Run the test suite locally
  10. Fix any failing tests
  11. Write new tests covering the edge case
  12. Run the full test suite again
  13. Create a new git branch
  14. Commit and push your changes
  15. Open a pull request
  16. Wait for code review
  17. Merge and deploy to production
  18. 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:

  1. Captures the stack trace and request context
  2. Pulls the relevant source files from your GitHub repo
  3. Analyzes the error and understands the code context
  4. Generates a minimal, verified fix
  5. Runs your existing test suite
  6. Pushes through your CI/CD pipeline
  7. 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)

  1. Add readyState checks before all WebSocket send operations.
  2. Implement handleDisconnect to clean up stale connections.
  3. Add error handling for send failures.
  4. Run tests to verify broadcast filters closed clients.
  5. 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.