I am building my first NextJs app for production, I’m a newbie so this is kind of an experiment. In my app I am using PeerJs
for real-time communication, however when I import PeerJs
the normal way I get below error,
This error occured because on the Server-Side Render the navigator is not present.
node_modulespeerjsdistbundler.mjs (108:0) @ new eval
⨯ ReferenceError: navigator is not defined
I also tried importing the library dynamically using below mentioned ways but then NextJs
treats the library as a JSX component.
import dynamic from 'next/dynamic';
const peerjs = dynamic(() => import('peerjs'), { ssr: false });
/
const { default: Peer } = await import('peerjs')
What am I doing wrong, if anyone knows please tell 🙂
2
Answers
I assume you are using the nextjs app router. In the app router, every component is a server component by default.
peerjs needs navigator to work. from your error, it is undefined. The navigator object is a property of the window object, so it is available on the client side only. so you need to use this on the client-side component using "use client" directive at the top of component.
To ensure that PeerJS is running only on the client, you can import it in the
useEffect
hook: