Performance: Authentication in WebSocket connections
This affects the initial connection setup time and ongoing message handling responsiveness in WebSocket communication.
const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080, verifyClient: (info, done) => { const token = extractTokenFromInfo(info); if (authenticate(token)) { done(true); } else { done(false, 401, 'Unauthorized'); } } }); wss.on('connection', function connection(ws) { // User is authenticated once during handshake ws.on('message', function incoming(message) { // Process message directly }); });
const WebSocket = require('ws'); const wss = new WebSocket.Server({ port: 8080 }); wss.on('connection', function connection(ws) { ws.on('message', function incoming(message) { // Authenticate user on every message if (!authenticate(message.token)) { ws.close(); return; } // Process message }); });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Authenticate on every message | N/A (WebSocket messages) | N/A | N/A | [X] Bad |
| Authenticate once during handshake | N/A (WebSocket messages) | N/A | N/A | [OK] Good |
server.on('upgrade', (req, socket, head) => {
const token = new URL(req.url, 'http://localhost').searchParams.get('token');
if (token !== 'secret') {
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);
});
});
What happens if the token is incorrect?server.on('upgrade', (req, socket, head) => {
const token = req.headers['sec-websocket-protocol'];
if (!token || token !== 'valid-token') {
socket.end();
return;
}
wss.handleUpgrade(req, socket, head, ws => {
wss.emit('connection', ws, req);
});
});
What is the main issue with this authentication approach?server.on('upgrade', (req, socket, head) => {
// Extract token
const token = req.headers['authorization']?.split(' ')[1];
// Verify token
if (!token || token !== 'my-secret-token') {
// Reject connection
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
socket.destroy();
return;
}
// Accept connection
wss.handleUpgrade(req, socket, head, ws => {
wss.emit('connection', ws, req);
});
});Pass the test and this pattern moves unknown