Authentication in WebSocket connections helps verify who is connecting. It keeps your app safe by allowing only trusted users to communicate.
Authentication in WebSocket connections in Express
const WebSocket = require('ws'); const wss = new WebSocket.Server({ noServer: true }); server.on('upgrade', (request, socket, head) => { // Extract token from request headers or URL const token = extractToken(request); if (isValidToken(token)) { wss.handleUpgrade(request, socket, head, (ws) => { wss.emit('connection', ws, request); }); } else { socket.destroy(); } });
Authentication usually happens during the HTTP upgrade request before WebSocket connection is established.
You can extract tokens from headers, cookies, or URL query parameters.
sec-websocket-protocol header to pass a token for authentication.const token = request.headers['sec-websocket-protocol']; if (token === 'my-secret-token') { // Accept connection }
const url = new URL(request.url, 'http://localhost'); const token = url.searchParams.get('token'); if (token === 'valid-token') { // Accept connection }
This example shows a simple WebSocket server using Express's HTTP server. It checks a token from the URL query during the upgrade request. If the token is correct, it accepts the connection and sends a welcome message. Otherwise, it rejects the connection.
const http = require('http'); const express = require('express'); const WebSocket = require('ws'); const app = express(); const server = http.createServer(app); const wss = new WebSocket.Server({ noServer: true }); function isValidToken(token) { return token === 'secret123'; } server.on('upgrade', (request, socket, head) => { const url = new URL(request.url, 'http://localhost'); const token = url.searchParams.get('token'); if (!isValidToken(token)) { socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n'); socket.destroy(); return; } wss.handleUpgrade(request, socket, head, (ws) => { wss.emit('connection', ws, request); }); }); wss.on('connection', (ws) => { ws.send('Welcome! You are authenticated.'); ws.on('message', (message) => { ws.send(`You said: ${message}`); }); }); server.listen(8080, () => { console.log('Server listening on http://localhost:8080'); });
Always validate tokens securely, for example by checking against a database or using JWT verification.
Do not trust tokens sent from the client without verification.
Use secure WebSocket (wss://) in production to protect data in transit.
Authentication happens during the HTTP upgrade request before WebSocket connection starts.
Tokens can be sent via headers or URL query parameters for verification.
Reject unauthorized connections by closing the socket early.