Handle client-only code in Next.js like a pro
Get rid of the dreaded inconsistencies between browser code and Next.js server-side rendering with NextPatterns.
Did you say client-only?
Here are some features that require 'client-only' JavaScript code in Next.js:
a frontend React application needs a lot of JavaScript code that is specific to browsers.
- 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...
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.