Laravel Echo
repository·2.x·Indexed 23 days ago
https://github.com/laravel/echoA JavaScript library that simplifies subscribing to channels and listening for real-time events broadcast by Laravel via WebSockets, with support for Pusher and Socket.IO. It includes specialized helpers and hooks for React, Vue, and Svelte to manage connection status and subscriptions to public, private, presence, and model channels.
What's inside Laravel Echo
- Laravel Echo is a JavaScript library designed to make it easy to subscribe to channels and listen for events broadcast by Laravel. It facilitates real-time, live-updating user interfaces by handling WebSocket messages sent from the server, providing a more efficient alternative to traditional polling.
Configure Laravel Echo React Helpers with `configureEcho`
2.xBefore using any Echo hooks in your components, you must call
configureEchoonce in your application to initialize the Echo instance. You only need to provide thebroadcastertype (e.g.,"reverb"), and the package will automatically populate default configuration values using environment variables (likeVITE_REVERB_APP_KEY,VITE_REVERB_HOST, etc.). You can override these defaults by passing your own configuration object.import { configureEcho } from "@laravel/echo-react"; configureEcho({ broadcaster: "reverb", });Configure Laravel Echo in Svelte with `configureEcho`
2.xBefore using Echo hooks in your components, you must call
configureEchoonce in your application to initialize the Echo instance. You only need to provide thebroadcastertype (e.g.,'reverb'). The package will automatically populate default configuration values based on your broadcaster, such askey,wsHost,wsPort, andforceTLSusing standard Vite environment variables (e.g.,import.meta.env.VITE_REVERB_APP_KEY). You can override any of these defaults by passing them into the configuration object.import { configureEcho } from "@laravel/echo-svelte"; configureEcho({ broadcaster: "reverb", });Configure Laravel Echo Vue Helpers with `configureEcho`
2.xBefore using any Echo hooks in your Vue components, you must call
configureEchoto initialize the Echo instance. You only need to provide the required configuration data (like thebroadcaster). The package will automatically fill in default values for other keys based on your broadcaster (e.g., usingVITE_REVERB_*environment variables if usingreverb). You can override any default values by providing them in the configuration object.import { configureEcho } from "@laravel/echo-vue"; configureEcho({ broadcaster: "reverb", });Install Laravel Echo via NPM
2.xYou can install the core Laravel Echo library using the NPM package manager.Understand how CSRF and Bearer tokens are applied
2.xThe
Connectorbase class automatically manages authentication headers based on the provided options and the environment:CSRF Token: The connector attempts to find a CSRF token in the following order:
window.Laravel.csrfToken(if available in the browser).- The
csrfTokenproperty provided in the options. - A
<meta name="csrf-token">tag in the document. If found, it is added toauth.headers['X-CSRF-TOKEN']anduserAuthentication.headers['X-CSRF-TOKEN'].
Bearer Token: If
bearerTokenis provided in the options, it is added toauth.headers['Authorization']anduserAuthentication.headers['Authorization']asBearer {token}.
Extend event payload types for Laravel Echo React
2.xTo get full type safety and autocomplete when listening to broadcast events, you must define your event payloads in a global
Eventsinterface. This allows the@laravel/echo-reactpackage to infer the correct payload type for a given event name usingInferEventPayload<TEvent>.You can achieve this in two ways:
1. Global Interface Extension (Simplest)
Create a
.d.tsfile (e.g.,types/echo.d.ts) in your project and extend theEventsinterface directly.2. Module Augmentation
Use module augmentation to declare the interface within the
@laravel/echo-reactmodule scope.// Approach 1: In user's types/echo.d.ts file interface Events { OrganizationUpdated: { id: number; name: string; updated_at: string; }; UserCreated: { id: number; email: string; name: string; }; } // Approach 2: Module augmentation declare module '@laravel/echo-react' { interface Events { OrganizationUpdated: { id: number; name: string; updated_at: string; }; } }Define custom event payload types for @laravel/echo-svelte
2.xTo get full type safety and autocomplete for your broadcast events, you should extend the global
Eventsinterface in a declaration file (e.g.,types/echo.d.ts). This allows the library to infer the correct payload types when you listen to specific events.You can use two approaches:
- Global Interface Extension (Simplest): Define the
Eventsinterface directly in a.d.tsfile. - Module Augmentation: Use
declare module '@laravel/echo-svelte'to augment the interface.
Once defined, the
EventNametype will provide autocomplete for your event keys, andInferEventPayload<TEvent>will resolve to the specific shape of your data.// In user's types/echo.d.ts file: interface Events { OrganizationUpdated: { id: number; name: string; updated_at: string; }; UserCreated: { id: number; email: string; name: string; }; } // OR via Module Augmentation: declare module '@laravel/echo-svelte' { interface Events { OrganizationUpdated: { id: number; name: string; updated_at: string; }; } }- Global Interface Extension (Simplest): Define the
Initialize the Echo client
2.xThe
Echoclass is the primary entry point for interacting with Laravel broadcasting. To create an instance, pass an options object that includes abroadcasterkey. Supported broadcasters includereverb,pusher,ably,socket.io, andnull.By default, Echo registers HTTP interceptors (for Axios, Vue, jQuery, and Turbo) to automatically include the
X-Socket-Idheader in outgoing requests, which is required for authenticating private and presence channels. You can disable this by settingwithoutInterceptors: truein your options.Configure Laravel Echo in Svelte
2.xUse
configureEchoto initialize the Echo instance with your broadcasting configuration. This function applies sensible defaults based on yourbroadcastertype (e.g.,reverb,pusher,socket.io,ably, ornull) using environment variables.If an Echo instance already exists, calling
configureEchowill reset it by callingleaveAllChannels()and clearing the existing instance.Defaults are pulled from the following environment variables:
- Reverb:
VITE_REVERB_APP_KEY,VITE_REVERB_HOST,VITE_REVERB_PORT,VITE_REVERB_SCHEME - Pusher:
VITE_PUSHER_APP_KEY,VITE_PUSHER_APP_CLUSTER,VITE_PUSHER_HOST,VITE_PUSHER_PORT - Socket.io:
VITE_SOCKET_IO_HOST - Ably:
VITE_ABLY_PUBLIC_KEY
- Reverb:
Define custom event payload types for Laravel Echo Vue
2.xTo get full type safety and autocomplete when listening to broadcasted events in
@laravel/echo-vue, you must define your event payloads in a globalEventsinterface. You can do this by creating a.d.tsfile in your project or by using module augmentation.Option 1: Global Interface (Simplest)
Create a file (e.g.,
types/echo.d.ts) and extend theEventsinterface:interface Events { OrganizationUpdated: { id: number; name: string; updated_at: string; }; UserCreated: { id: number; email: string; name: string; }; }Option 2: Module Augmentation
Alternatively, use module augmentation to declare the interface:
declare module '@laravel/echo-vue' { interface Events { OrganizationUpdated: { id: number; name: string; updated_at: string; }; } }// In user's types/echo.d.ts file (simplest approach): interface Events { OrganizationUpdated: { id: number; name: string; updated_at: string; }; UserCreated: { id: number; email: string; name: string; }; } // Alternative: Module augmentation declare module '@laravel/echo-vue' { interface Events { OrganizationUpdated: { id: number; name: string; updated_at: string; }; } }Configure Echo in Vue
2.xBefore using Echo in your Vue application, you must call
configureEcho()to initialize the instance with your broadcasting credentials. This function uses sensible defaults based on environment variables (prefixed withVITE_) for common broadcasters likereverb,pusher,socket.io,ably, ornull.When you call
configureEcho(config), it merges your providedconfigwith the defaults for the specifiedbroadcaster. If an Echo instance already exists, callingconfigureEchowill reset it.