Quiet Coder
Quiet Coder

Reputation: 159

Confusing library imported by using next/dynamic with component

In my app I'm 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_modules\peerjs\dist\bundler.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 :)

Upvotes: 1

Views: 172

Answers (2)

Invulner
Invulner

Reputation: 2043

To ensure that PeerJS is running only on the client, you can import it in the useEffect hook:

useEffect(() => {
    import("peerjs").then(({ default: Peer }) => {
        const peer = new Peer();
        ...
    });
}, []);

Upvotes: 1

Naga Sai
Naga Sai

Reputation: 36

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.

Upvotes: 1

Related Questions