Authenticate WebSocket connection
Authenticate a WebSocket connection during the HTTP upgrade by checking a token before handleUpgrade, and reject with 401 if it fails.
A WebSocket starts as an HTTP GET that asks to upgrade. The server can inspect that request and refuse the upgrade before a socket exists.
import { createServer } from 'node:http';
import { WebSocketServer } from 'ws';
const wss = new WebSocketServer({ noServer: true });
const server = createServer();
server.on('upgrade', (req, socket, head) => {
const url = new URL(req.url, 'http://localhost');
const ticket = url.searchParams.get('ticket');
if (!isValidTicket(ticket)) {
socket.write('HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n');
socket.destroy();
return;
}
wss.handleUpgrade(req, socket, head, (ws) => {
wss.emit('connection', ws, req);
});
});
function isValidTicket(ticket) {
return ticket === 'one-time-ticket'; // look up and delete a real ticket here
}
server.listen(3000);Browsers cannot add an Authorization header to new WebSocket(url), so the credential has to travel another way: a cookie, which the browser sends automatically, or a short-lived single-use ticket in the query string, as shown here. The client first calls a normal authenticated endpoint to get a ticket that expires in seconds.
Never put the long-lived access token in the URL, because URLs end up in logs. If you use cookies, check the Origin header in the upgrade handler: WebSockets are not covered by the same-origin policy, and without that check any site can open a socket with your user's cookie. See [the ws documentation on noServer](https://github.com/websockets/ws/blob/master/doc/ws.md#new-websocketserveroptions-callback).