Broadcast your server-side events to your frontend via WebSockets. Supported drivers include Pusher, Ably, and a local log driver for debugging.
Setup your broadcaster credentials in config/app.ts.
1// src/config/app.ts2export const config = {3// ...4broadcasting: {5default: 'pusher',6connections: {7pusher: {8driver: 'pusher',9key: process.env.PUSHER_APP_KEY,10secret: process.env.PUSHER_APP_SECRET,11appId: process.env.PUSHER_APP_ID,12options: {13host: 'api.pusherapp.com',14encrypted: true,15}16},17ably: {18driver: 'ably',19key: process.env.ABLY_KEY,20},21log: {22driver: 'log', // Useful for debugging23}24}25}26};
Implement the Broadcasts interface on your event classes to make them broadcastable.
1import { Dispatchable, Broadcasts } from 'canxjs';23export class OrderUnpdated implements Dispatchable, Broadcasts {4constructor(public order: Order) {}56// The channel to broadcast on7broadcastOn() {8return ['orders.' + this.order.id];9}1011// The event name (optional, defaults to class name)12broadcastAs() {13return 'order.updated';14}1516// Data to send17broadcastWith() {18return {19status: this.order.status,20updated_at: new Date()21};22}23}2425// Dispatch26await new OrderUpdated(order).dispatch();
CanxJS events are compatible with Laravel Echo. You can use the standard Echo client to listen for events.
1import Echo from 'laravel-echo';2import Pusher from 'pusher-js';34window.Pusher = Pusher;56const echo = new Echo({7broadcaster: 'pusher',8key: 'your-pusher-key',9cluster: 'mt1',10forceTLS: true11});1213echo.channel('orders.1')14.listen('order.updated', (e) => {15console.log('Order Updated:', e.status);16});