Window is not defined in Next.js?

Introduction

This code displays the width and height of your web browser.
Error for the code above.

Pre-Rendering

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?

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:

Create a new component and save in NewComponent.tsx

Then, we can import the component to our index.tsx file:

Import the newly created component with the option { ssr: false }

What just happened?

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

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 :)

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store