How do you authenticate WebSocket connections?

Answer

WebSocket connections lack cookie-based auth by default after the protocol upgrade, so authentication must be handled explicitly. Three common approaches: (1) Query parameter token — pass a JWT or session token in the WebSocket URL: new WebSocket('wss://api.example.com/ws?token=xxx'); the server validates it in the connection event handler. Simple but tokens appear in server logs; (2) First message authentication — establish the WebSocket connection unauthenticated, then send credentials as the first message; the server authenticates before allowing further messages; (3) Cookie-based — WebSocket upgrade requests send cookies automatically, so if the user has an HTTP session cookie, the server can read it from the upgrade request headers (req.headers.cookie in Node.js). In Socket.IO, use the auth option: io({ auth: { token: 'xxx' } }) and validate in middleware with io.use((socket, next) => { verifyToken(socket.handshake.auth.token) }).