Constructing WebSocket URLs
1. Building Basic URL
Component Example Notes
Scheme ws://Unencrypted, port 80
Host api.example.comFQDN or IP
Port :8080Optional
Path /socketEndpoint route
Query ?token=abcOptional params
Example: Basic ws URL
const ws = new WebSocket ( "ws://api.example.com:8080/socket" );
2. Building Secure URL
Scheme Transport Default Port
ws://Plain TCP 80
wss://TLS 443
Example: TLS WebSocket
const ws = new WebSocket ( "wss://realtime.example.com/v1/stream" );
Warning: Browsers block ws:// from https:// pages (mixed content). Always use wss:// in production.
3. Adding Query Parameters
Purpose Example Param
Auth token ?token=eyJhbGc...
Channel ?channel=prices
Client ID ?clientId=uuid
Version ?v=2
Example: URL builder
const url = new URL ( "wss://api.example.com/stream" );
url.searchParams. set ( "token" , token);
url.searchParams. set ( "channel" , "btc-usd" );
const ws = new WebSocket (url);
4. Encoding URL Components
Function Use For
encodeURIComponent()Param values, path segments
URL / URLSearchParamsSafer composition
encodeURI()Whole URLs (rare)
5. Using Dynamic Hosts
Example: Same-host WS
const proto = location.protocol === "https:" ? "wss:" : "ws:" ;
const ws = new WebSocket ( `${ proto }//${ location . host }/ws` );
Source Use
location.hostInherit current origin
Env var Per-environment endpoint
Service discovery Cluster-aware routing
6. Handling Port Numbers
Scenario Recommendation
Public prod Use 443 (wss) — avoids corporate firewalls
Dev/local Custom port OK (e.g. 3000, 8080)
Container Map internal port to standard externally
7. Using Path Parameters
Example: REST-style path
const roomId = encodeURIComponent (room);
const ws = new WebSocket ( `wss://api.example.com/rooms/${ roomId }/chat` );
Pattern Example
Resource ID /users/:id/feed
Version /v2/stream
Tenant /t/:tenantId/ws
8. Implementing URL Patterns
Pattern Use Case
Single endpoint + msg routing One /ws, dispatch by message type
Per-feature endpoints /chat, /notifications, /prices
Per-room endpoint /rooms/:id
Example: Validation
function isValidWsUrl ( u ) {
try {
const url = new URL (u);
return url.protocol === "ws:" || url.protocol === "wss:" ;
} catch { return false ; }
}
Check Reason
Scheme Must be ws/wss
Host Non-empty
No fragment Spec forbids #
10. Handling Relative URLs
Note: The WebSocket constructor requires an absolute URL with ws / wss scheme. Resolve relatives manually via new URL(path, location.href) and rewrite the scheme.
Input Resolution
/wswss://host/ws
./streamResolve against current path