top | item 28610965

(no title)

axhl | 4 years ago

Not the original commenter but would appreciate more on this. If you can be bothered, could you also expand a bit on how Next.js works under the hood when it comes to forcing CSR à la

  {typeof window === 'undefined' ? null : children
On a related note, thanks for what you do for Next in the discord.

discuss

order

drewpc|4 years ago

Read @leerob's answer first. Additionally, the notion of "forcing" CSR might be a misnomer. The way I understand it, NextJS always prefers CSR; the server renders HTML on first page load and the NextJS framework attaches JS stuff to the page on render to handle the client-side interactivity. So, if you turn off JS on your browser and load the page, everything works out of the box (page renders HTML, links work, etc). There are ways to specify server-only data requirements.

Once the client-side JS has taken over, the `next/link` component [1] is used to render and listen to events when a user clicks on a link. That component tells `next/router` to render the page that was clicked on. All of this happens on the client by default. If JS is disabled on the client, then the HTML rendered by the `next/link` component on the server is a simple `<a/>` tag and a normal browser page load occurs.

[1] https://nextjs.org/docs/api-reference/next/link

leerob|4 years ago

The easiest way to force CSR would be to render nothing on the server, `useEffect` and then render everything on the client. This could be at the top level of your application. But, I'm guessing most folks don't actually want that. It's typically a better user experience to serve some loading state/skeleton pre-rendered from the server, followed by loading data client-side (instead of full CSR). If you have NPM packages or code that can only execute on the client-side, you can also use next/dynamic to load specific components in client-side only.

https://nextjs.org/docs/advanced-features/dynamic-import