How do you handle CORS and origin validation for WebSockets?
Understand why CORS does not protect WebSockets and how to validate the Origin header with an allowlist plus token auth on the server.
Expected Interview Answer
WebSockets are not governed by the browser's CORS mechanism, so you handle cross-origin safety by validating the Origin header on the server during the handshake and rejecting connections whose origin is not on your allowlist. Combine this with a connection token, because the Origin header alone can be forged by non-browser clients.
A browser always attaches an accurate Origin header to the WebSocket upgrade request, but unlike fetch it does not perform a preflight or enforce CORS response headers — the connection proceeds regardless of Access-Control-Allow-Origin. That means the server is solely responsible: read the Origin header, compare it to a strict allowlist, and close the socket if it does not match. Because scripts and tools outside the browser can send any Origin they like, origin validation stops browser-based CSWSH but must be paired with real authentication for full protection.
- Blocks browser-based cross-site connections
- Prevents Cross-Site WebSocket Hijacking
- Keeps authorization logic on the trusted server
- Works alongside token authentication
- Simple allowlist is easy to audit
AI Mentor Explanation
Imagine the team dressing room where the gatekeeper checks each person's accreditation lanyard against the day's approved list before letting them in. The lanyard is the Origin header, and the printed list is your allowlist. A forged lanyard can slip past a lazy check, which is why the captain also knows every player by face — that second check is your token auth backing up the origin gate.
Step-by-Step Explanation
Step 1
Understand the difference
Recognize that browsers do not apply CORS preflight or Access-Control headers to WebSocket upgrades — the connection is not blocked by CORS.
Step 2
Read the Origin header
During the handshake, extract the Origin header from the upgrade request on the server.
Step 3
Compare against an allowlist
Match the origin against a strict, explicit allowlist of trusted sites rather than a wildcard.
Step 4
Reject mismatches
Close the socket with an appropriate status if the origin is missing or not allowlisted.
Step 5
Layer authentication
Add a verified token because non-browser clients can forge the Origin header, so origin checks alone are not enough.
What Interviewer Expects
- Awareness that CORS does not apply to WebSocket connections
- Knowing browsers always send an accurate Origin header
- Server-side origin allowlisting during the handshake
- Understanding that non-browser clients can spoof Origin
- Pairing origin checks with token authentication
Common Mistakes
- Assuming Access-Control-Allow-Origin restricts WebSockets
- Allowlisting with a wildcard that accepts any origin
- Trusting the Origin header as proof of identity
- Doing origin checks only on the client
- Skipping origin validation because TLS is enabled
Best Answer (HR Friendly)
“Unlike normal web requests, WebSockets are not automatically restricted by the browser to trusted sites, so the server must check where each connection is coming from and only accept approved origins. Since that check can be faked by non-browser tools, you also require a login token to be sure who is connecting.”
Code Example
const ALLOWED = new Set(['https://app.example.com', 'https://admin.example.com'])
server.on('upgrade', (req, socket, head) => {
const origin = req.headers.origin
if (!origin || !ALLOWED.has(origin)) {
socket.write('HTTP/1.1 403 Forbidden\r\n\r\n')
socket.destroy()
return
}
wss.handleUpgrade(req, socket, head, (ws) => {
wss.emit('connection', ws, req)
})
})Follow-up Questions
- Why does the browser not enforce CORS on WebSocket upgrades?
- Can a non-browser client fake the Origin header, and what does that imply?
- Why should the allowlist avoid wildcards?
- How does origin validation relate to CSWSH?
- Where in the connection lifecycle should you reject a bad origin?
MCQ Practice
1. How does CORS apply to WebSocket connections?
Browsers do not enforce CORS on WebSocket upgrades, so the server is responsible for reading and validating the Origin header.
2. Why is origin validation not sufficient by itself?
Tools and scripts outside a browser can send any Origin value, so origin checks must be paired with real authentication.
3. The best allowlist strategy is to...
An explicit allowlist of trusted origins is auditable and avoids accepting arbitrary sites.
Flash Cards
Does CORS block WebSockets? — No. Browsers do not apply CORS to WebSocket upgrades, so the server must validate the Origin header itself.
Where do you validate origin? — On the server during the handshake, comparing the Origin header to a strict allowlist before the socket opens.
Can Origin be spoofed? — Yes, by non-browser clients — so origin validation must be paired with token authentication.
Why avoid wildcards? — A wildcard allowlist accepts any site, defeating the point of origin validation.
Continue Learning
Related Interview Questions
What are common WebSocket security vulnerabilities and how do you mitigate them?
hard
Should a WebSocket be authenticated during the HTTP handshake or with a first application message, and what are the trade-offs?
hard
What are WebSockets and what problems do they solve?
easy
What is the difference between WebSockets and HTTP?
medium