1

So I'm learning NextJs and trying to build a audio chat app and I'm stuck when I try to import PeerJs

Its throwing an window is not defined error.

import Peer from 'peerjs';

export default function Home() {

useEffect(() => {
  const myPeer = new Peer(undefined, {
    host: '/',
    port: '3001'
  })
}, [])
}
code.cycling
  • 1,246
  • 2
  • 15
  • 33

1 Answers1

8

This is because using nextjs, code is first evaluated in server side (render to HTML). At this stage, windowis not defined. This is probably because peer js is performing some side effect during import. To workaround this, you could use dynamic import:

useEffect(() => {
  import('peerjs').then(({ default: Peer }) => {
    // Do your stuff here
  });
}, [])
seanplwong
  • 1,051
  • 5
  • 14
  • How can I import `DataConnection` also, I have TypeScript. need here: `peer.on('connection', (conn: DataConnection) => {` I need replace this: `import Peer, { DataConnection } from 'peerjs'`. – János Jan 23 '23 at 20:56
  • looks like you just need the type, put this in the top: `import { type DataConnection } from 'peerjs';` You will import DataConnection as type only then and tsc will simply remove it when compiling. – seanplwong Jan 30 '23 at 02:46