Getting window is not defined in next.js middleware

Viewed 21

I'm building web3 project, In which if the user is logged in via metamask, I want to check for window.ethereum for any change in metamask account change by the user,

Currently I can think for writting middleware in next.js for checking that, but getting window is not defined in console.

in _middleware.ts file

declare let window: any

export function middleware() {
  if (typeof window === 'object' && window.ethereum) {
    console.log('HAVE METAMASK')
    window.ethereum.on('accountsChanged', function () {
      console.log('Account changed')
    })
  } else {
    console.log('NO METAMASK')
  }
}

I'm getting NO METAMASK being printed in the console, and when I tried to print window getting window is not defined error

Is there any other way to achieve this?

0 Answers
Related