Etherjs "window" object not accessible in Next.js

Viewed 1193

I have a relatively basic project using solidity and react working as a single page dApp using Create React App. However I am trying to move this now to Nextjs and have hit a hurdle which I assume is something to do with the server side stuff Nextjs does. I have removed all the redundant code and just provide enough to generate the error:

import { ethers, Contract } from 'ethers';
import Project from '../src/artifacts/contracts/Project.sol/Project.json';

const contractAddress = process.env.contract_address;

export default function App() {

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

  console.log(provider.getSigner())

  return (
    <div className="App">
      <p>Hello!</p>
    </div>
  );

}

This errors with:

window is not defined

I saw someone else suggest loading and setting it via state like so:

const [provider, setProvider] = useState({})

React.useEffect(() => {
   setProvider(new ethers.providers.Web3Provider(window.ethereum))
}, []);

const signer = provider.getSigner(); 

But this returns: TypeError: provider.getSigner is not a function

However if i comment out this code, refresh and let the page load, then uncomment the code and let hot reload refresh the component I get no such error and can successfully console.log the signer.

Pulling my limited supply of hair out trying to resolve this, any help would be appreciated.

1 Answers

I have managed to get this working whilst sticking with my functional components.

Within useEffect I included a statement to check if the windowobject was undefined:

if (typeof window.ethereum !== "undefined" || (typeof window.web3 !== "undefined")) {
   // Existing code goes here
}

And then had to make sure that any variables that I wanted to use outside of this if statement were saved to state as well as declared within the statement. Like:

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

This seemed to solve most of the issues with moving from CRA to Next and I now have the dApp back up and running.

Related