Tips for implementing Peer.js in Next.js using TypeScript?

Next.js has the ability to run on the server side, which can result in Peer.js throwing errors when used with Next.js. One user on Stack Overflow explains this issue:

The error is likely due to peer js performing side effects during import.

The suggested solution is:

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

However, I am in need of using DataConnection with Typescript and storing it in a useState variable. Can you provide an example of how to do this?

This is what I have put together, but I am encountering errors with Typescript:

    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()
            }
        })
    }, [])

For example: 'DataConnection' is referenced as a value but is being used as a type in this context. Did you mean to use 'typeof DataConnection'?

Answer №1

To make use of a type-only import (which was introduced in version 3.8), you can add the following line at the beginning of your file:

import type { DataConnection } from "peerjs";

Don't worry, this import will not be included in the final output, ensuring it won't affect the order of imports.


If that option doesn't appeal to you, you can also "inline" the import like this:

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

It may look strange, but using import(...) as a type will resolve to the namespace that would result from importing the module.

Answer №2

If you want to incorporate the component that utilizes peerjs (along with its other dependencies) on the client side, you can import it as shown below:

import dynamic from "next/dynamic";

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

export default function Page() {

    return (
       <WebRTC />
    )

}

By specifying ssr: false, Next.js will ensure that the component is only loaded on the client's side. For more detailed information, please refer to https://nextjs.org/docs/app/building-your-application/optimizing/lazy-loading#nextdynamic

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How is it possible that this is not causing a syntax or compile-time error?

Oops! I made a mistake and typed : instead of = on line 2 of this code snippet. Why does Typescript allow this error? Isn't colon supposed to indicate a known Type for a property declaration? I'm pretty sure there's a reason encoded in the ...

How can I solve export issues from index.ts after publishing to NPM?

I have a package called this package which contains an index.ts file. The corresponding index.d.ts file that is located in the directory node_modules/@fireflysemantics/slice has the following content: export { EStore } from './EStore'; export { ...

Create a duplicate of the table and remove specific rows

Hi there, I have a query about duplicating a table. I am looking to extract specific results and display only those results. To illustrate, here is an example in HTML code: <table class="table table-striped" id="ProfileList2"> <tbody> ...

Having trouble extracting the ID from the URL using parameters

Just diving into the world of Express JS and MongoDB, so I appreciate your patience with me. Currently following a web development tutorial by Colt Steele. Take a look at my code: app.get("/:id",async(req,res)=> { const id= req.params[&apo ...

Combine items with similar structure, yet distinct characteristics

Currently working on a program that checks the frequency of certain occurrences in a document based on specified rules. Using regular expressions to process fields, I am able to count the instances of a particular field or perform a more detailed analysis ...

Is there a way to make elasticX() and elasticY() only affect the upper bound in dc.js?

One question I have regarding my bubbleChart in dc.js is related to the x-axis. I want the count on the x-axis to always start at 0, but have an upper bound that adjusts based on the range I am looking at. Currently, when I use .elasticX(true), both the up ...

jquery survey quiz

Currently, I am attempting to develop a jQuery questionnaire, but my limited knowledge in the area is proving to be quite inadequate. So far, here is what I have: Upon clicking on "Questions," a pop-up window will appear with two questions. My goal is t ...

Is it a bad idea to set directive scope to false, considering the limitations on broadcasting in an isolated scope?

There is a unique situation I am trying to tackle where I need to use $broadcast within a directive's linking function that has an isolated scope. Unfortunately, broadcasting from inside an isolated scope becomes challenging as the directive scope doe ...

Exploring other options for authentication in Next.js beyond next_auth and similar frameworks

I'm working on creating a dynamic authentication system in Next.js that can connect to a Spring (Java) API backend. The API's endpoints are functioning properly when tested with Postman, and it also provides its own JWT. My goal is to enable regi ...

Arrange the object's key-value pairs in ng-repeat by their values

I'm completely new to AngularJS and I am working with an API that returns key-value pairs related to different sports. $scope.sports = { 1: "Soccer", 2: "Tennis", 3: "Basketball" ... }; My challenge is sorting these items by sport name: <ul> ...

The challenge in displaying data from the backend using ajax in Vue.js 2.0 is hindering its visibility on the view

Currently, I am utilizing vue.js version 2.0, and the demo provided below is fully functional. <div class="container" id="app"> <ol> <li v-for="(todo,index) in todos"> {{ index }} {{ todo.text }} </li&g ...

Encountering an error with Mongoose's .pre('save') method in Typescript

Every time I attempt to use the hash password .pre hook, it refuses to save. userSchema.pre("save", async function (next) { let user = this as UserDocument; if (!user.isModified("password")) return next(); const salt = await bcry ...

How can we declare and showcase a generic object with an unspecified number and names of keys in React using TypeScript?

I am facing a challenge with objects that have a 'comments' field. While all the other fields in these different objects have the same types, the 'comment' field varies. I do not know the exact number or names of the keys that will be p ...

Learn the ins and outs of utilizing *ngIf in index.html within Angular 8

Can anyone explain how I can implement the *ngIf condition in index.html for Angular2+? I need to dynamically load tags based on a condition using the *ngIf directive, and I'm trying to retrieve the value from local storage. Below is my code snippet b ...

Confusion about the unwinding of the call stack in the Graph Depth-

Issue with function: hasPathDFSBroken Fix implemented in: hasPathDFS The updated version includes a forced parameter to address the issue, which I would prefer to avoid. I'm trying to comprehend why in the broken version, when the call stack unwinds ...

How to effectively utilize TypeScript in a team environment using both Atom and VSCode?

Our team utilizes TypeScript with both Atom and VSCode as our editors, but we are facing challenges with the tsconfig.json file. VSCode is not recognizing the typings, causing the namespace for 'ng' (for Angular 1.x) to be unknown in VSCode. Wh ...

Javascript Pretty Print Format is producing inaccurate output

function displayData(info) { document.body.appendChild(document.createElement('pre')).innerHTML = info; } function searchInGitHub(str) { const http = new XMLHttpRequest(); http.open("GET", "https://api.github.com/search/reposi ...

How can you convert an epoch datetime value from a textbox into a human-readable 24-hour date format

I have an initial textbox that displays an epoch datetime stamp. Since this format is not easily readable by humans, I made it hidden and readonly. Now, I want to take the epoch value from the first textbox and convert it into a 24-hour human-readable da ...

Set the subscription's value to the class property without changing its original state

Lately, I have been using the following method to set the value of a subscription to a property in my classes: export class ExampleComponent implements OnInit { exampleId: string; constructor(public route: ActivatedRoute) { this.route.params.subs ...

Error message: CORS policy prevents third-party scripts from running in Next.js

I am encountering an issue with implementing a script handling tool in my Next.js project. I followed the documentation on nextjs.org and utilized the worker (experimental) parameter to enhance the page's performance. However, I am facing a CORS polic ...