FARDEEN's avatar

Cannot create Echo (laravel-echo) instance in react (Next.JS)

Since it is a next.js app, I do not have resources/js/bootstrap.js

I am trying to create an Echo instance but it throws an error:

Server Error
ReferenceError: Pusher is not defined
  13 | import Echo from "laravel-echo";
  14 | 
> 15 | const echo = new Echo({
     |           ^
  16 | broadcaster: "pusher",
  17 | key: process.env.PUSHER_APP_KEY,
  18 | wsHost: process.env.PUSHER_HOST,

My component

import Pusher from "pusher-js";
import Echo from "laravel-echo";

const echo = new Echo({
  broadcaster: "pusher",
  key: process.env.PUSHER_APP_KEY,
  wsHost: process.env.PUSHER_HOST,
  wsPort: process.env.PUSHER_PORT ?? 80,
  wssPort: process.env.PUSHER_PORT ?? 443,
  forceTLS: (process.env.PUSHER_SCHEME ?? "https") === "https",
  encrypted: true,
  enabledTransports: ["ws", "wss"],
});

If I paste code from resources/js/bootstrap.js

import Echo from 'laravel-echo';

import Pusher from 'pusher-js';
window.Pusher = Pusher;

window.Echo = new Echo({
    broadcaster: "pusher",
    key: process.env.PUSHER_APP_KEY,
    wsHost: process.env.PUSHER_HOST,
    wsPort: process.env.PUSHER_PORT ?? 80,
    wssPort: process.env.PUSHER_PORT ?? 443,
    forceTLS: (process.env.PUSHER_SCHEME ?? "https") === "https",
    encrypted: true,
    enabledTransports: ["ws", "wss"],
  });

I get the following error

Server Error
ReferenceError: window is not defined
  27 | 
  28 | import Pusher from 'pusher-js';
> 29 | window.Pusher = Pusher;
  30 | 
  31 | window.Echo = new Echo({
  32 | broadcaster: "pusher",
0 likes
1 reply
finleth's avatar

Kind of an old question but since I came across the same error today, I'll show how I was able to fix it.

When instantiating the Echo instance, you can pass the Pusher instance into it instead of setting it on the global window object which doesn't exist on NextJS.

To do this, just pass it in on the Pusher key - note the capitalization:

import Echo from 'laravel-echo';
import Pusher from 'pusher-js';

const echo = new Echo({
    broadcaster: 'pusher',
    Pusher: Pusher,
    // rest of your configs
});

Caused me some headache as I dug around the pusher-js source code so I hope it saves someone else some future headache.

2 likes

Please or to participate in this conversation.