Home > Enterprise >  "window not defined" or "document not defined" when importing module in Next.js
"window not defined" or "document not defined" when importing module in Next.js

Time:09-11

Trying to add Wysiwyg editor to my web app.

When trying to import editor module, get error. Tried both react-draft-wysiwyg and react-quill. First leads to "window not defined", second to "document not defined" when loading page. And all this just on import, I not even used it anywhere.

I looked for solution, but I didn't find similar situation anywhere. The most near to it was case when somebody also had "document not defined", but there it was cured by using NoSsr wrapper. This case, as I already said, I can't even load page with only import of this element.

So, this doesn't work:

...
import DeleteIcon from '@mui/icons-material/Delete';
import { DesktopDatePicker } from '@mui/x-date-pickers'
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import {NoSsr} from "@mui/base";
import { EditorState } from 'draft-js';
import { Editor } from 'react-draft-wysiwyg';
...

But this is okay:

...
import DeleteIcon from '@mui/icons-material/Delete';
import { DesktopDatePicker } from '@mui/x-date-pickers'
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import {NoSsr} from "@mui/base";
import { EditorState } from 'draft-js';
...

enter image description here

Could somebody help me please, if you know why this problem appears?

Thank you in advance.

CodePudding user response:

Nextjs consider the import in the page's initial javascript bundle. The package you are using needs to be imported lazily since it is internally using window and document objects, this should not be executed on the server. Try to import react-draft-wysiwyg and react-quill dynamically with next/dynamic.

Something like this:

import dynamic from 'next/dynamic'

const { Editor } = dynamic(() => import('react-draft-wysiwyg'), {ssr: false})

CodePudding user response:

you can use window just put a check before using it like this

if(typeof window !== "undefined"){
  window.location.reload()
 }
  • Related