3. WebSocket URIs
This specification defines two URI schemes using ABNF syntax and terminology from RFC 3986.
URI Scheme Definitions
ws-URI (Unencrypted)
ws-URI = "ws:" "//" host [ ":" port ] path [ "?" query ]
- Scheme name: ws
- Default port: 80
- Purpose: Unencrypted WebSocket connections
Examples:
ws://example.com/socket
ws://example.com:8080/chat
ws://192.168.1.1/data
wss-URI (TLS Encrypted)
wss-URI = "wss:" "//" host [ ":" port ] path [ "?" query ]
- Scheme name: wss
- Default port: 443
- Purpose: TLS-encrypted WebSocket connections
Examples:
wss://example.com/socket
wss://secure.example.com:8443/chat
URI Component Description
host
The host component can be:
- Domain name:
example.com - IPv4 address:
192.168.1.1 - IPv6 address:
[2001:db8::1]
port
- If omitted, uses default port (80 for ws, 443 for wss)
- Can explicitly specify any valid port
path
- Must start with
/ - Defaults to
/if empty
query
- Optional query parameters
- Format:
?key1=value1&key2=value2
Security Considerations
Recommended: Use wss://
In production environments, strongly recommended to use wss:// (TLS encrypted) instead of ws://:
✅ Advantages of wss://:
- Encrypted transmission, prevents man-in-the-middle attacks
- Prevents data eavesdropping
- Better firewall traversal
- Browser security policy support (e.g., mixed content policy)
❌ Risks of ws://:
- Data transmitted in plaintext
- Easily intercepted and tampered
- Browsers may block ws:// connections from HTTPS pages
Origin Validation
Servers should validate the Origin header to ensure connections only from trusted sources:
// Server-side validation example
const allowedOrigins = ['https://example.com', 'https://app.example.com'];
const origin = request.headers['origin'];
if (!allowedOrigins.includes(origin)) {
response.status(403).send('Forbidden');
}
URI Parsing Examples
Example 1: Complete URI
wss://chat.example.com:8443/room/general?user=alice
Parsed result:
- Scheme: wss
- Host: chat.example.com
- Port: 8443
- Path: /room/general
- Query: user=alice
Example 2: Minimal URI
ws://example.com
Parsed result:
- Scheme: ws
- Host: example.com
- Port: 80 (default)
- Path: / (default)
- Query: (none)
Example 3: IPv6 Address
wss://[2001:db8::1]:443/socket
Parsed result:
- Scheme: wss
- Host: 2001:db8::1
- Port: 443
- Path: /socket
Browser Usage Examples
JavaScript Client
// Connect to unencrypted WebSocket
const ws1 = new WebSocket('ws://example.com/socket');
// Connect to TLS encrypted WebSocket (recommended)
const ws2 = new WebSocket('wss://example.com/socket');
// With port and path
const ws3 = new WebSocket('wss://example.com:8443/chat/room1');
// With query parameters
const ws4 = new WebSocket('wss://example.com/socket?token=abc123');
Related Specifications
- RFC 3986: Uniform Resource Identifier (URI): Generic Syntax
- RFC 2818: HTTP Over TLS
Reference Links
- Previous Chapter: 2. Conformance Requirements
- Next Chapter: 4. Opening Handshake
- Implementation Guide: WebSocket URI Details