2

I have an issue with Next.js. When I'm trying to import a node module, the module uses the window object and Next.js is throwing an error: window is not defined.

The module is imported like this:

import * as widgets from 'survey-widgets';

widgets.autocomplete(Survey);

I guess Next.js dynamic imports will not work in my case. Is there any way of doing it?

Zsolt Meszaros
  • 21,961
  • 19
  • 54
  • 57
AWIXOR
  • 406
  • 4
  • 15

2 Answers2

1

Try deferring all the code that uses window or any other api that is restricted to the browser, in useEffect, because the code in useEffect only runs in the browser.

If you can't do that, then make an intermediary module which you will use to import survey-widgets and re-export what you need. So in the end, you import that intermediary module dynamically.

import * as widgets from 'survey-widgets
export default widgets
Ivan V.
  • 7,593
  • 2
  • 36
  • 53
1

For anyone looking for the solution for this, I solved it with NextJs Dynamic imports with no SSR.

What I did instead is importing my top level component using dynamic import like this:

const MyComponent= dynamic(
() => import('../components/hello3'),
  { ssr: false }
)

So the hello3 component will no longer be used in server side rendering and instead it will render on client side.

Then just use it like this:

<MyComponent/>
AWIXOR
  • 406
  • 4
  • 15