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) }).
Previous
What is the difference between Socket.IO and raw WebSockets?
Next
How do WebSockets work behind a load balancer?
More WebSockets & Real-time Questions
View all →- Intermediate How do you implement a WebSocket server in Node.js using the `ws` library?
- Intermediate What are Socket.IO rooms and namespaces?
- Intermediate How do you handle WebSocket reconnection logic?
- Intermediate What is the difference between Socket.IO and raw WebSockets?
- Intermediate How do WebSockets work behind a load balancer?