Next.js (Part 2)

getStaticProps, getServerSideProps, getStaticPaths and useSWR

Pre-rendering

Next.js has two forms of pre-rendering: Static Generation and Server-side Rendering. The difference is in when Next.js generates the HTML for a page.

Static Generation is a pre-rendering approach that generates the HTML pages at build time.

Server-side Rendering is a pre-rendering approach that generates the HTML on each request.

You can create a Next.js app that uses Static Generation for some pages and Server-side Rendering for others.

Static Generation (with data)

In Next.js, after exporting a page function, a developer can export a getStaticProps function.

A getStaticProps runs at build time.

getStaticProps

A getStaticProps function can be used to generate a page based on data returned by a web service call*.

You should not fetch an API Route from getStaticProps or getStaticPaths. Instead, write your server-side code directly in getStaticProps or getStaticPaths (or call a helper function).

/pages/articles/index.js

getStaticProps

getServerSideProps

A getServerSideProps function is used at runtime to build a page in response to a request (with or without caching).

/pages/articles/[id]/index.js

getServerSideProps

getStaticPaths

getStaticProps and getStaticPaths can be used together to generate multiple pages.

/pages/articles/[id]/index.js

getStaticProps and getStaticPaths being used together

next export

next export can be used to generate html pages that can be uploaded to a static web server.

$ npm run export

npm run export

out folder with generated pages

/out/articles/36

useSWR

Once the server-side rendered parts of a page have been downloaded JavaScript running on the page can fetch data and populate the remaining parts of the page (client-side).

$ npm install swr

/pages/articles/[id]/index.js

Catch all routes

Dynamic routes can be extended to catch all paths by adding three dots (...) inside the brackets. For example:

pages/post/[...slug].js matches /post/a, but also /post/a/b, /post/a/b/c and so on.

pages/fullname/[...slug]/index.js matches /fullname/neil, but also /fullname/neil/haddley, /fullname/neil/leonard/haddley and so on.

You can use names other than slug, such as: [...param]

/pages/fullname/[...slug]/index.js

Client-side code

Catch all routes