Window is not defined in Next.js?
Introduction
Take a look at this piece of code for our Next.js app. Can you tell why we are getting an error?
Pre-Rendering
If you said something along the lines of Pre-Rendering, you are correct.
If you are coming from React.js or are unfamiliar with pre-rendering, you might be scratching your head.
From the official Next.js documentation:
By default, Next.js pre-renders every page. This means that Next.js generates HTML for each page in advance, instead of having it all done by client-side JavaScript. Pre-rendering can result in better performance and SEO.
I won’t go too deep about pre-rendering but you can read more here.
So what’s with the error?
Since Next.js generates the HTML on the server instead of the client, it has no idea what your window size is! The window object is available only on the client-side.
Luckily, Next.js gives us the ability to choose which type of rendering to use. We can do this by using dynamic imports.
We can move the parts of the code that uses window to a new component:
Then, we can import the component to our index.tsx file:
What just happened?
Instead of giving up pre-rendering entirely, we isolated the parts that needed to be rendered on the client-side.
We put that in a separate component, and told Next.js to render it without SSR (Server-Side Rendering).
This way, we are able to still get the benefit of pre-rendering as well as being able to use client-side objects, such as window.
Conclusion
I ran into this issue multiple times until I figured out that dynamic imports existed. I haven’t seen many people mention it online so I hope that this is helpful to whoever finds it.
If you have further questions or suggestions, you can DM me on twitter. Consider dropping a follow to stay updated with my content!
Twitter: https://twitter.com/gooltoe
Github Repo: https://github.com/gooltoe/NextJS-Dynamic-Import-Example
Thanks for reading, see you on the next one :)