Laravel Echo is a JavaScript library that makes it painless to subscribe to channels and listen for events broadcast by Laravel. You may install Echo via the NPM package manager.
npm install --save-dev laravel-echo pusher-js
npm i @laravel/echo-react
Create a provider for echo
// app/echo-provider.tsx
"use client";
import {configureEcho} from "@laravel/echo-react";
export function EchoProvider({ children }: { children: React.ReactNode }) {
configureEcho({
broadcaster: "reverb",
key: process.env.NEXT_PUBLIC_REVERB_APP_KEY,
authEndpoint: process.env.NEXT_PUBLIC_API_URL + "/v1/broadcasting/auth",
auth: {
headers: {
Authorization: `Bearer <jwtToken>`, // Replace <jwtToken> with your actual JWT token
Accept: "application/json",
},
},
wsHost: process.env.NEXT_PUBLIC_REVERB_HOST,
wsPort: Number(process.env.NEXT_PUBLIC_REVERB_PORT),
wssPort: Number(process.env.NEXT_PUBLIC_REVERB_PORT),
forceTLS:
(process.env.NEXT_PUBLIC_REVERB_SCHEME ?? "https") === "https",
enabledTransports: ["ws", "wss"],
});
return <>{children}</>;
}
Make sure your .env.local file has all the env variable.
Then wrap your app with it:
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
<EchoProvider>{children}</EchoProvider>
</body>
</html>
);
}
Use useEcho, useEchoPublic, etc. in components.
Once configured, you can use the hooks in client components like this:
"use client";
import {useEcho} from "@laravel/echo-react";
type UserEvent = {
id: number;
message: string;
};
export default function UserNotification() {
useEcho<{message: UserEvent}>(
`users.10`,
["Notify", "NewMessage"],
(e) => {
console.log("User event:", e.message);
}
);
return <p>Listening for user notifications...</p>;
}
Read more in echo-react docs: https://laravel.com/docs/12.x/broadcasting#client-events
Link to source code: https://github.com/samiecode/laravel-echo-react
Top comments (0)