Search code examples
reactjsnext.jsserver-side-renderingclient-side

Next.js - Client Side Navigation vs. changes in html


I'm currently working through the next.js tutorial, but I'm struggling to understand the following:

The tutorial is telling me here, that clicking a <Link> element won't trigger a server request, and instead do "Client-side navigation", i.e. adjusting the page content with js:

The Link component enables client-side navigation between two pages in the same Next.js app. Client-side navigation means that the page transition happens using JavaScript

Three questions right away:

  • This sounds like regular SPA react routing without next.js etc. to me. But it isn't, right?
  • The <Link> still works if I disable javascript in Chrome dev tools. This shows that the transition is actually not happening with js. Is this a contradiction to their statement?
  • When I right click the page and click "view source" (in Chrome) I get different HTML before and after clicking the <Link>. (Contratry to the "regular" react behavior). How can this be considered "Client-side navigation"?

Going further in the tutorial, they tell me here:

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

This statement sound like a contradiction to the other one quoted above. Can you help me to clarify this? When I click the <Link> what exactly is happening? Is a new html file loaded? If so, how can this happen "client side". Thank you!


Solution

  • Here is how I understand it:

    The approach Next.js takes for client-side navigation is a mixture of SPA-style navigation and traditional navigation

    • In SPA-style navigation, a "link" is a component with some JS logic. It does not have a <a> element. When you click on it, some JS will run to render the new page. If you disable JS then you can't navigate to a new page;
    • In traditional navigation, a link is really a <a> element. If you click on it, then the browser will discard the current page and load the new page entirely. If you disable JS then you can still navigate to the new page;
    • In Next.js navigation, a "link" is a component with some JS logic, but it also has this <a> element under the hood. When you click on it, some JS will run to render the new page and prevent the default <a> navigation. So even if you disable JS, you'll still be able to navigate in a traditional fashion through the <a> element. The pre-rendered page will be fetched and loaded. This is really useful in terms of SEO (as crawlers typically don't have JS enabled), and is the main problem Next.js wants to solve.

    In short, when JS is enabled, Next.js navigation behaves just like in SPAs; when JS is disabled, it behaves just like in traditional websites.

    Update:

    I made a video to further demonstrate the concept: https://www.youtube.com/watch?v=D3wVDE9GGVE