Constructing WebSocket URLs

1. Building Basic URL

ComponentExampleNotes
Schemews://Unencrypted, port 80
Hostapi.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

SchemeTransportDefault Port
ws://Plain TCP80
wss://TLS443

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

PurposeExample 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

FunctionUse 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`);
SourceUse
location.hostInherit current origin
Env varPer-environment endpoint
Service discoveryCluster-aware routing

6. Handling Port Numbers

ScenarioRecommendation
Public prodUse 443 (wss) — avoids corporate firewalls
Dev/localCustom port OK (e.g. 3000, 8080)
ContainerMap 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`);
PatternExample
Resource ID/users/:id/feed
Version/v2/stream
Tenant/t/:tenantId/ws

8. Implementing URL Patterns

PatternUse Case
Single endpoint + msg routingOne /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; }
}
CheckReason
SchemeMust be ws/wss
HostNon-empty
No fragmentSpec 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.
InputResolution
/wswss://host/ws
./streamResolve against current path