Laravel Echo

repository·2.x·Indexed 23 days ago

https://github.com/laravel/echo

A 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.

Tokens
13.7K
Snippets
19
Records
77
Agent score
79%

What's inside Laravel Echo

  1. Introduction to Laravel Echo

    2.x
    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.
  2. Configure Laravel Echo React Helpers with `configureEcho`

    2.x

    Before using any Echo hooks in your components, you must call configureEcho once in your application to initialize the Echo instance. You only need to provide the broadcaster type (e.g., "reverb"), and the package will automatically populate default configuration values using environment variables (like VITE_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",
    });
  3. Configure Laravel Echo in Svelte with `configureEcho`

    2.x

    Before using Echo hooks in your components, you must call configureEcho once in your application to initialize the Echo instance. You only need to provide the broadcaster type (e.g., 'reverb'). The package will automatically populate default configuration values based on your broadcaster, such as key, wsHost, wsPort, and forceTLS using 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",
    });
  4. Configure Laravel Echo Vue Helpers with `configureEcho`

    2.x

    Before using any Echo hooks in your Vue components, you must call configureEcho to initialize the Echo instance. You only need to provide the required configuration data (like the broadcaster). The package will automatically fill in default values for other keys based on your broadcaster (e.g., using VITE_REVERB_* environment variables if using reverb). You can override any default values by providing them in the configuration object.

    import { configureEcho } from "@laravel/echo-vue";
    
    configureEcho({
        broadcaster: "reverb",
    });
  5. Understand how CSRF and Bearer tokens are applied

    2.x

    The Connector base class automatically manages authentication headers based on the provided options and the environment:

    1. CSRF Token: The connector attempts to find a CSRF token in the following order:

      • window.Laravel.csrfToken (if available in the browser).
      • The csrfToken property provided in the options.
      • A <meta name="csrf-token"> tag in the document. If found, it is added to auth.headers['X-CSRF-TOKEN'] and userAuthentication.headers['X-CSRF-TOKEN'].
    2. Bearer Token: If bearerToken is provided in the options, it is added to auth.headers['Authorization'] and userAuthentication.headers['Authorization'] as Bearer {token}.

  6. Extend event payload types for Laravel Echo React

    2.x

    To get full type safety and autocomplete when listening to broadcast events, you must define your event payloads in a global Events interface. This allows the @laravel/echo-react package to infer the correct payload type for a given event name using InferEventPayload<TEvent>.

    You can achieve this in two ways:

    1. Global Interface Extension (Simplest)

    Create a .d.ts file (e.g., types/echo.d.ts) in your project and extend the Events interface directly.

    2. Module Augmentation

    Use module augmentation to declare the interface within the @laravel/echo-react module 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;
        };
      }
    }
  7. Define custom event payload types for @laravel/echo-svelte

    2.x

    To get full type safety and autocomplete for your broadcast events, you should extend the global Events interface 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:

    1. Global Interface Extension (Simplest): Define the Events interface directly in a .d.ts file.
    2. Module Augmentation: Use declare module '@laravel/echo-svelte' to augment the interface.

    Once defined, the EventName type will provide autocomplete for your event keys, and InferEventPayload<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;
        };
      }
    }
  8. Initialize the Echo client

    2.x

    The Echo class is the primary entry point for interacting with Laravel broadcasting. To create an instance, pass an options object that includes a broadcaster key. Supported broadcasters include reverb, pusher, ably, socket.io, and null.

    By default, Echo registers HTTP interceptors (for Axios, Vue, jQuery, and Turbo) to automatically include the X-Socket-Id header in outgoing requests, which is required for authenticating private and presence channels. You can disable this by setting withoutInterceptors: true in your options.

  9. Configure Laravel Echo in Svelte

    2.x

    Use configureEcho to initialize the Echo instance with your broadcasting configuration. This function applies sensible defaults based on your broadcaster type (e.g., reverb, pusher, socket.io, ably, or null) using environment variables.

    If an Echo instance already exists, calling configureEcho will reset it by calling leaveAllChannels() 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
  10. Define custom event payload types for Laravel Echo Vue

    2.x

    To get full type safety and autocomplete when listening to broadcasted events in @laravel/echo-vue, you must define your event payloads in a global Events interface. You can do this by creating a .d.ts file in your project or by using module augmentation.

    Option 1: Global Interface (Simplest)

    Create a file (e.g., types/echo.d.ts) and extend the Events interface:

    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;
        };
      }
    }
  11. Configure Echo in Vue

    2.x

    Before 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 with VITE_) for common broadcasters like reverb, pusher, socket.io, ably, or null.

    When you call configureEcho(config), it merges your provided config with the defaults for the specified broadcaster. If an Echo instance already exists, calling configureEcho will reset it.