Skip to content

Instantly share code, notes, and snippets.

@kirilkirkov
Last active February 20, 2024 08:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kirilkirkov/73ef5feb99fa45fa0896e5348ed0095d to your computer and use it in GitHub Desktop.
Save kirilkirkov/73ef5feb99fa45fa0896e5348ed0095d to your computer and use it in GitHub Desktop.
"Understanding Next.js: Prefetching, Server-Side Rendering, and Data Fetching for Dynamic Pages"
// pages/index.js

import Link from 'next/link'

export default function HomePage() {
  return (
    <div>
      <h1>Welcome to our news site!</h1>
      <ul>
        <li>
          <Link href="/news/1">
            <a>News Article 1</a>
          </Link>
        </li>
        <li>
          <Link href="/news/2">
            <a>News Article 2</a>
          </Link>
        </li>
        <li>
          <Link href="/news/3">
            <a>News Article 3</a>
          </Link>
        </li>
      </ul>
    </div>
  )
}

This code represents the homepage of a news site. Each news article is represented as a link to another page on the site. Next.js will automatically prefetch the JavaScript code for these pages due to the next/link component.

// pages/news/[id].js

export async function getServerSideProps(context) {
  const { id } = context.params
  const response = await fetch(`https://api.example.com/news/${id}`)
  const data = await response.json()

  return {
    props: { data }, // will be passed to the page component as props
  }
}

export default function NewsArticle({ data }) {
  return (
    <div>
      <h1>{data.title}</h1>
      <p>{data.content}</p>
    </div>
  )
}

This code represents a dynamic page for a news article. The getServerSideProps function fetches the data for the article from an API on the server-side. When navigating to this page, Next.js will fetch the data for the page when you navigate to it, even if the JavaScript code for the page was prefetched. The fetched data is passed as props to the page component and used to render the article's title and content.

The Power of <Link>

Next.js simplifies routing by using a file-based approach. All you need to do is create files within the ./pages/ directory, and Next.js automatically creates routes based on these files.

The <Link> component is used to navigate between these pages, similar to the traditional <a> tag in HTML:

<Link href="/page2">
  <a>Go to Page 2</a>
</Link>

However, the <Link> component in Next.js has a special feature: it automatically prefetches the JavaScript needed for the linked page. This means that the JavaScript required to render the linked page is already downloaded and ready to go when you click on the link, making your application feel much faster.

You can verify this automatic prefetching by inspecting the network traffic in your browser's developer tools. When you load a page that contains a <Link>, you'll see that the JavaScript for the linked page is also fetched.

How Automatic Prefetching Works

The automatic prefetching in Next.js is quite intelligent. It only prefetches links that are currently visible in the viewport by using the Intersection Observer API. If the network connection is slow or the user has enabled data saving, prefetching is disabled to save resources.

When prefetching, Next.js only downloads the JavaScript code for the page; it doesn't actually execute the code. This means it doesn't fetch additional data that might be requested when the page is actually loaded.

Controlling Prefetching

While prefetching is generally beneficial, it might not be necessary for all links, especially for pages that are infrequently visited. You can disable prefetching on a per-link basis by setting the prefetch prop to false:

<Link href="/infrequent-page" prefetch={false}>
  <a>Infrequently Visited Page</a>
</Link>

Prefetching with Custom Routing

The <Link> component should cover most routing needs, but there might be cases where you need more control over routing, such as executing some code before navigating to a new route. You can create your own routing component by using the router API provided by next/router.

When creating custom routing components, you can still utilize prefetching by calling the prefetch method from the useRouter hook. This allows you to manually prefetch specific routes when necessary.

In Conclusion

The <Link> component in Next.js offers more than just easy navigation between pages. With its automatic prefetching feature, it can significantly improve the performance of your application by preemptively fetching JavaScript for linked pages. This feature can also be utilized in custom routing components for greater control over prefetching behavior. Remember to be considerate of user resources by disabling prefetching for infrequently visited pages.

Next.js is a powerful React framework that enables features such as Server-Side Rendering (SSR), Static Site Generation (SSG), Incremental Static Regeneration (ISR), and Client-Side Rendering (CSR). One of the tools it uses to improve application performance is a technique called prefetching.

Prefetching in Next.js

In Next.js, prefetching is a process where the JavaScript code (bundles) for linked pages are fetched in the background before the user navigates to them. This is facilitated by the next/link component. By default, the prefetch property in next/link is set to true, which means that Next.js will automatically prefetch the JavaScript code for all linked pages.

When you navigate to a new page in a Next.js application, if the page's JavaScript code has been prefetched, it's already available in the browser cache and doesn't need to be downloaded again. This can lead to a more responsive application as the new page can be rendered faster.

However, it's important to understand that the prefetching process only downloads the JavaScript bundles needed to render the page. It doesn't fetch the full HTML of the page as generated by SSR.

Server-Side Rendering (SSR) in Next.js

SSR is a technique where the HTML for a page is generated on the server rather than in the client's browser. This HTML includes the initial rendering of the page content, which can be displayed by the browser immediately, even before the JavaScript has been fully downloaded and executed.

In Next.js, you can enable SSR for a page by exporting a function called getServerSideProps from that page. This function runs on the server for every request and can fetch the data needed to render the page. The fetched data is then passed as props to the page component and can be used to generate the HTML for the page.

Data Fetching for Dynamic Pages

For dynamic pages (i.e., pages that use getServerSideProps or getInitialProps), even if the page's JavaScript bundle is prefetched, the data needed to render the page is not fetched until you navigate to the page. This is because these functions (getServerSideProps, getInitialProps) are designed to fetch fresh data from the server for each request.

When you navigate to a dynamic page, Next.js will make an additional HTTP (XHR) request to the server to fetch the data required for the page. This is in addition to the prefetching of the JavaScript code for the page.

However, if you use getStaticProps instead of getServerSideProps or getInitialProps, Next.js will prefetch the data for the page during the prefetching process and include it directly in the JavaScript bundle for the page. This means that no additional HTTP requests for data are needed when navigating to the page.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment