0
# Network & Communication
1
2
HTTP client utilities, WebSocket management, and browser communication APIs for data fetching, real-time communication, and inter-tab messaging.
3
4
## Capabilities
5
6
### HTTP Client
7
8
#### useFetch
9
10
Comprehensive reactive fetch wrapper with extensive configuration options.
11
12
```typescript { .api }
13
/**
14
* Reactive fetch wrapper with extensive options
15
* @param url - Request URL (reactive)
16
* @param options - Standard fetch options
17
* @param useFetchOptions - VueUse specific options
18
* @returns Fetch utilities and state
19
*/
20
function useFetch<T>(
21
url: MaybeRefOrGetter<string>,
22
options?: RequestInit,
23
useFetchOptions?: UseFetchOptions
24
): UseFetchReturn<T> & PromiseLike<UseFetchReturn<T>>;
25
26
interface UseFetchReturn<T> {
27
// State
28
isFinished: Ref<boolean>;
29
isFetching: Ref<boolean>;
30
aborted: Ref<boolean>;
31
statusCode: Ref<number | null>;
32
response: Ref<Response | null>;
33
error: Ref<any>;
34
data: Ref<T | null>;
35
36
// Methods
37
abort: () => void;
38
execute: (throwOnFailed?: boolean) => Promise<UseFetchReturn<T>>;
39
get: () => UseFetchReturn<T> & PromiseLike<UseFetchReturn<T>>;
40
post: (payload?: MaybeRefOrGetter<unknown>, type?: string) => UseFetchReturn<T> & PromiseLike<UseFetchReturn<T>>;
41
put: (payload?: MaybeRefOrGetter<unknown>, type?: string) => UseFetchReturn<T> & PromiseLike<UseFetchReturn<T>>;
42
delete: () => UseFetchReturn<T> & PromiseLike<UseFetchReturn<T>>;
43
patch: (payload?: MaybeRefOrGetter<unknown>, type?: string) => UseFetchReturn<T> & PromiseLike<UseFetchReturn<T>>;
44
head: () => UseFetchReturn<T> & PromiseLike<UseFetchReturn<T>>;
45
options: () => UseFetchReturn<T> & PromiseLike<UseFetchReturn<T>>;
46
47
// Type helpers
48
json: <JSON = any>() => UseFetchReturn<JSON> & PromiseLike<UseFetchReturn<JSON>>;
49
text: () => UseFetchReturn<string> & PromiseLike<UseFetchReturn<string>>;
50
blob: () => UseFetchReturn<Blob> & PromiseLike<UseFetchReturn<Blob>>;
51
arrayBuffer: () => UseFetchReturn<ArrayBuffer> & PromiseLike<UseFetchReturn<ArrayBuffer>>;
52
formData: () => UseFetchReturn<FormData> & PromiseLike<UseFetchReturn<FormData>>;
53
}
54
55
interface UseFetchOptions {
56
immediate?: boolean;
57
refetch?: MaybeRefOrGetter<boolean>;
58
initialData?: any;
59
timeout?: number;
60
beforeFetch?: (ctx: BeforeFetchContext) => Promise<Partial<BeforeFetchContext> | void> | Partial<BeforeFetchContext> | void;
61
afterFetch?: (ctx: AfterFetchContext) => Promise<Partial<AfterFetchContext>> | Partial<AfterFetchContext>;
62
onFetchError?: (ctx: OnFetchErrorContext) => Promise<Partial<OnFetchErrorContext>> | Partial<OnFetchErrorContext>;
63
updateDataOnError?: boolean;
64
}
65
```
66
67
**Usage Examples:**
68
69
```typescript
70
import { useFetch } from "@vueuse/core";
71
72
// Basic GET request
73
const { data, isFetching, error } = useFetch('/api/users').json();
74
75
// POST request with payload
76
const { data, execute } = useFetch('/api/users', {
77
immediate: false
78
}).post({ name: 'John', email: 'john@example.com' });
79
80
await execute();
81
82
// Reactive URL
83
const userId = ref('123');
84
const { data } = useFetch(computed(() => `/api/users/${userId.value}`)).json();
85
86
// With interceptors
87
const { data } = useFetch('/api/protected', {
88
beforeFetch({ url, options }) {
89
options.headers = {
90
...options.headers,
91
Authorization: `Bearer ${token.value}`,
92
};
93
return { options };
94
},
95
afterFetch(ctx) {
96
ctx.data = transformData(ctx.data);
97
return ctx;
98
}
99
}).json();
100
101
// Error handling
102
const { data, error, statusCode } = useFetch('/api/data', {
103
onFetchError({ error, response }) {
104
console.error('Fetch failed:', error);
105
if (response?.status === 401) {
106
// Handle unauthorized
107
redirectToLogin();
108
}
109
}
110
}).json();
111
```
112
113
#### createFetch
114
115
Create a custom fetch composable with base configuration.
116
117
```typescript { .api }
118
/**
119
* Create a custom fetch composable with base configuration
120
* @param config - Base configuration for all requests
121
* @returns Configured fetch function
122
*/
123
function createFetch(config?: CreateFetchOptions): typeof useFetch;
124
125
interface CreateFetchOptions {
126
baseUrl?: MaybeRefOrGetter<string>;
127
combination?: 'overwrite' | 'chain';
128
options?: RequestInit;
129
fetchOptions?: Omit<UseFetchOptions, 'immediate'>;
130
}
131
```
132
133
**Usage Examples:**
134
135
```typescript
136
import { createFetch } from "@vueuse/core";
137
138
// Create API client
139
const useAPI = createFetch({
140
baseUrl: 'https://api.example.com',
141
options: {
142
headers: {
143
'Content-Type': 'application/json',
144
},
145
},
146
fetchOptions: {
147
beforeFetch({ options }) {
148
options.headers = {
149
...options.headers,
150
Authorization: `Bearer ${getToken()}`,
151
};
152
return { options };
153
},
154
},
155
});
156
157
// Use the configured client
158
const { data } = useAPI('/users').json();
159
const { data: user } = useAPI('/users/123').json();
160
```
161
162
### WebSocket
163
164
#### useWebSocket
165
166
Reactive WebSocket client with auto-reconnection and buffer management.
167
168
```typescript { .api }
169
/**
170
* Reactive WebSocket client with auto-reconnection
171
* @param url - WebSocket URL (reactive)
172
* @param options - Configuration options
173
* @returns WebSocket state and utilities
174
*/
175
function useWebSocket<Data = any>(
176
url: MaybeRefOrGetter<string | URL | undefined>,
177
options?: UseWebSocketOptions
178
): UseWebSocketReturn<Data>;
179
180
interface UseWebSocketReturn<Data> {
181
data: Ref<Data | null>;
182
status: Ref<UseWebSocketStatus>;
183
close: WebSocket['close'];
184
open: () => void;
185
send: (data: string | ArrayBuffer | Blob, useBuffer?: boolean) => void;
186
ws: Ref<WebSocket | undefined>;
187
}
188
189
interface UseWebSocketOptions {
190
onConnected?: (ws: WebSocket) => void;
191
onDisconnected?: (ws: WebSocket, event: CloseEvent) => void;
192
onError?: (ws: WebSocket, event: Event) => void;
193
onMessage?: (ws: WebSocket, event: MessageEvent) => void;
194
immediate?: boolean;
195
autoClose?: boolean;
196
autoReconnect?: boolean | UseWebSocketAutoReconnectOptions;
197
protocols?: string[];
198
heartbeat?: boolean | UseWebSocketHeartbeatOptions;
199
}
200
201
interface UseWebSocketAutoReconnectOptions {
202
retries?: number;
203
delay?: number;
204
onFailed?: () => void;
205
}
206
207
interface UseWebSocketHeartbeatOptions {
208
message?: string | (() => string);
209
interval?: number;
210
pongTimeout?: number;
211
}
212
213
type UseWebSocketStatus = 'CONNECTING' | 'CONNECTED' | 'DISCONNECTED';
214
```
215
216
**Usage Examples:**
217
218
```typescript
219
import { useWebSocket } from "@vueuse/core";
220
221
// Basic WebSocket connection
222
const { status, data, send, open, close } = useWebSocket('ws://localhost:8080');
223
224
// Send message
225
send('Hello Server!');
226
227
// With JSON serialization
228
const { data, send } = useWebSocket('ws://localhost:8080', {
229
onMessage: (ws, event) => {
230
console.log('Received:', JSON.parse(event.data));
231
}
232
});
233
234
send(JSON.stringify({ type: 'message', content: 'Hello' }));
235
236
// Auto-reconnection
237
const { status } = useWebSocket('ws://localhost:8080', {
238
autoReconnect: {
239
retries: 3,
240
delay: 1000,
241
onFailed() {
242
console.log('Failed to reconnect WebSocket after 3 attempts');
243
}
244
}
245
});
246
247
// Heartbeat
248
const { status } = useWebSocket('ws://localhost:8080', {
249
heartbeat: {
250
message: 'ping',
251
interval: 30000, // 30 seconds
252
pongTimeout: 5000 // 5 seconds
253
}
254
});
255
```
256
257
### Browser Communication
258
259
#### useBroadcastChannel
260
261
Reactive BroadcastChannel API for inter-tab communication.
262
263
```typescript { .api }
264
/**
265
* Reactive BroadcastChannel API for inter-tab communication
266
* @param name - Channel name
267
* @param options - Configuration options
268
* @returns BroadcastChannel utilities
269
*/
270
function useBroadcastChannel<D, P>(
271
name: string,
272
options?: UseBroadcastChannelOptions<D, P>
273
): UseBroadcastChannelReturn<D, P>;
274
275
interface UseBroadcastChannelReturn<D, P> {
276
isSupported: Ref<boolean>;
277
channel: Ref<BroadcastChannel | undefined>;
278
data: Ref<D>;
279
post: (data: P) => void;
280
close: () => void;
281
error: Ref<Event | null>;
282
isClosed: Ref<boolean>;
283
}
284
285
interface UseBroadcastChannelOptions<D, P> {
286
immediate?: boolean;
287
}
288
```
289
290
#### useUrlSearchParams
291
292
Reactive URLSearchParams management.
293
294
```typescript { .api }
295
/**
296
* Reactive URLSearchParams management
297
* @param mode - Update mode for URL changes
298
* @param options - Configuration options
299
* @returns Reactive search params utilities
300
*/
301
function useUrlSearchParams<T extends Record<string, any> = Record<string, string>>(
302
mode?: 'history' | 'hash' | 'hash-params',
303
options?: UseUrlSearchParamsOptions
304
): T;
305
306
interface UseUrlSearchParamsOptions {
307
removeNullishValues?: boolean;
308
removeFalsyValues?: boolean;
309
write?: boolean;
310
window?: Window;
311
}
312
```
313
314
**Usage Examples:**
315
316
```typescript
317
import { useUrlSearchParams } from "@vueuse/core";
318
319
// Basic usage
320
const params = useUrlSearchParams('history');
321
322
// Get/set search params
323
console.log(params.q); // Get 'q' parameter
324
params.q = 'vue'; // Set 'q' parameter
325
326
// Reactive to URL changes
327
watchEffect(() => {
328
if (params.page) {
329
loadPage(params.page);
330
}
331
});
332
333
// Typed parameters
334
const params = useUrlSearchParams<{
335
page?: string;
336
limit?: string;
337
q?: string;
338
}>('history');
339
```
340
341
### Server-Sent Events
342
343
#### useEventSource
344
345
Reactive EventSource (Server-Sent Events) client.
346
347
```typescript { .api }
348
/**
349
* Reactive EventSource (Server-Sent Events) client
350
* @param url - EventSource URL (reactive)
351
* @param events - Event names to listen for
352
* @param options - Configuration options
353
* @returns EventSource state and utilities
354
*/
355
function useEventSource(
356
url: MaybeRef<string | URL>,
357
events?: Array<string>,
358
options?: UseEventSourceOptions
359
): UseEventSourceReturn;
360
361
interface UseEventSourceReturn {
362
eventSource: Ref<EventSource | null>;
363
event: Ref<string | null>;
364
data: Ref<string | null>;
365
status: Ref<UseEventSourceStatus>;
366
error: Ref<Event | null>;
367
close: () => void;
368
}
369
370
interface UseEventSourceOptions extends ConfigurableWindow {
371
immediate?: boolean;
372
autoReconnect?: boolean | UseEventSourceAutoReconnectOptions;
373
withCredentials?: boolean;
374
}
375
376
type UseEventSourceStatus = 'CONNECTING' | 'CONNECTED' | 'DISCONNECTED';
377
```
378
379
### Web Workers
380
381
#### useWebWorker
382
383
Reactive Web Worker management.
384
385
```typescript { .api }
386
/**
387
* Reactive Web Worker management
388
* @param url - Worker script URL
389
* @param options - Configuration options
390
* @returns Web Worker utilities
391
*/
392
function useWebWorker<T = any>(
393
url: MaybeRefOrGetter<string>,
394
options?: UseWebWorkerOptions
395
): UseWebWorkerReturn<T>;
396
397
interface UseWebWorkerReturn<T> {
398
data: Ref<T>;
399
worker: Ref<Worker | undefined>;
400
post: typeof Worker.prototype.postMessage;
401
terminate: () => void;
402
}
403
```
404
405
#### useWebWorkerFn
406
407
Run function in Web Worker with automatic serialization.
408
409
```typescript { .api }
410
/**
411
* Run function in Web Worker with automatic serialization
412
* @param fn - Function to run in worker
413
* @param options - Configuration options
414
* @returns Worker function utilities
415
*/
416
function useWebWorkerFn<T extends (...fnArgs: any[]) => any>(
417
fn: T,
418
options?: UseWebWorkerFnOptions
419
): UseWebWorkerFnReturn<T>;
420
421
interface UseWebWorkerFnReturn<T> {
422
workerFn: (...fnArgs: Parameters<T>) => Promise<ReturnType<T>>;
423
workerStatus: Ref<UseWebWorkerStatus>;
424
workerTerminate: (timeout?: number) => void;
425
}
426
427
type UseWebWorkerStatus = 'PENDING' | 'SUCCESS' | 'RUNNING' | 'ERROR' | 'TIMEOUT_EXPIRED';
428
```