Next.js Guide | About pages/
Tags: webdev, nextjs, typescript, mongodb
Published: 2023-02-03 16:25:20

## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q2zi9dpa6n37ld2m2a3q.jpg)

---

**Follow me on my journey in learning [Next.js](https://nextjs.org/).** 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](https://nextjs.org/docs)
2. [Udemy Course](https://www.udemy.com/course/full-stack-development-with-next-js-typescript/)
3. [The Nest.js Handbook](https://www.freecodecamp.org/news/the-next-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](https://dev.to/jacobjpelletier/nextjs-guide-getting-started-2mc2)
Next Post (coming soon!)

---

![Routing](https://media0.giphy.com/media/xUNd9YJwF6ifDUnqNi/giphy.gif?cid=ecf05e47zkc18yugby7pxlyo33ouaye1tj6seamgrthdfsyo&rid=giphy.gif&ct=g)

## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2lz6dl4rrj90xxtlb1hq.png)

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mzs12gr6048kkx5o1bjv.png)

**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](https://media4.giphy.com/media/l41lXC2FUZ5ljuqly/giphy.gif?cid=ecf05e47zdofk72hj9reazmxwgfvt8xbwm4ssqox4bwfcvdb&rid=giphy.gif&ct=g)
"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](https://nextjs.org/docs/basic-features/data-fetching/client-side) 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lhrssh83je9lvjp954bk.png)

## 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
```

Before edits:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bbcbqe2v3g95erzauuwb.png)

After edits:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5b9794iaxkxk0g74xxcf.png)

localhost:3000 result:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/twzr2359hxf4rll1cub5.png)

I will cover [pages with dynamics routes](Pages with Dynamic 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ifcy6bkzme7y4jmraf8h.png)

Add the following code to the about.tsx page:

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

export default About
```

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>
  )
}
```

> 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,
    },
  }
}
```

Scenario 2: Your page paths depend on external data

[Dynamic routes](https://nextjs.org/docs/basic-features/pages#scenario-2-your-page-paths-depend-on-external-data) 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 } }
}
```


## 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](https://dev.to/jacobjpelletier/nextjs-guide-getting-started-2mc2)
Next Post (coming soon!)