ZLYNX

Blog

1 min read

Config NextJS with Laravel Echo + Pusher

Share:

Nextjs with laravel echo + pusher

Step 1: Install Laravel Echo And Pusher JS

1 npm install --save-dev laravel-echo pusher-js

Step 2: Create a new file in the root of your project called socket.ts and add the following code:

1import Pusher from 'pusher-js'; 2import Echo from 'laravel-echo'; 3 4declare global { 5 interface Window { 6 Pusher: typeof Pusher; 7 Echo: Echo; 8 } 9} 10 11export const pusher = new Pusher(process.env.NEXT_PUBLIC_PUSHER_KEY, { 12 cluster: process.env.NEXT_PUBLIC_PUSHER_CLUSTER, 13}); 14 15export const echo = () => { 16 if (typeof window === 'undefined') return; 17 18 window.Pusher = Pusher; 19 20 return new Echo({ 21 broadcaster: 'pusher', 22 key: process.env.NEXT_PUBLIC_PUSHER_KEY, 23 cluster: process.env.NEXT_PUBLIC_PUSHER_CLUSTER, 24 forceTLS: true, 25 }); 26};

Step 3: Test

1useEffect(() => { 2 const channel = pusher.subscribe(CHANEL_NAME); 3 channel.bind(CHANEL_EVENT, (data: any) => { 4 setNotifications([...notifications, data]); 5 console.log(data); 6 }); 7 return () => { 8 pusher.unsubscribe(CHANEL_NAME); 9 }; 10 // using echo 11 echo()! 12 .channel(CHANEL_NAME); 13 .listen('.' + CHANEL_EVENT, (data: any) => { 14 console.log(data); 15 }); 16 }, [router]);
Share: