📖 Scenario: You are building a chat server using Express and WebSocket. To keep the chat safe, you want to check if users are allowed to connect before letting them join the chat.
🎯 Goal: Build a simple Express server that accepts WebSocket connections only if the client sends a correct token in the connection URL query.
📋 What You'll Learn
Create an Express server with WebSocket support
Check for a token in the WebSocket connection URL query
Allow connection only if the token matches a preset secret
Close the connection if the token is missing or wrong
💡 Why This Matters
🌍 Real World
WebSocket authentication is important in real-time apps like chat, games, or live updates to ensure only authorized users connect.
💼 Career
Understanding how to secure WebSocket connections is a key skill for backend developers working on real-time web applications.
Progress0 / 4 steps
1
Set up Express server and WebSocket
Create an Express server and set up a WebSocket server using the ws library. Store the server in a variable called server and the WebSocket server in a variable called wss.
Express
Hint
Use http.createServer(app) to create the server and pass it to new WebSocket.Server.
2
Define the secret token
Create a constant variable called SECRET_TOKEN and set it to the string "mysecrettoken123".
Express
Hint
Use const SECRET_TOKEN = "mysecrettoken123"; to define the token.
3
Check token on WebSocket connection
Add a wss.on('connection', (ws, request) => { ... }) event listener. Inside it, get the token from request.url query string using new URL(request.url, 'http://localhost'). Then check if the token equals SECRET_TOKEN. If not, close the WebSocket connection with ws.close().
Express
Hint
Use new URL(request.url, 'http://localhost') to parse the URL and get the token with searchParams.get('token').
4
Start the server listening
Add server.listen(3000) to start the server on port 3000.
Express
Hint
Use server.listen(3000) to start the server on port 3000.
Practice
(1/5)
1. In Express with WebSocket, when does authentication usually happen for a WebSocket connection?
easy
A. During the HTTP upgrade request before the WebSocket connection is established
B. After the WebSocket connection is fully established
C. Only when sending the first message over WebSocket
D. Authentication is not needed for WebSocket connections
Solution
Step 1: Understand WebSocket handshake
The WebSocket connection starts with an HTTP upgrade request from client to server.
Step 2: Identify when authentication fits
Authentication must happen during this upgrade request to allow or deny the connection before it opens.
Final Answer:
During the HTTP upgrade request before the WebSocket connection is established -> Option A
Quick Check:
Authentication = HTTP upgrade request [OK]
Hint: Authenticate during upgrade request, not after connection opens [OK]
Common Mistakes:
Trying to authenticate after WebSocket connection opens
Assuming authentication is unnecessary for WebSocket
Authenticating only on first message instead of handshake
2. Which of the following is a correct way to send an authentication token during a WebSocket connection upgrade in Express?
easy
A. Include the token in the WebSocket message after connection opens
B. Send the token as a URL query parameter in the WebSocket URL
C. Send the token in a cookie after the connection is established
D. Send the token in a separate HTTP POST request after connection
Solution
Step 1: Review token sending methods during upgrade
Tokens can be sent in the URL query string or headers during the HTTP upgrade request.
Step 2: Identify valid option
Sending the token as a URL query parameter is a common and valid method to authenticate during upgrade.
Final Answer:
Send the token as a URL query parameter in the WebSocket URL -> Option B
Quick Check:
Token in URL query = valid during upgrade [OK]
Hint: Use URL query or headers to send token during upgrade [OK]
Common Mistakes:
Sending token only after connection opens
Using cookies after connection instead of during upgrade
Sending token in separate HTTP requests unrelated to upgrade
3. Consider this Express WebSocket upgrade handler snippet:
This header is meant for subprotocol negotiation, not for authentication tokens.
Step 2: Recognize handshake impact
Misusing this header can cause handshake failure or client rejection because clients expect specific values here.
Final Answer:
Using 'sec-websocket-protocol' header for token is incorrect and may cause handshake failure -> Option A
Quick Check:
Wrong header for token breaks handshake [OK]
Hint: Use proper headers or URL query for tokens, not subprotocol header [OK]
Common Mistakes:
Assuming any header can carry token safely
Ignoring WebSocket protocol header purpose
Confusing socket.end() and socket.destroy() effects
5. You want to implement token-based authentication for WebSocket connections in Express. Which approach correctly combines token extraction and connection rejection to secure the WebSocket handshake?