DEV Community

Samie Azubike
Samie Azubike

Posted on

1

How to setup echo-react on nextjs app

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
Enter fullscreen mode Exit fullscreen mode

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}</>;
}

Enter fullscreen mode Exit fullscreen mode

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

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>;
}

Enter fullscreen mode Exit fullscreen mode

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)

DevCycle image

Ship Faster, Stay Flexible.

DevCycle is the first feature flag platform with OpenFeature built-in to every open source SDK, designed to help developers ship faster while avoiding vendor-lock in.

Start shipping