QA
Senior LevelExpress JS

How do you route and authenticate HTTP Upgrade requests for WebSockets alongside Express on the same port?

❓ Interview Prompt: Explain handling HTTP Upgrade requests, attaching WebSocketServer (ws) to native http.Server, and verifying authentication cookies before WebSocket handshake.

Binding WebSocket servers directly to Express route paths can cause socket conflicts.

Architecture Pattern:

Attach the WebSocket server ('WebSocketServer({ noServer: true })') to the native 'http.Server' instance:

1
Listen for the HTTP 'upgrade' event on the server instance.
2
Authenticate the incoming WebSocket upgrade request (inspecting cookies or headers).
3
If authorized, complete the WebSocket handshake via 'wss.handleUpgrade()'!

Code Implementation Example

javascript
import express from 'express';
import { WebSocketServer } from 'ws';

const app = express();
const server = app.listen(3000);
const wss = new WebSocketServer({ noServer: true });

// Intercept HTTP Upgrade requests before WebSocket handshake!
server.on('upgrade', (req, socket, head) => {
  const token = req.headers['sec-websocket-protocol'];
  
  if (token === 'valid-secret-token') {
    wss.handleUpgrade(req, socket, head, (ws) => {
      wss.emit('connection', ws, req);
    });
  } else {
    socket.write('HTTP/1.1 401 Unauthorized

');
    socket.destroy();
  }
});
💡Authenticating HTTP Upgrade requests before completing WebSocket handshake on the same port.
🎯 Interview Key Takeaway

Listen for server.on("upgrade") and verify credentials before completing wss.handleUpgrade() on the underlying HTTP server.

#WebSockets#HTTP Upgrade#Architecture#Senior
Back to all Express JS Questions→

More Express JS Interview Questions

Beginner LevelExpress JS

What is Express.js and how does the middleware pipeline work?

Beginner LevelExpress JS

What is the difference between req.params, req.query, and req.body?

Beginner LevelExpress JS

How does express.Router() work for building modular route controllers?