I
I
Im p3l2022-04-09 14:47:43
React
Im p3l, 2022-04-09 14:47:43

How to globally declare to avoid "Server Error ReferenceError: window is not defined" error in next.js?

Good afternoon, I encountered the error " Server Error ReferenceError: window is not defined " when using the crypto-pro library in Next.js
The crypto-pro library is imported from node_modules

import  'crypto-pro'
const getUserCertificates = async (): Promise<Certificate[]> => {
  let oStore
  const certificates: Certificate[] = []

  try {
    oStore = await window.cadesplugin.CreateObjectAsync('CAdESCOM.Store')
  } catch (err) {
    console.error(err)
  }
}
const certs = await getUserCertificates()
console.log(certs)


declared globally cadesplugin in global.d.ts file
export {}
declare global {
  interface Window extends Window{
    cadesplugin: any
  }
}


and added the global.d.ts file to tsconfig
{
  ...,
  "include": [
    "next-env.d.ts",
    "global.d.ts",
    "**/*.ts",
    "**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ],
}


How can this problem be solved?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
wonderingpeanut, 2022-04-11
@wonderingpeanut

a simple check for the presence of window will fix the error

if (typeof window !== 'undefined') {
  // кодище
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question