Handle client-only code in Next.js like a pro

Client-only mascott

Did you say client-only?

Here are some features that require 'client-only' JavaScript code in Next.js:
  • Displaying a map thanks to Leaflet
  • Creating interactive charts thanks to D3
  • Using technologies like WebGL or WebAssembly
  • Using browser features to check if cookies are enabled, display current
    date-time with localization...
  • Storing data in the localStorage, sessionStorage or IndexedDB
  • Relying on older libraries like jQuery
  • And the list goes on...
See, it's everywhere! Client-only code is code that works only in the browser. Without surprise,
a frontend React application needs a lot of JavaScript code that is specific to browsers.

What makes it so difficult?

Does it really need its own course?

As a default, Next always tries to render your React components server-side. If you don't handle client-only code properly, you are good to trigger "window not defined" or "Text content does not match server-rendered HTML" errors.

Each developer on StackOverflow will propose their own little trick to fix them, but they don't explain properly which solution should be used in each specific situation.

window is not defined

Try it out!

Each pattern is an article focused on solving a specific problem.
It includes an interactive code demonstration.
For those who want to practice, each pattern comes with an optional exercise with
a live preview in a web container.

Learn more about client-only code in Next.js and other topics on NextPatterns