Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Apply VueUse composables in Vue 3/Nuxt projects to replace custom implementations with battle-tested utilities.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/useWebSocket.md
1---2category: Network3---45# useWebSocket67Reactive [WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/WebSocket) client.89## Usage1011```ts12import { useWebSocket } from '@vueuse/core'1314const { status, data, send, open, close, ws } = useWebSocket('ws://websocketurl')15```1617### Return Values1819| Property | Type | Description |20| -------- | ----------------------------------------- | ------------------------------------ |21| `data` | `Ref<any>` | Latest received data |22| `status` | `Ref<'OPEN' \| 'CONNECTING' \| 'CLOSED'>` | Connection status |23| `ws` | `Ref<WebSocket>` | WebSocket instance |24| `send` | `(data, useBuffer?) => boolean` | Send data (buffers if not connected) |25| `open` | `() => void` | Open/reconnect the connection |26| `close` | `(code?, reason?) => void` | Close the connection |2728### Callbacks2930```ts31const { data } = useWebSocket('ws://websocketurl', {32onConnected(ws) {33console.log('Connected!')34},35onDisconnected(ws, event) {36console.log('Disconnected!', event.code)37},38onError(ws, event) {39console.error('Error:', event)40},41onMessage(ws, event) {42console.log('Message:', event.data)43},44})45```4647See the [Type Declarations](#type-declarations) for more options.4849### immediate5051Enable by default.5253Establish the connection immediately when the composable is called.5455### autoConnect5657Enable by default.5859If a URL is provided as a ref, when the URL changes, it will automatically reconnect to the new URL.6061### autoClose6263Enable by default.6465This will call `close()` automatically when the `beforeunload` event is triggered or the associated effect scope is stopped.6667### autoReconnect6869Reconnect on errors automatically (disabled by default).7071```ts72import { useWebSocket } from '@vueuse/core'73// ---cut---74const { status, data, close } = useWebSocket('ws://websocketurl', {75autoReconnect: true,76})77```7879Or with more controls over its behavior:8081```ts82import { useWebSocket } from '@vueuse/core'83// ---cut---84const { status, data, close } = useWebSocket('ws://websocketurl', {85autoReconnect: {86retries: 3,87delay: 1000,88onFailed() {89alert('Failed to connect WebSocket after 3 retries')90},91},92})93```9495You can also pass a function to `delay` to calculate the delay based on the number of retries. This is useful for implementing exponential backoff:9697```ts98import { useWebSocket } from '@vueuse/core'99// ---cut---100const { status, data, close } = useWebSocket('ws://websocketurl', {101autoReconnect: {102retries: 5,103// Exponential backoff: 1s, 2s, 4s, 8s, 16s104delay: retries => Math.min(1000 * 2 ** (retries - 1), 30000),105},106})107```108109```ts110import { useWebSocket } from '@vueuse/core'111// ---cut---112const { status, data, close } = useWebSocket('ws://websocketurl', {113autoReconnect: {114retries: 5,115// Linear backoff: 1s, 2s, 3s, 4s, 5s116delay: retries => retries * 1000,117},118})119```120121Explicitly calling `close()` won't trigger the auto reconnection.122123### heartbeat124125It's common practice to send a small message (heartbeat) for every given time passed to keep the connection active. In this function we provide a convenient helper to do it:126127```ts128import { useWebSocket } from '@vueuse/core'129// ---cut---130const { status, data, close } = useWebSocket('ws://websocketurl', {131heartbeat: true,132})133```134135Or with more controls:136137```ts138import { useWebSocket } from '@vueuse/core'139// ---cut---140const { status, data, close } = useWebSocket('ws://websocketurl', {141heartbeat: {142message: 'ping',143scheduler: cb => useIntervalFn(cb, 2000),144pongTimeout: 1000,145},146})147```148149### Sub-protocols150151List of one or more subprotocols to use, in this case SOAP and WAMP.152153```ts154import { useWebSocket } from '@vueuse/core'155// ---cut---156const { status, data, send, open, close } = useWebSocket('ws://websocketurl', {157protocols: ['soap'], // ['soap', 'wamp']158})159```160161## Type Declarations162163```ts164export type WebSocketStatus = "OPEN" | "CONNECTING" | "CLOSED"165export type WebSocketHeartbeatMessage = string | ArrayBuffer | Blob166export interface UseWebSocketOptions {167onConnected?: (ws: WebSocket) => void168onDisconnected?: (ws: WebSocket, event: CloseEvent) => void169onError?: (ws: WebSocket, event: Event) => void170onMessage?: (ws: WebSocket, event: MessageEvent) => void171/**172* Send heartbeat for every x milliseconds passed173*174* @default false175*/176heartbeat?:177| boolean178| (ConfigurableScheduler & {179/**180* Message for the heartbeat181*182* @default 'ping'183*/184message?: MaybeRefOrGetter<WebSocketHeartbeatMessage>185/**186* Response message for the heartbeat, if undefined the message will be used187*/188responseMessage?: MaybeRefOrGetter<WebSocketHeartbeatMessage>189/**190* Interval, in milliseconds191*192* @deprecated Please use `scheduler` option instead193* @default 1000194*/195interval?: number196/**197* Heartbeat response timeout, in milliseconds198*199* @default 1000200*/201pongTimeout?: number202})203/**204* Enabled auto reconnect205*206* @default false207*/208autoReconnect?:209| boolean210| {211/**212* Maximum retry times.213*214* Or you can pass a predicate function (which returns true if you want to retry).215*216* @default -1217*/218retries?: number | ((retried: number) => boolean)219/**220* Delay for reconnect, in milliseconds221*222* Or you can pass a function to calculate the delay based on the number of retries.223*224* @default 1000225*/226delay?: number | ((retries: number) => number)227/**228* On maximum retry times reached.229*/230onFailed?: Fn231}232/**233* Immediately open the connection when calling this composable234*235* @default true236*/237immediate?: boolean238/**239* Automatically connect to the websocket when URL changes240*241* @default true242*/243autoConnect?: boolean244/**245* Automatically close a connection246*247* @default true248*/249autoClose?: boolean250/**251* List of one or more sub-protocol strings252*253* @default []254*/255protocols?: string[]256}257export interface UseWebSocketReturn<T> {258/**259* Reference to the latest data received via the websocket,260* can be watched to respond to incoming messages261*/262data: Ref<T | null>263/**264* The current websocket status, can be only one of:265* 'OPEN', 'CONNECTING', 'CLOSED'266*/267status: ShallowRef<WebSocketStatus>268/**269* Closes the websocket connection gracefully.270*/271close: WebSocket["close"]272/**273* Reopen the websocket connection.274* If there the current one is active, will close it before opening a new one.275*/276open: Fn277/**278* Sends data through the websocket connection.279*280* @param data281* @param useBuffer when the socket is not yet open, store the data into the buffer and sent them one connected. Default to true.282*/283send: (data: string | ArrayBuffer | Blob, useBuffer?: boolean) => boolean284/**285* Reference to the WebSocket instance.286*/287ws: Ref<WebSocket | undefined>288}289/**290* Reactive WebSocket client.291*292* @see https://vueuse.org/useWebSocket293* @param url294*/295export declare function useWebSocket<Data = any>(296url: MaybeRefOrGetter<string | URL | undefined>,297options?: UseWebSocketOptions,298): UseWebSocketReturn<Data>299```300