Search code examples
javascripttypescriptnext.jspeerjs

How to use Peer.js in Next.js with TypeScript?


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'?


Solution

  • 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.