Isomorphic WebSocket implementation that works across Node.js and browser environments
npx @tessl/cli install tessl/npm-isomorphic-ws@5.0.00
# Isomorphic WebSocket
1
2
Isomorphic WebSocket provides a unified WebSocket interface that works seamlessly across Node.js and browser environments. It acts as a compatibility layer that uses the 'ws' package in Node.js and falls back to native WebSocket APIs in browsers, enabling developers to write WebSocket code once and run it everywhere.
3
4
## Package Information
5
6
- **Package Name**: isomorphic-ws
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install isomorphic-ws ws`
10
11
Note: Both `isomorphic-ws` and `ws` must be installed, as `ws` is a peer dependency required for Node.js functionality.
12
13
## Core Imports
14
15
```javascript
16
const WebSocket = require('isomorphic-ws');
17
```
18
19
ES Modules:
20
21
```javascript
22
import WebSocket from 'isomorphic-ws';
23
```
24
25
## Basic Usage
26
27
```javascript
28
import WebSocket from 'isomorphic-ws';
29
30
// Create WebSocket connection
31
const ws = new WebSocket('wss://echo.websocket.org/');
32
33
// Set up event handlers
34
ws.onopen = function open() {
35
console.log('Connected to WebSocket server');
36
ws.send('Hello Server!');
37
};
38
39
ws.onmessage = function incoming(event) {
40
console.log('Received:', event.data);
41
};
42
43
ws.onclose = function close() {
44
console.log('Connection closed');
45
};
46
47
ws.onerror = function error(err) {
48
console.error('WebSocket error:', err);
49
};
50
```
51
52
## Architecture
53
54
Isomorphic WebSocket uses environment detection to provide the appropriate WebSocket implementation:
55
56
- **Node.js Environment**: Re-exports the entire 'ws' package, providing full server-side WebSocket capabilities
57
- **Browser Environment**: Uses native WebSocket with fallback to MozWebSocket for older Firefox versions
58
- **TypeScript Support**: Full type definitions that reference the 'ws' package types
59
60
## Capabilities
61
62
### WebSocket Constructor
63
64
Creates a new WebSocket connection with isomorphic compatibility.
65
66
```javascript { .api }
67
/**
68
* Create a new WebSocket connection
69
* @param {string} url - WebSocket server URL (ws:// or wss://)
70
* @param {string|string[]} [protocols] - Optional subprotocol(s)
71
* @param {object} [options] - Options (Node.js only, ignored in browsers)
72
* @returns {WebSocket} WebSocket instance
73
*/
74
new WebSocket(url, protocols?, options?)
75
```
76
77
**Usage Example:**
78
79
```javascript
80
// Basic connection
81
const ws = new WebSocket('wss://echo.websocket.org/');
82
83
// With subprotocols
84
const ws = new WebSocket('wss://example.com/', ['protocol1', 'protocol2']);
85
86
// With options (Node.js only)
87
const ws = new WebSocket('wss://example.com/', {
88
headers: { 'User-Agent': 'MyApp/1.0' }
89
});
90
```
91
92
### WebSocket Instance Properties
93
94
Properties available on WebSocket instances, following the standard WebSocket API.
95
96
```javascript { .api }
97
/**
98
* Current connection state
99
* @type {number} 0=CONNECTING, 1=OPEN, 2=CLOSING, 3=CLOSED
100
*/
101
ws.readyState
102
103
/**
104
* WebSocket server URL
105
* @type {string}
106
*/
107
ws.url
108
109
/**
110
* Selected subprotocol
111
* @type {string}
112
*/
113
ws.protocol
114
115
/**
116
* Bytes queued for transmission
117
* @type {number}
118
*/
119
ws.bufferedAmount
120
121
/**
122
* Negotiated extensions
123
* @type {string}
124
*/
125
ws.extensions
126
127
/**
128
* Binary data type ('blob' or 'arraybuffer')
129
* @type {string}
130
*/
131
ws.binaryType
132
```
133
134
### WebSocket Instance Methods
135
136
Methods available on WebSocket instances for controlling the connection and sending data.
137
138
```javascript { .api }
139
/**
140
* Send data through the WebSocket connection
141
* @param {string|Buffer|ArrayBuffer|Blob} data - Data to send
142
*/
143
ws.send(data)
144
145
/**
146
* Close the WebSocket connection
147
* @param {number} [code] - Close code (1000 = normal closure)
148
* @param {string} [reason] - Reason for closing
149
*/
150
ws.close(code?, reason?)
151
152
/**
153
* Add event listener
154
* @param {string} type - Event type ('open', 'close', 'message', 'error')
155
* @param {function} listener - Event handler function
156
*/
157
ws.addEventListener(type, listener)
158
159
/**
160
* Remove event listener
161
* @param {string} type - Event type
162
* @param {function} listener - Event handler function to remove
163
*/
164
ws.removeEventListener(type, listener)
165
166
/**
167
* Dispatch event
168
* @param {Event} event - Event to dispatch
169
* @returns {boolean} true if event was handled
170
*/
171
ws.dispatchEvent(event)
172
```
173
174
### WebSocket Event Handlers
175
176
Event handler properties for WebSocket lifecycle events.
177
178
```javascript { .api }
179
/**
180
* Connection opened event handler
181
* @type {function|null}
182
*/
183
ws.onopen = function(event) { /* handle open */ }
184
185
/**
186
* Connection closed event handler
187
* @type {function|null}
188
*/
189
ws.onclose = function(event) {
190
// event.code - close code
191
// event.reason - close reason
192
// event.wasClean - boolean indicating clean close
193
}
194
195
/**
196
* Message received event handler
197
* @type {function|null}
198
*/
199
ws.onmessage = function(event) {
200
// event.data - received data (string, Buffer, ArrayBuffer, etc.)
201
}
202
203
/**
204
* Error event handler
205
* @type {function|null}
206
*/
207
ws.onerror = function(event) {
208
// event.error - error object (Node.js)
209
// In browsers, error details may be limited
210
}
211
```
212
213
### WebSocket Constants
214
215
Static constants defining connection states.
216
217
```javascript { .api }
218
/**
219
* Connection state constants
220
*/
221
WebSocket.CONNECTING = 0 // Connection is being established
222
WebSocket.OPEN = 1 // Connection is open and ready
223
WebSocket.CLOSING = 2 // Connection is closing
224
WebSocket.CLOSED = 3 // Connection is closed
225
```
226
227
## Environment-Specific Behavior
228
229
### Node.js Environment
230
231
In Node.js, isomorphic-ws re-exports the 'ws' package, providing access to all its features:
232
233
- Full WebSocket Server implementation
234
- Additional constructor options (headers, certificates, etc.)
235
- Node.js-specific features like compression and extensions
236
- Buffer support for binary data
237
238
### Browser Environment
239
240
In browsers, isomorphic-ws uses the native WebSocket implementation:
241
242
- Standard WebSocket API only
243
- No server implementation
244
- Constructor options parameter is ignored/unsupported
245
- Automatic fallback to MozWebSocket for older Firefox versions
246
247
## Error Handling
248
249
Common error scenarios and handling patterns:
250
251
```javascript
252
const ws = new WebSocket('wss://example.com/');
253
254
ws.onerror = function(event) {
255
// Connection errors, network issues, etc.
256
console.error('WebSocket error occurred');
257
};
258
259
ws.onclose = function(event) {
260
if (!event.wasClean) {
261
// Connection closed unexpectedly
262
console.log('Connection lost, attempting to reconnect...');
263
}
264
};
265
266
// Handle connection timeout
267
const connectionTimeout = setTimeout(() => {
268
if (ws.readyState === WebSocket.CONNECTING) {
269
ws.close();
270
console.error('Connection timeout');
271
}
272
}, 10000);
273
274
ws.onopen = function() {
275
clearTimeout(connectionTimeout);
276
};
277
```
278
279
## TypeScript Support
280
281
Full TypeScript support is provided via type definitions:
282
283
```typescript
284
import WebSocket from 'isomorphic-ws';
285
286
// Type-safe WebSocket usage
287
const ws: WebSocket = new WebSocket('wss://example.com/');
288
289
ws.onmessage = (event: MessageEvent) => {
290
const data: string = event.data;
291
console.log('Received:', data);
292
};
293
```
294
295
**Requirements:**
296
- Install `@types/ws` for full type support
297
- Types are compatible with both Node.js and browser environments