Encountering a problem when utilizing window.ethereum in Next Js paired with ether JS

Experiencing some difficulties while utilizing the window.ethereum in the latest version of NextJs. Everything was functioning smoothly with NextJs 12, but after upgrading to NextJs 13, this error started popping up. Are there any alternative solutions available for this issue?

Code Snippet:

 const provider = new ethers.providers.Web3Provider(window.ethereum);

 const signer = provider.getSigner();

 console.log(signer);

Answer №1

To utilize the functionality, you must first execute the command

npm i --save-dev @ethersproject/providers
.

import { ExternalProvider } from "@ethersproject/providers";

useEffect(() => {
    async function load() {
      try {
        const provider = new ethers.providers.Web3Provider(
          window.ethereum as unknown as ExternalProvider
        );
       // gather variables
       // then update state using useState
      }
      

verification of completion:

Answer №2

I encountered a similar issue when working with NextJS, but after some trial and error, I stumbled upon a solution that worked well for me.

const [ethereumProvider, setEthereumProvider] = useState({});

useEffect( async () => {
    if (typeof window.ethereum !== 'undefined' || (typeof window.web3 !== 'undefined')) {
        const provider = new ethers.providers.Web3Provider(window.ethereum);
        setEthereumProvider(provider);
        // additional logic using the ethereumProvider here
    }
}, []);

Check out this GitHub link for more information.

Answer №3

For those utilizing ethers version 6.0.0 or higher, I suggest referring to my solution provided in this link. It appears to be related to the updated version.

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

Patience is key when it comes to waiting for a function to finish before moving on to the next step

I'm delving into the world of node js and currently immersing myself in the concepts of promises and async/await. Here's a code snippet I've been experimenting with, but I can't quite figure out how to ensure that the code waits until t ...

Loader successfully resolving deep array references

My schema is structured as follows: type User{ id: String! name: String posts: [Post] } type Post { id: String! userId: String body: String } I'm utilizing Facebook's dataloader to batch the request. query { GetAllUser { id ...

Executing untrusted JavaScript code on a server using a secure sandbox environment

I am facing difficulties in creating a secure node sandbox that can execute untrusted code while allowing users to communicate with the program through api calls (input and output). My goal is to establish a browser console where users can run their own se ...

Update the observability status of one observable using a different observable

Upon running the following code, you'll notice that an xhr request is being sent to the console regardless of whether I am subscribed to the subject or not. I would prefer for these requests not to be made if I am not subscribed. // To start, install ...

Error-throwing constructor unit test

In my code, I have implemented a constructor that takes in a configuration object. Within this constructor, I perform validations on the object. If the validation fails, I aim to throw an error that clearly describes the issue to the user. Now, I am wonde ...

Extending Error object disrupts `instanceof` validation in TypeScript

Could someone clarify why the error instanceof CustomError part of the code below returns false? class CustomError extends Error {} const error = new CustomError(); console.log(error instanceof Error); // true console.log(error instanceof CustomError); ...

The getJSON API functions properly on a local machine but encounters issues when deployed on a

I have a vision to create a web application that can display the weather of any city based on user input. I've divided my project into three files - index.html for collecting user input, index2.html for retrieving and displaying the data, and a CSS fi ...

AngularJS - Controller routing to open link in new tab based on condition

Within my application, there are two distinct types of profiles available for organisations. When a user interacts with a profile name, the system must first determine if a premium profile exists for that organisation. If a premium profile is found, the us ...

Caution: The `id` property did not match. Server: "fc-dom-171" Client: "fc-dom-2" while utilizing FullCalendar in a Next.js environment

Issue Background In my current project, I am utilizing FullCalendar v5.11.0, NextJS v12.0.7, React v17.0.2, and Typescript v4.3.5. To set up a basic calendar based on the FullCalendar documentation, I created a component called Calendar. Inside this comp ...

The request to login at the specified API endpoint on localhost:3000 was not successful, resulting in a

As I continue to develop my programming skills, I have been working on configuring a database connected with nodejs in the same folder. However, when trying to make an ajax request to the database, I encountered an error indicating that the database may be ...

Retrieving Vue data from parent components in a nested getter/setter context

<template> <div id="app"> {{ foo.bar }} <button @click="meaning++">click</button> <!--not reactive--> <button @click="foo.bar++">click2</button> </div> </templ ...

Create custom AngularJS directives for validation and store them in a variable

Through the use of AngularJS, I've developed a directive called "integer" that invalidates a form if anything other than integers are entered. Because I'm generating the page dynamically by fetching data from the database, it would be helpful to ...

Tips for transferring input values from a JavaScript function to a separate PHP page for storage in a database

This code snippet allows dynamic rows to be added to a table when the add button is clicked. Now, the goal is to retrieve the values entered into the text boxes and submit them to the database. <div id="addinput"> <p> <button name=" ...

What are the steps to retrieve historical stock data for over one year using Yahoo Finance YQL query?

I am currently using a Tableau web connector to retrieve stock price data. Here is the source code: <html> <meta http-equiv="Cache-Control" content="no-store" /> <head> <title>Stock Quote Connector-Tutorial</title> <sc ...

Having trouble with a basic select tag and options not functioning properly in Chrome browser

I encountered an issue where I am unable to expand a simple select tag in Chrome. <select id="filterCategory" class=""> <option>1</option> <option>2</option> <option>3</option> <option>4</option ...

How can you store previously calculated values in a costly recursive function in a React application?

Consider a scenario where there is a recursive callback function like the one shown below: const weightedFactorial = useCallback(n => { if (n === 0) { return 1; } return weight * n * weightedFactorial(n - 1); }, [weight]); Is it possible to ...

Modify path and refresh display upon ajax call to node server

Recently, I made the decision to utilize a Node server as a proxy for making API calls to third-party public APIs from my front end. After successfully sending a request to my Node endpoint and then to the third-party API, I received the expected response. ...

How to use JavaScript regular expressions to extract the content following the second-to-last occurrence of a back

I currently have a regular expression that looks like this: /^.*[\\\/]/ At the moment, it removes every single backslash from a string. However, now I need to modify it in order to capture everything after the second to last backslash. Fo ...

Identify when a click occurs outside specific elements

I've been searching for solutions to address this issue, but so far nothing has worked. Here is the JavaScript code I am using: var specifiedElement = document.getElementById('a'); document.addEventListener('click', function(eve ...

Showing hidden errors in specific browsers via JavaScript

I was struggling to make the code work on certain browsers. The code you see in the resource URL below has been a collection of work-around codes to get it functioning, especially for Android browsers and Windows 8. It might be a bit sketchy as a result. ...