Skip to content

websocket service don't working by command ng serve #33515

Description

@zhangcongmr

Command

serve

Is this a regression?

  • Yes, this behavior used to work in the previous version

The previous version in which this bug was not present was

No response

Description

For Angular SSR APP, The websocket service can only be used in the condition of starting server by command 'start:ssr:dev', that is the following condition is true.

isMainModule(import.meta.url) || process.env['pm_id']

The code is like this:

src/server.ts

/**
 * Start the server if this module is the main entry point, or it is ran via PM2.
 * The server listens on the port defined by the `PORT` environment variable, or defaults to 4000.
 */
if (isMainModule(import.meta.url) || process.env['pm_id']) {
  const port = process.env['PORT'] || 4000;
  const httpServer = app.listen(port, (error: any) => {
    if (error) {
      throw error;
    }
    console.log(`Node Express server listening on http://localhost:${port}`);
  });

  // --- WebSocket PTY ---
  const wss = new WebSocketServer({ noServer: true });

  httpServer.on('upgrade', (req, socket, head) => {
    const url = new URL(req.url || '/', `http://${req.headers.host}`);

    if (url.pathname === '/ws/terminal') {
      const token = url.searchParams.get('token');
      if (!token || !tokenManager.verify(token)) {
        socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
        socket.destroy();
        return;
      }
      wss.handleUpgrade(req, socket, head, (ws) => {
        wss.emit('connection', ws, req);
      });
    } else {
      socket.destroy();
    }
  });

  wss.on('connection', (ws, _req) => {
    let ptyId: string | null = null;

    ws.on('message', (data) => {
	   console.log("......")
    });

    ws.on('close', () => { });
    ws.on('error', () => {  });
  });
}

Th command 'ng serve' can also start the Angular SSR App , but the websocket service will not working because the condition above is false.
I ask the AI for the answer
`
I: Can the code of websocket service be moved beyond the judgment conditions?

AI: In the ng serve mode, Angular CLI uses its own internal server and will not create your httpServer at all. Therefore, even if the WebSocket code is moved out, no server can be bound.
`
Can the websocket be supported by the 'ng serve' ?

Minimal Reproduction

The websocket service can be defiition outsode the main httpServer code.

Exception or Error


Your Environment

_                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/


Angular CLI       : 21.2.2
Angular           : 21.2.4
Node.js           : 24.16.0
Package Manager   : pnpm 11.4.0
Operating System  : win32 x64

┌───────────────────────────────────┬───────────────────┬───────────────────┐
│ Package                           │ Installed Version │ Requested Version │
├───────────────────────────────────┼───────────────────┼───────────────────┤
│ @angular/animations               │ 21.2.4            │ ^21.2.4           │
│ @angular/build                    │ 21.2.2            │ ^21.2.2           │
│ @angular/cdk                      │ 20.2.14           │ ^20.2.14          │
│ @angular/cli                      │ 21.2.2            │ ^21.2.2           │
│ @angular/common                   │ 21.2.4            │ ^21.2.4           │
│ @angular/compiler                 │ 21.2.4            │ ^21.2.4           │
│ @angular/compiler-cli             │ 21.2.4            │ ^21.2.4           │
│ @angular/core                     │ 21.2.4            │ ^21.2.4           │
│ @angular/forms                    │ 21.2.4            │ ^21.2.4           │
│ @angular/platform-browser         │ 21.2.4            │ ^21.2.4           │
│ @angular/platform-browser-dynamic │ 21.2.4            │ ^21.2.4           │
│ @angular/platform-server          │ 21.2.4            │ ^21.2.4           │
│ @angular/router                   │ 21.2.4            │ ^21.2.4           │
│ @angular/ssr                      │ 21.2.2            │ ^21.2.2           │
│ typescript                        │ 5.9.3             │ ~5.9.3            │
└───────────────────────────────────┴───────────────────┴───────────────────┘

Anything else relevant?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Fields

    No fields configured for Enhancement.

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions