Constructing WebSocket URLs
1. Building Basic URL
| Component | Example | Notes |
|---|---|---|
| Scheme | ws:// | Unencrypted, port 80 |
| Host | api.example.com | FQDN or IP |
| Port | :8080 | Optional |
| Path | /socket | Endpoint route |
| Query | ?token=abc | Optional params |
2. Building Secure URL
| Scheme | Transport | Default Port |
|---|---|---|
ws:// | Plain TCP | 80 |
wss:// | TLS | 443 |
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 / URLSearchParams | Safer 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.host | Inherit 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 |
9. Validating URL Format
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 |
|---|---|
/ws | wss://host/ws |
./stream | Resolve against current path |