DEV Community

Jacob Pelletier for Yankeedom.io

Posted on

Next.js Guide | About pages/

Next.js Guide | About pages/

by Jacob Pelletier
Contact me for suggestions, comments, or just to say hello at jacob@yankeedo.io! 👋

Guide Prerequisites:

  1. Good Javascript knowledge
  2. Good Typescript knowledge
  3. Basic React knowledge
  4. Ensure Node.js 14.6.0 or newer is installed on your machine.

Image description


Follow me on my journey in learning Next.js. These guide break down documentation into little bite size pieces!

I was not born with the knowledge of Next.js, so in addition to hours of suffering, here is where additional wisdom of Next.js will come from:

  1. Next.js docs
  2. Udemy Course
  3. The Nest.js Handbook

This guide will use typescript, MongoDB for a database, and tailwind for UI. I also use VS Code.

I will likely add more information in the future as I come across good examples in code.

Previous Post
Next Post (coming soon!)


Routing

About Next.js Pages

What does the pages directory do?

Important note from docs:

Next.js 13 introduces the app/ directory (beta). This new directory has support for layouts, nested routes, and uses Server Components by default. Inside app/, you can fetch data for your entire application inside layouts, including support for more granular nested layouts (with colocated data fetching).

I have not chosen to create a guide on the app directory at this time, but maybe in the future!

What does the pages directory do?
From handbook:

Any URL is mapped to the filesystem, to files put in the pages folder, and you don't need any configuration (you have customization options of course).

What is a page?
From docs:

In Next.js, a page is a React Component exported from a .js, .jsx, .ts, or .tsx file in the pages directory. Each page is associated with a route based on its file name.

For example:

Image description

If you create pages/about.js that exports a React component like below, it will be accessible at /about.

Image description

What is pre-rendering?
From docs:

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. Pre-rendering can result in better performance and SEO.

Each generated HTML is associated with minimal JavaScript code necessary for that page. When a page is loaded by the browser, its JavaScript code runs and makes the page fully interactive. (This process is called hydration.)

SSG vs SSR

  1. SSG, or Static Site Generation is the recommended form of pre-rendering in the Next.js framework. This means that the HTML is generated at build time and will be reused on each request for the resource.
  2. SSR, or Server Side Rendering on the other hand, is a form of pre-rendering where the HTML is generated on each request of the resource.

SSR
"A google crawler inspecting SSR"

From docs:

Importantly, Next.js lets you choose which pre-rendering form you'd like to use for each page. You can create a "hybrid" Next.js app by using Static Generation for most pages and using Server-side Rendering for others.

We recommend using Static Generation over Server-side Rendering for performance reasons. Statically generated pages can be cached by CDN with no extra configuration to boost performance. However, in some cases, Server-side Rendering might be the only option.

You can also use Client-side data fetching along with Static Generation or Server-side Rendering. That means some parts of a page can be rendered entirely by client side JavaScript. To learn more, take a look at the Data Fetching documentation.

When should I use SSG?

  1. Whenever possible because it is much faster than rendering a page with every request.
  2. Marketing pages
  3. Blogs and portfolios
  4. E-commerce product listing
  5. Help and documentation

Image description

Create A Blank Slate To Work From

Before our experiments to learn more about pages and routing, I deleted the files home.module.css, _documents.tsx, and I deleted all the contents of globals.css and replace the contents of index.tsx with:

function Home() {
  return <div>Welcome to Next.js!</div>
}

export default HomePage
Enter fullscreen mode Exit fullscreen mode

Before edits:
Image description

After edits:
Image description

localhost:3000 result:
Image description

I will cover pages with dynamics routes into its own guide.

Static Generation

From docs:

If a page uses Static Generation, the page HTML is generated at build time. That means in production, the page HTML is generated when you run next build . This HTML will then be reused on each request. It can be cached by a CDN.
In Next.js, you can statically generate pages with or without data. Let's take a look at each case.

Static Generation Without Data

At this time, add a new about.tsx page as shown above.

Image description

Add the following code to the about.tsx page:

function About() {
  return <div>About</div>
}

export default About
Enter fullscreen mode Exit fullscreen mode

And there you have it, a statically generated site with no data. Well the journey here was exciting. The result? Maybe not so much. Let's make it more interesting with data.

Static Generation With Data

From docs:

Some pages require fetching external data for pre-rendering. There are two scenarios, and one or both might apply. In each case, you can use these functions that Next.js provides:

Your page content depends on external data: Use getStaticProps.
Your page paths depend on external data: Use getStaticPaths (usually in addition to getStaticProps).

Scenario 1: Your page content depends on external data:

// TODO: Need to fetch `posts` (by calling some API endpoint)
//       before this page can be pre-rendered.
export default function Blog({ posts }) {
  return (
    <ul>
      {posts.map((post) => (
        <li>{post.title}</li>
      ))}
    </ul>
  )
}
Enter fullscreen mode Exit fullscreen mode

To fetch this data on pre-render, Next.js allows you to export an async function called getStaticProps from the same file. This function gets called at build time and lets you pass fetched data to the page's props on pre-render.

export default function Blog({ posts }) {
  // Render posts...
}

// This function gets called at build time
export async function getStaticProps() {
  // Call an external API endpoint to get posts
  const res = await fetch('https://.../posts')
  const posts = await res.json()

  // By returning { props: { posts } }, the Blog component
  // will receive `posts` as a prop at build time
  return {
    props: {
      posts,
    },
  }
}
Enter fullscreen mode Exit fullscreen mode

Scenario 2: Your page paths depend on external data

Dynamic routes will be covered in a guide of their own in the future!

Server Side Rendering

If a page uses Server-side Rendering, the page HTML is generated on each request.

From docs:

To use Server-side Rendering for a page, you need to export an async function called getServerSideProps. This function will be called by the server on every request.

For example, suppose that your page needs to pre-render frequently updated data (fetched from an external API). You can write getServerSideProps which fetches this data and passes it to Page like below:

export default function Page({ data }) {
  // Render data...
}

// This gets called on every request
export async function getServerSideProps() {
  // Fetch data from external API
  const res = await fetch(`https://.../data`)
  const data = await res.json()

  // Pass data to the page via props
  return { props: { data } }
}
Enter fullscreen mode Exit fullscreen mode

Summary

Static Generation (Recommended): The HTML is generated at build time and will be reused on each request. To make a page use Static Generation, either export the page component, or export getStaticProps (and getStaticPaths if necessary). It's great for pages that can be pre-rendered ahead of a user's request. You can also use it with Client-side Rendering to bring in additional data.

Server-side Rendering: The HTML is generated on each request. To make a page use Server-side Rendering, export getServerSideProps. Because Server-side Rendering results in slower performance than Static Generation, use this only if absolutely necessary.


Previous Post
Next Post (coming soon!)

Top comments (1)

Collapse
 
Sloan, the sloth mascot
Comment deleted