2

Next.js runs on server side also, so Peer.js raise error when using Next.js. Here one says: https://stackoverflow.com/a/66292100/239219

this is probably because peer js is performing some side effect during import.

He propose this:

useEffect(() => {
  import('peerjs').then(({ default: Peer }) => {
    // Do your stuff here
  });
}, [])

But I need DataConnection as using Typescript, and also asign it to a useState. would you show an example how?

This is what I put togeter, but TypesScript raise errors:

    useEffect(() => {
        import('peerjs').then(({ default: Peer, DataConnection }) => {
            const peer = new Peer(localStorage.token)

            peer.on('connection', (conn: DataConnection) => {
                console.log('Connected to peer:', conn)

                conn.on('data', (data) => {
                    console.log('Received data:', data)
                })
            })

            return () => {
                peer.destroy()
            }
        })
    }, [])

like: 'DataConnection' refers to a value, but is being used as a type here. Did you mean 'typeof DataConnection'?

János
  • 32,867
  • 38
  • 193
  • 353

2 Answers2

2

You can use a type-only import (introduced in version 3.8) at the top of the file:

import type { DataConnection } from "peerjs";

This import will be erased in the output, so rest assured that this will not import it "early".


Or if that doesn't fancy you, you can also "inline" the import:

peer.on('connection', (conn: import("peerjs").DataConnection) => {

Looks weird, but when import(...) is used as a type, it resolves to the namespace that importing the module would give you.

TTang
  • 36
  • 2
0

You can import the component that is using peerjs (and its other imports) on the client.

import dynamic from "next/dynamic";

let WebRTC = dynamic(() => import("./main"), { ssr: false, loading: () => 
    <h2>loading..</h2> })

export default function Page() {

    return (
       <WebRTC />
    )

}

By setting ssr: false you tell next to load it only on the client side. Check for more info https://nextjs.org/docs/app/building-your-application/optimizing/lazy-loading#nextdynamic