From 042dab356e6be1882372e8896b7402e9e0a285db Mon Sep 17 00:00:00 2001 From: Shu Uesugi Date: Wed, 4 Mar 2020 23:44:55 -0800 Subject: [PATCH 01/21] Update pages doc for SSG --- docs/basic-features/pages.md | 260 +++++++++++++++++++++++++++-------- 1 file changed, 205 insertions(+), 55 deletions(-) diff --git a/docs/basic-features/pages.md b/docs/basic-features/pages.md index ade94c5e8a46c76..a4202b14b266e8f 100644 --- a/docs/basic-features/pages.md +++ b/docs/basic-features/pages.md @@ -4,104 +4,254 @@ description: Next.js pages are React Components exported in a file in the pages # Pages -A page is a [React Component](https://reactjs.org/docs/components-and-props.html) exported from a `.js`, `.ts`, or `.tsx` file in the `pages` directory. +> This document is for Next.js versions 9.3 and up. If you're using older versions of Next.js, refer to our [previous documentation](/docs/tag/v9.2.2/basic-features/pages). -Pages are associated with a route based on their file name. For example `pages/about.js` is mapped to `/about`. You can even utilize dynamic route parameters through the filename. +In Next.js, a **page** is a [React Component](https://reactjs.org/docs/components-and-props.html) exported from a `.js`, `.ts`, or `.tsx` file in the `pages` directory. Each page is associated with a route based on its file name. -For example `pages/index.js` could be a React component returning some [JSX](https://reactjs.org/docs/introducing-jsx.html) content: +**Example**: If you create `pages/about.js` that exports a React component like below, it will be accessible at `/about`. ```jsx -function HomePage() { - return
Welcome to Next.js!
+function About() { + return
About
} -export default HomePage +export default About ``` +### Pages with Dynamic Routes + +Next.js supports pages with dynamic routes. For example, if you create a file called `pages/posts/[id].js`, then it will be accessible at `posts/1`, `posts/2`, etc. + +> To learn more about dynamic routing, check the [routing documentation](/docs/routing/dynamic-routes.md). + ## Pre-rendering -Next.js comes with the concept of pre-rendering built-in. This is enabled by default. Pre-rendering comes in 2 forms: +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_.) + +### Two Forms of Pre-rendering + +Next.js has two forms of pre-rendering: **Static Generation** and **Server-side Rendering**. The difference is in **when** it generates the HTML for a page. + +- [**Static Generation (Recommended)**](#static-generation-recommended): The HTML is generated at **build time** and will be reused on each request. +- [**Server-side Rendering**](#server-side-rendering): The HTML is generated on **each request**. + +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 to boost performance. However, in some cases, Server-side Rendering might be the only option. + +Finally, you can always use **Client-side Rendering** 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](/docs/basic-features/data-fetching#fetching-data-on-the-client-side) documentation. + +## Static Generation (Recommended) + +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 + +By default, Next.js pre-renders pages using Static Generation without fetching data. Here's an example: + +```jsx +function About() { + return
About
+} + +export default About +``` + +Note that this page does not need to fetch any external data to be pre-rendered. In cases like this, Next.js simply generates a single HTML file per page during build time. + +### Static Generation with data + +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 a special function Next.js provides: + +1. Your page **content** depends on external data: Use `getStaticProps`. +2. Your page **paths** depend on external data: Use `getStaticPaths` (usually in addition to `getStaticProps`). + +#### Scenario 1: Your page **content** depends on external data + +**Example**: Your blog page might need to fetch the list of blog posts from a CMS (content management system). + +```jsx +// TODO: Need to fetch `posts` (by calling some API endpoint) +// before this page can be pre-rendered. +function Blog({ posts }) { + return ( + + ) +} + +export default Blog +``` + +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. + +```jsx +// You can use any data fetching library +import fetch from 'node-fetch' + +function Blog({ posts }) { + // Render posts... +} -- Static Generation -- Server-side rendering +// 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, + }, + } +} -Next.js applications can be a hybrid combination of these rendering targets. You decide per-page if it will be statically rendered at build time or if will be server-rendered on-demand. +export default Blog +``` -The way that Pre-rendering works in Next.js is that the page is rendered to HTML either at build-time or on-demand, this generated HTML will be optimized automatically. +To learn more about how `getStaticProps` works, check out the [Data Fetching documentation](/docs/basic-features/data-fetching#getstaticprops). -The generated HTML will include the JavaScript needed to load React with the current page's React component. When that is loaded we use a process called "hydration" to make sure the React event handlers and effects are attached and called. +#### Scenario 2: Your page paths depend on external data -## Static Generation +Next.js allows you to create pages with **dynamic routes**. For example, you can create a file called `pages/posts/[id].js` to show a single blog post based on `id`. This will allow you to show a blog post with `id: 1` when you access `posts/1`. -Generally used for: +> To learn more about dynamic routing, check the [routing documentation](/docs/routing/dynamic-routes.md). -- Static Marketing pages -- Static Blog -- Dashboards +However, which `id` you want to pre-render at build time might depend on external data. -Referred to as: +**Example**: suppose that you've only added one blog post (with `id: 1`) to the database. In this case, you'd only want to pre-render `posts/1` at build time. -- Static Site Generation (SSG) -- Static Generation -- Static Websites +Later, you might add the second post with `id: 2`. Then you'd want to pre-render `posts/2` as well. -The page is rendered to static HTML when `next build` is ran. `next build` will output the HTML into a `.html` file and that file will be served consistently without changes. +So your page **paths** that are pre-rendered depend on external data**.** To handle this, Next.js lets you `export` an `async` function called `getStaticPaths` from a dynamic page (`pages/posts/[id].js` in this case). This function gets called at build time and lets you specify which paths you want to pre-render. -Considering that by default pages in Next.js have consistent output between renders, Next.js will pre-render the pages that don't have blocking data requirements. +```jsx +import fetch from 'node-fetch' -One upside of build-time pre-rendering is that static HTML can be served from a CDN automatically if your hosting provider supports it. +// This function gets called at build time +export async function getStaticPaths() { + // Call an external API endpoint to get posts + const res = await fetch('https://.../posts') + const posts = await res.json() + + // Get the paths we want to pre-render based on posts + const paths = posts.map(post => `/posts/${post.id}`) + + // We'll pre-render only these paths at build time. + // { fallback: false } means other routes should 404. + return { paths, fallback: false } +} +``` + +Also in `pages/posts/[id].js`, you need to export `getStaticProps` so that you can fetch the data about the post with this `id` and use it to pre-render the page: ```jsx -// This page has no blocking data requirements -// it'll be rendered as static HTML at build time -function HomePage() { - return
Welcome to Next.js!
+import fetch from 'node-fetch' + +function Post({ post }) { + // Render post... +} + +export async function getStaticPaths() { + // ... } -export default HomePage +// This also gets called at build time +export async function getStaticProps({ params }) { + // params contains the post `id`. + // If the route is like /posts/1, then params.id is 1 + const res = await fetch(`https://.../posts/${params.id}`) + const post = await res.json() + + // Pass post data to the page via props + return { props: { post } } +} + +export default Post ``` -## Server-Side Rendering +To learn more about how `getStaticPaths` works, check out the [Data Fetching documentation](/docs/basic-features/data-fetching.md#getstaticpaths). + +### When should I use Static Generation? -Generally used for: +We recommend using **Static Generation** (with and without data) whenever possible because your page can be built once and served by CDN, which makes it much faster than having a server render the page on every request. -- Frequently updated data -- CMS backed pages +You can use Static Generation for many types of pages, including: -Referred to as: +- Marketing pages +- Blog posts +- E-commerce product listings +- Help and documentation -- Server-Side rendering (SSR) -- Dynamic rendering -- On-demand rendering +You should ask yourself: "Can I pre-render this page **ahead** of a user's request?" If the answer is yes, then you should choose Static Generation. -When a request comes in to the server the page is rendered on-demand, meaning the user that requests the page always gets the latest data. This mode is opted into by adding a blocking data requirement to the page. +On the other hand, Static Generation is **not** a good idea if you cannot pre-render a page ahead of a user's request. Maybe your page shows frequently updated data, and the page content changes on every request. -Data is always up-to-date but it comes at the cost of a slightly higher [Time to First Byte](https://web.dev/time-to-first-byte/) as HTML has to be rendered for the specific user. Additionally a Node.js runtime has to be running and has to scale with the amount of traffic. +In cases like this, you can do one of the following: + +- Use Static Generation with **Client-side Rendering:** You can skip pre-rendering some parts of a page and then use client-side JavaScript to populate them. To learn more about this approach, check out the [Data Fetching documentation](/docs/basic-features/data-fetching#fetching-data-on-the-client-side.md). +- Use **Server-Side Rendering:** Next.js pre-renders a page on each request. It will be slower because the page cannot be cached by a CDN, but the pre-rendered page will always be up-to-date. We'll talk about this approach below. + +## Server-side Rendering + +> Also referred to as "SSR" or "Dynamic Rendering". + +If a page uses **Server-side Rendering**, the page HTML is generated on **each request**. + +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: ```jsx -// This page has defined `getInitialProps` to do data fetching. -// Next.js will execute `getInitialProps` -// It will wait for the result of `getInitialProps` -// When the results comes back Next.js will render the page. -// Next.js will do this for every request that comes in. -import fetch from 'isomorphic-unfetch' - -function HomePage({ stars }) { - return
Next stars: {stars}
+import fetch from 'node-fetch' + +function Page({ data }) { + // Render data... } -HomePage.getInitialProps = async ({ req }) => { - const res = await fetch('https://api.github.com/repos/zeit/next.js') - const json = await res.json() - return { stars: json.stargazers_count } +// 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 } } } -export default HomePage +export default Page ``` -## Learn more +As you can see, `getServerSideProps` is similar to `getStaticProps`, but the difference is that `getServerSideProps` is run on every request instead of on build time. + +To learn more about how `getServerSideProps` works, check out our [Data Fetching documentation](/docs/basic-features/data-fetching.md#getserversideprops) -For more information on what to do next, we recommend the following sections: +## Summary + +We've discussed two forms of pre-rendering for Next.js. + +- **Static Generation (Recommended):** The HTML is generated at **build time** and will be reused on each request. To make a page use Static Generation, just 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. + +## Learn More + +We recommend you to read the following sections next: + +
+ + Data Fetching: + Learn more about data fetching in Next.js. + +
From 61ebde89c2f2b1ce731175461416321d5ec728e5 Mon Sep 17 00:00:00 2001 From: Shu Uesugi Date: Thu, 5 Mar 2020 00:19:57 -0800 Subject: [PATCH 02/21] Add data fetching doc --- docs/basic-features/data-fetching.md | 408 +++++++++++++++++++++++---- docs/basic-features/pages.md | 6 +- 2 files changed, 355 insertions(+), 59 deletions(-) diff --git a/docs/basic-features/data-fetching.md b/docs/basic-features/data-fetching.md index 9641b98099d0840..68df39f57f5a14a 100644 --- a/docs/basic-features/data-fetching.md +++ b/docs/basic-features/data-fetching.md @@ -2,96 +2,392 @@ description: Next.js can handle data fetching in multiple ways for server-rendered and static pages. Learn how it works here. --- -# Data fetching +# Data Fetching -Next.js has 2 pre-rendering modes built-in: +> This document is for Next.js versions 9.3 and up. If you're using older versions of Next.js, refer to our [previous documentation](/docs/tag/v9.2.2/basic-features/data-fetching). -- [Static Generation](#static-generation) -- [Server-side rendering](#server-side-rendering) +In the [Pages documentation](/docs/basic-features/pages.md), we've explained that Next.js has two forms of pre-rendering: **Static Generation** and **Server-side Rendering**. In this page, we'll talk in depths about data fetching strategies for each case. We recommend you to [read through the Pages documentation](<(/docs/basic-features/pages.md)>) first if you haven't done so. -You can learn more about the differences in the [pages section](/docs/basic-features/pages.md#pre-rendering). +We'll talk about the three special Next.js functions you can use to fetch data for pre-rendering: -These rendering modes are tightly coupled to the way that you do data fetching. +- `getStaticProps` (Static Generation): Fetch data at **build time**. +- `getStaticPaths` (Static Generation): Specify [dynamic routes](/docs/routing/dynamic-routes.md) to pre-render based on data. +- `getServerSideProps` (Server-side Rendering): Fetch data on **each request**. -In Next.js data fetching generally happens at the page level. There are multiple reasons for this: +In addition, we'll talk briefly about how to do fetch data on the client side. -- Avoid data fetching waterfalls, having to render then wait then render etc. -- When pre-rendering React needs to have all data available before rendering. +## `getStaticProps` (Static Generation) -## Static Generation +If you export an `async` function called `getStaticProps` from a page, Next.js will pre-render this page at build time using the props returned by `getStaticProps`. -By default Next.js pages that don't use [`getInitialProps`](/docs/api-reference/data-fetching/getInitialProps.md) get rendered to static HTML at `next build` time. +```jsx +export async function getStaticProps(context) { + return { + props: {}, // will be passed to the page component as props + } +} +``` + +The `context` parameter is an object containing the following keys: -This is useful for, as an example, dashboards that have a lot of dynamic data that depends on a specific user. +- `params`: `params` contains the route parameters for pages using dynamic routes. For example, if the page name is `[id].js` , then `params` will look like `{ id: ... }`. To learn more, take a look at the [Dynamic Routing documentation](/docs/routing/dynamic-routes.md). You should use this together with `getStaticPaths`, which we'll explain later. -You might not want to server-render that content but instead load the data client-side. +### Simple Example -For this particular use case [ZEIT](https://zeit.co) has created a data-fetching library called [SWR](https://github.com/zeit/swr). +Here's an example which uses `getStaticProps` to fetch a list of blog posts from a CMS (content management system). This example is also in the [Pages documentation](/docs/basic-features/pages.md). ```jsx -// This page doesn't define `getInitialProps`. -// Next.js will export the page to HTML at build time with the loading state -// When the page is loaded in the browser SWR will fetch the data -// Using the defined fetcher function -import fetch from 'unfetch' -import useSWR from 'swr' - -const API_URL = 'https://api.github.com' -async function fetcher(path) { - const res = await fetch(API_URL + path) - const json = await res.json() - return json +// You can use any data fetching library +import fetch from 'node-fetch' + +// posts will be populated at build time by getStaticProps() +function Blog({ posts }) { + return ( +
    + {posts.map(post => ( +
  • {post.title}
  • + ))} +
+ ) } -function HomePage() { - const { data, error } = useSWR('/repos/zeit/next.js', fetcher) +// This function gets called at build time on server-side. +// It won't be called on client-side, so you can even do +// direct database queries. See the "Technical Details" section. +export async function getStaticProps() { + // Call an external API endpoint to get posts. + const res = await fetch('https://.../posts') + const posts = await res.json() - if (error) return
failed to load
- if (!data) return
loading...
- return
Next stars: {data.stargazers_count}
+ // By returning { props: posts }, the Blog component + // will receive `posts` as a prop at build time + return { + props: { + posts, + }, + } } -export default HomePage +export default Blog ``` -## Server-side rendering +### When should I use `getStaticProps`? + +You should use `getStaticProps` if: + +- The data required to render the page is available at build time ahead of a user's request. +- The data comes from headless CMS. +- The data can be publicly cached (not user-specific). +- The page must be pre-rendered (for SEO) and be very fast — `getStaticProps` generates HTML and JSON files, both of which can be cached by a CDN for performance. + +### Technical Details + +#### Only runs at build time + +Because `getStaticProps` runs at build time, it does **not** receive data that's only available during request time, such as query parameters or HTTP headers as it generates static HTML. + +#### Write server-side code directly + +Note that `getStaticProps` runs only on the server-side. It will never be run on the client-side. It won't even be included in the JS bundle for the browser. That means you can write code such as direct database queries without them being sent to browsers. You should not fetch an **API route** from `getStaticProps` — instead, you can write the server-side code directly in `getStaticProps`. + +#### Statically Generates both HTML and JSON + +When a page with `getStaticProps` is pre-rendered at build time, in addition to the page HTML file, Next.js generates a JSON file holding the result of running `getStaticProps`. + +This JSON file will be used in client-side routing through `next/link` ([documentation](/docs/api-reference/next/link)) or `next/router` ([documentation](/docs/api-reference/next/router)). When you navigate to a page that's pre-rendered using `getStaticProps`, Next.js fetches this JSON file (pre-computed at build time) and uses it as the props for the page component. This means that client-side page transitions will **not** call `getStaticProps` as only the exported JSON is used. + +#### Only allowed in a page -Pages might have to wait on some data before pre-rendering, for example, if you want the page to be indexed with the data by search engines. +`getStaticProps` can only be exported from a **page**. You can't export it from non-page files. -Next.js comes with [`getInitialProps`](/docs/api-reference/data-fetching/getInitialProps.md), which is an [`async`](https://zeit.co/blog/async-and-await) function that can be added to any page as a [`static method`](https://javascript.info/static-properties-methods). +One of the reasons for this restriction is that React needs to have all the required data before the page is rendered. -`getInitialProps` allows the page to wait for data before rendering starts. +Also, you must use `export` — it will **not** work if you add `getStaticProps` as a property of the page component. -Using `getInitialProps` will make the page opt-in to on-demand [server-side rendering](/docs/basic-features/pages.md#server-side-rendering). +#### Runs on every request in development + +In development (`next dev`), `getStaticProps` will be called on every request. + +## `getStaticPaths` (Static Generation) + +If a page has dynamic routes ([documentation](https://nextjs.org/docs/routing/dynamic-routes)) and uses `getStaticProps` it needs to define a list of paths that have to be rendered to HTML at build time. + +If you export an `async` function called `getStaticPaths` from a page that uses dynamic routes, Next.js will statically pre-render all the paths specified by `getStaticPaths`. ```jsx -// This page has defined `getInitialProps` to do data fetching. -// Next.js will execute `getInitialProps` -// It will wait for the result of `getInitialProps` -// When the results comes back Next.js will render the page. -// Next.js will do this for every request that comes in. -import fetch from 'isomorphic-unfetch' - -function HomePage({ stars }) { - return
Next stars: {stars}
+export async function getStaticPaths() { + return { + paths: [ + { params: { ... } } // See the "paths" section below + ], + fallback: true or false // See the "fallback" section below + }; } +``` + +#### The `paths` key (required) -HomePage.getInitialProps = async () => { - const res = await fetch('https://api.github.com/repos/zeit/next.js') - const json = await res.json() - return { stars: json.stargazers_count } +The `paths` key determines which paths will be pre-rendered. For example, suppose that you have a page that uses dynamic routes named `pages/posts/[id].js`. If you export `getStaticPaths` from this page and return the following for `paths`: + +```js +return { + paths: [ + { params: { id: 1 } }, + { params: { id: 2 } } + ], + fallback: ... } +``` + +Then Next.js will statically generate `posts/1` and `posts/2` at build time using the page component in `pages/posts/[id].js`. + +Note that the value for each `params` must match the parameters used in the page name: + +- If the page name is `pages/posts/[postId]/[commentId]`, then `params` should contain `postId` and `commentId`. +- If the page name uses catch-all routes, for example `pages/[...slug]`, then `params` should contain `slug` which is an array. For example, if this array is `['foo', 'bar']`, then Next.js will statically generate the page at `/foo/bar`. + +#### The `fallback` key (required) + +The object returned by `getStaticPaths` must contain a boolean `fallback` key. + +#### `fallback: false` + +If `fallback` is `false`, then any paths not returned by `getStaticPaths` will result in a **404 page**. You can do this if you have a small number of paths to pre-render - so they are all statically generated during build time. It's also useful when the new pages are not added often. If you add more items to the data source and need to render the new pages, you'd need to run the build again. -export default HomePage +Here's an example which pre-renders one blog post per page called `pages/posts/[id].js`. The list of blog posts will be fetched from a CMS and returned by `getStaticPaths` . Then, for each page, it fetches the post data from a CMS using `getStaticProps`. This example is also in the **Pages** documentation. + +```jsx +// pages/posts/[id].js +import fetch from 'node-fetch' + +function Post({ post }) { + // Render post... +} + +// This function gets called at build time +export async function getStaticPaths() { + // Call an external API endpoint to get posts + const res = await fetch('https://.../posts') + const posts = await res.json() + + // Get the paths we want to pre-render based on posts + const paths = posts.map(post => `/posts/${post.id}`) + + // We'll pre-render only these paths at build time. + // { fallback: false } means other routes should 404. + return { paths, fallback: false } +} + +// This also gets called at build time +export async function getStaticProps({ params }) { + // params contains the post `id`. + // If the route is like /posts/1, then params.id is 1 + const res = await fetch(`https://.../posts/${params.id}`) + const post = await res.json() + + // Pass post data to the page via props + return { props: { post } } +} + +export default Post ``` -## Related +#### `**fallback: true**` + +If `fallback` is `true`, then the behavior of `getStaticProps` changes: + +- The paths returned from `getStaticPaths` will be rendered to HTML at build time. +- The paths that have not been generated at build time will **not** result in a 404 page. Instead, Next.js will serve a "fallback" version of the page on the first request to such a path (see "Fallback Page" below for details). +- In the background, Next.js will statically generate the requested path HTML and JSON. This includes running `getStaticProps`. +- When that's done, the browser receives the JSON for the generated path. This will be used to automatically render the page with the required props. From the user's perspective, the page will be swapped from the fallback page to the full page. +- At the same time, Next.js adds this path to the list of pre-rendered pages. Subsequent requests to the same path will serve the generated page, just like other pages pre-rendered at build time. + +#### Fallback Pages -For more information on what to do next, we recommend the following sections: +In the "fallback" version of a page: + +- The page's props will be empty. +- If you use the **router**, `router.isFallback` will be `true`. Learn more about the router **here**. + +Here's an example that uses `isFallback`: + +```jsx +// pages/posts/[id].js +import { useRouter } from 'next/router' +import fetch from 'node-fetch' + +function Post({ post }) { + const router = useRouter() + + // If the page is not yet generated, this will be displayed + // initially until getStaticProps() finishes running + if (router.isFallback) { + return
Loading...
+ } + + // Render post... +} + +// This function gets called at build time +export async function getStaticPaths() { + return { + // Only `/posts/1` and `/posts/2` are generated at build time + paths: [{ params: { id: 1 } }, { params: { id: 2 } }], + // Enable statically generating additional pages + // For example: `/posts/3` + fallback: true, + } +} + +// This also gets called at build time +export async function getStaticProps({ params }) { + // params contains the post `id`. + // If the route is like /posts/1, then params.id is 1 + const res = await fetch(`https://.../posts/${params.id}`) + const post = await res.json() + + // Pass post data to the page via props + return { props: { post } } +} + +export default Post +``` + +#### When is `fallback: true` useful? + +`fallback: true` is useful if your app has a very large number of static pages that depend on data (think: a very large e-commerce site). You want to pre-render all product pages, but then your builds would take forever. + +Instead, you may statically generate a small subset of pages and use `fallback: true` for the rest. When someone requests a page that's not generated yet, the user will see the page with a loading indicator. Shortly after, `getStaticProps` finishes and the page will be rendered with the requested data. From now on, everyone who requests the same page will get the statically pre-rendered page. + +This ensures that users always have a fast experience while preserving fast builds and the benefits of Static Generation. + +### When should I use `getStaticPaths`? + +You should use `getStaticPaths` if you're statically pre-rendering pages that use dynamic routes. + +### Technical Details + +#### Use together with `getStaticProps` + +When you use `getStaticProps` on a page with dynamic route parameters, you must use `getStaticPaths`. + +You cannot use `getStaticPaths` with `getServerSideProps`. + +#### Only runs at build time on server-side + +`getStaticPaths` only runs at build time on server-side. + +#### Only allowed in a page + +`getStaticPaths` can only be exported from a **page**. You can't export it from non-page files. + +Also, you must use `export` — it will **not** work if you add `getStaticPaths` as a property of the page component. + +#### Runs on every request in development + +In development (`next dev`), `getStaticPaths` will be called on every request. + +## `getServerSideProps` (Server-side Rendering) + +If you export an `async` function called `getServerSideProps` from a page, Next.js will pre-render this page on each request using the data returned by `getServerSideProps`. + +```js +export async function getServerSideProps(context) { + return { + props: {}, // will be passed to the page component as props + } +} +``` + +The `context` parameter is an object containing the following keys: + +- `params`: If this page uses a dynamic route, `params` contains the route parameters. If the page name is `[id].js` , then `params` will look like `{ id: ... }`. To learn more, take a look at the [Dynamic Routing documentation](/docs/routing/dynamic-routes.md). +- `req`: [The HTTP request object](https://nodejs.org/api/http.html#http_class_http_incomingmessage). +- `res`: [The HTTP response object](https://nodejs.org/api/http.html#http_class_http_serverresponse). +- `query`: The query string. + +### Simple Example + +Here's an example which uses `getServerSideProps` to fetch data at request time and pre-renders it. This example is also in the [Pages](/docs/basic-features/pages.md) documentation. + +```jsx +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 } } +} + +export default Page +``` + +### When should I use `getServerSideProps`? + +You should use `getServerSideProps` only if you need to pre-render a page whose data must be fetched on the request time. Time to first byte (TTFB) will be slower than `getStaticProps` because the server must compute the result on every request, and the result cannot be cached by CDN. + +If you don't need to pre-render the data, then you should consider fetching data on the client side. [Click here to learn more](#fetching-data-on-the-client-side). + +### Technical Details + +#### Only runs on server-side + +`getServerSideProps` only runs on server-side and never runs on the browser. If a page uses `getServerSideProps` , then: + +- When you request this page directly, `getServerSideProps` runs at the request time, and this page will be pre-rendered with the returned props. +- When you request this page on client-side page transitions, the browser sends an API request to Next.js, which runs `getServerSideProps`. It'll return a JSON that contains the result of running `getServerSideProps`, and the JSON will be used to render the page. All this work will be handled automatically by Next.js, so you don't need to do anything extra as long as you have `getServerSideProps` defined. + +#### Only allowed in a page + +`getServerSideProps` can only be exported from a **page**. You can't export it from non-page files. + +Also, you must use `export` — it will **not** work if you add `getServerSideProps` as a property of the page component. + +## Fetching data on the client side + +If your page contains frequently updating data, and you don't need to pre-render the data, you can fetch the data on the client side. Here's how it works: + +- First, immediately show the page without data. Parts of the page can be pre-rendered using Static Generation (without data). You can show loading states for missing data. +- Then, fetch the data on the client side and display it when ready. + +This approach works well for user dashboard pages, for example. Because a dashboard is a private, user-specific page, SEO is irrelevant and the page doesn't need to be pre-rendered. And the data is frequently updated, which requires request-time data fetching. + +### SWR + +ZEIT, the team behind Next.js, has created a React hook for data fetching called [**SWR**](https://swr.now.sh/). We highly recommend it If you're fetching data on the client side. It handles caching and revalidation, focus tracking, refetching on interval, and more. And the usage is very simple: + + import useSWR from 'swr' + + function Profile () { + const { data, error } = useSWR('/api/user', fetch) + + if (error) return
failed to load
+ if (!data) return
loading...
+ return
hello {data.name}!
+ } + +[Check out the SWR documentation to learn more](https://swr.now.sh/). + +## Learn More + +We recommend you to read the following sections next: + +
diff --git a/docs/basic-features/pages.md b/docs/basic-features/pages.md index a4202b14b266e8f..fb180e12501fbb6 100644 --- a/docs/basic-features/pages.md +++ b/docs/basic-features/pages.md @@ -22,7 +22,7 @@ export default About Next.js supports pages with dynamic routes. For example, if you create a file called `pages/posts/[id].js`, then it will be accessible at `posts/1`, `posts/2`, etc. -> To learn more about dynamic routing, check the [routing documentation](/docs/routing/dynamic-routes.md). +> To learn more about dynamic routing, check the [Routing documentation](/docs/routing/dynamic-routes.md). ## Pre-rendering @@ -124,7 +124,7 @@ To learn more about how `getStaticProps` works, check out the [Data Fetching doc Next.js allows you to create pages with **dynamic routes**. For example, you can create a file called `pages/posts/[id].js` to show a single blog post based on `id`. This will allow you to show a blog post with `id: 1` when you access `posts/1`. -> To learn more about dynamic routing, check the [routing documentation](/docs/routing/dynamic-routes.md). +> To learn more about dynamic routing, check the [Dynamic Routing documentation](/docs/routing/dynamic-routes.md). However, which `id` you want to pre-render at build time might depend on external data. @@ -198,7 +198,7 @@ On the other hand, Static Generation is **not** a good idea if you cannot pre-re In cases like this, you can do one of the following: -- Use Static Generation with **Client-side Rendering:** You can skip pre-rendering some parts of a page and then use client-side JavaScript to populate them. To learn more about this approach, check out the [Data Fetching documentation](/docs/basic-features/data-fetching#fetching-data-on-the-client-side.md). +- Use Static Generation with **Client-side Rendering:** You can skip pre-rendering some parts of a page and then use client-side JavaScript to populate them. To learn more about this approach, check out the [Data Fetching documentation](/docs/basic-features/data-fetching.md#fetching-data-on-the-client-side). - Use **Server-Side Rendering:** Next.js pre-renders a page on each request. It will be slower because the page cannot be cached by a CDN, but the pre-rendered page will always be up-to-date. We'll talk about this approach below. ## Server-side Rendering From 34f790054204a39887796b70f580a861f931f174 Mon Sep 17 00:00:00 2001 From: Shu Uesugi Date: Thu, 5 Mar 2020 00:20:28 -0800 Subject: [PATCH 03/21] Format code --- docs/basic-features/data-fetching.md | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/docs/basic-features/data-fetching.md b/docs/basic-features/data-fetching.md index 68df39f57f5a14a..2065798e7f8bfa4 100644 --- a/docs/basic-features/data-fetching.md +++ b/docs/basic-features/data-fetching.md @@ -362,15 +362,17 @@ This approach works well for user dashboard pages, for example. Because a dashbo ZEIT, the team behind Next.js, has created a React hook for data fetching called [**SWR**](https://swr.now.sh/). We highly recommend it If you're fetching data on the client side. It handles caching and revalidation, focus tracking, refetching on interval, and more. And the usage is very simple: - import useSWR from 'swr' +```jsx +import useSWR from 'swr' - function Profile () { - const { data, error } = useSWR('/api/user', fetch) +function Profile() { + const { data, error } = useSWR('/api/user', fetch) - if (error) return
failed to load
- if (!data) return
loading...
- return
hello {data.name}!
- } + if (error) return
failed to load
+ if (!data) return
loading...
+ return
hello {data.name}!
+} +``` [Check out the SWR documentation to learn more](https://swr.now.sh/). From 6455e11fcc1aef2f97a4d6451fffc9036abdb902 Mon Sep 17 00:00:00 2001 From: Shu Uesugi Date: Thu, 5 Mar 2020 00:22:16 -0800 Subject: [PATCH 04/21] Link directly to nextjs.org --- docs/basic-features/data-fetching.md | 2 +- docs/basic-features/pages.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/basic-features/data-fetching.md b/docs/basic-features/data-fetching.md index 2065798e7f8bfa4..e416319eed746b0 100644 --- a/docs/basic-features/data-fetching.md +++ b/docs/basic-features/data-fetching.md @@ -4,7 +4,7 @@ description: Next.js can handle data fetching in multiple ways for server-render # Data Fetching -> This document is for Next.js versions 9.3 and up. If you're using older versions of Next.js, refer to our [previous documentation](/docs/tag/v9.2.2/basic-features/data-fetching). +> This document is for Next.js versions 9.3 and up. If you're using older versions of Next.js, refer to our [previous documentation](https://nextjs.org/docs/tag/v9.2.2/basic-features/data-fetching). In the [Pages documentation](/docs/basic-features/pages.md), we've explained that Next.js has two forms of pre-rendering: **Static Generation** and **Server-side Rendering**. In this page, we'll talk in depths about data fetching strategies for each case. We recommend you to [read through the Pages documentation](<(/docs/basic-features/pages.md)>) first if you haven't done so. diff --git a/docs/basic-features/pages.md b/docs/basic-features/pages.md index fb180e12501fbb6..83727f87561a7fb 100644 --- a/docs/basic-features/pages.md +++ b/docs/basic-features/pages.md @@ -4,7 +4,7 @@ description: Next.js pages are React Components exported in a file in the pages # Pages -> This document is for Next.js versions 9.3 and up. If you're using older versions of Next.js, refer to our [previous documentation](/docs/tag/v9.2.2/basic-features/pages). +> This document is for Next.js versions 9.3 and up. If you're using older versions of Next.js, refer to our [previous documentation](https://nextjs.org/docs/tag/v9.2.2/basic-features/pages). In Next.js, a **page** is a [React Component](https://reactjs.org/docs/components-and-props.html) exported from a `.js`, `.ts`, or `.tsx` file in the `pages` directory. Each page is associated with a route based on its file name. From 2e161bca13a0b75d3a5c8ae9df68d49bbeea023d Mon Sep 17 00:00:00 2001 From: Shu Uesugi Date: Thu, 5 Mar 2020 00:30:35 -0800 Subject: [PATCH 05/21] Fix link --- docs/basic-features/data-fetching.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/basic-features/data-fetching.md b/docs/basic-features/data-fetching.md index e416319eed746b0..24db04751049d9e 100644 --- a/docs/basic-features/data-fetching.md +++ b/docs/basic-features/data-fetching.md @@ -6,7 +6,7 @@ description: Next.js can handle data fetching in multiple ways for server-render > This document is for Next.js versions 9.3 and up. If you're using older versions of Next.js, refer to our [previous documentation](https://nextjs.org/docs/tag/v9.2.2/basic-features/data-fetching). -In the [Pages documentation](/docs/basic-features/pages.md), we've explained that Next.js has two forms of pre-rendering: **Static Generation** and **Server-side Rendering**. In this page, we'll talk in depths about data fetching strategies for each case. We recommend you to [read through the Pages documentation](<(/docs/basic-features/pages.md)>) first if you haven't done so. +In the [Pages documentation](/docs/basic-features/pages.md), we've explained that Next.js has two forms of pre-rendering: **Static Generation** and **Server-side Rendering**. In this page, we'll talk in depths about data fetching strategies for each case. We recommend you to [read through the Pages documentation](/docs/basic-features/pages.md) first if you haven't done so. We'll talk about the three special Next.js functions you can use to fetch data for pre-rendering: From 29d75e14dbf215ff7078ee8c4b60d7310e8dae02 Mon Sep 17 00:00:00 2001 From: Shu Uesugi Date: Thu, 5 Mar 2020 00:31:50 -0800 Subject: [PATCH 06/21] Add .md --- docs/basic-features/data-fetching.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/basic-features/data-fetching.md b/docs/basic-features/data-fetching.md index 24db04751049d9e..d0d3cf61f598195 100644 --- a/docs/basic-features/data-fetching.md +++ b/docs/basic-features/data-fetching.md @@ -94,7 +94,7 @@ Note that `getStaticProps` runs only on the server-side. It will never be run on When a page with `getStaticProps` is pre-rendered at build time, in addition to the page HTML file, Next.js generates a JSON file holding the result of running `getStaticProps`. -This JSON file will be used in client-side routing through `next/link` ([documentation](/docs/api-reference/next/link)) or `next/router` ([documentation](/docs/api-reference/next/router)). When you navigate to a page that's pre-rendered using `getStaticProps`, Next.js fetches this JSON file (pre-computed at build time) and uses it as the props for the page component. This means that client-side page transitions will **not** call `getStaticProps` as only the exported JSON is used. +This JSON file will be used in client-side routing through `next/link` ([documentation](/docs/api-reference/next/link.md)) or `next/router` ([documentation](/docs/api-reference/next/router.md)). When you navigate to a page that's pre-rendered using `getStaticProps`, Next.js fetches this JSON file (pre-computed at build time) and uses it as the props for the page component. This means that client-side page transitions will **not** call `getStaticProps` as only the exported JSON is used. #### Only allowed in a page From 3e0e301351c604fb9f6837159057bd7c6e4a28f0 Mon Sep 17 00:00:00 2001 From: Shu Uesugi Date: Thu, 5 Mar 2020 00:34:32 -0800 Subject: [PATCH 07/21] Add .md --- docs/basic-features/pages.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/basic-features/pages.md b/docs/basic-features/pages.md index 83727f87561a7fb..3cce4d717dc71c0 100644 --- a/docs/basic-features/pages.md +++ b/docs/basic-features/pages.md @@ -41,7 +41,7 @@ Importantly, Next.js lets you **choose** which pre-rendering form you'd like to We **recommend** using **Static Generation** over Server-side Rendering for performance reasons. Statically generated pages can be cached by CDN to boost performance. However, in some cases, Server-side Rendering might be the only option. -Finally, you can always use **Client-side Rendering** 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](/docs/basic-features/data-fetching#fetching-data-on-the-client-side) documentation. +Finally, you can always use **Client-side Rendering** 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](/docs/basic-features/data-fetching.md#fetching-data-on-the-client-side) documentation. ## Static Generation (Recommended) From be23d9a99b1bbc49b32769a499716a494c6dfa9c Mon Sep 17 00:00:00 2001 From: Shu Uesugi Date: Thu, 5 Mar 2020 00:35:56 -0800 Subject: [PATCH 08/21] Fix hashes --- docs/basic-features/pages.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/basic-features/pages.md b/docs/basic-features/pages.md index 3cce4d717dc71c0..2fffcf3fd9d2406 100644 --- a/docs/basic-features/pages.md +++ b/docs/basic-features/pages.md @@ -118,7 +118,7 @@ export async function getStaticProps() { export default Blog ``` -To learn more about how `getStaticProps` works, check out the [Data Fetching documentation](/docs/basic-features/data-fetching#getstaticprops). +To learn more about how `getStaticProps` works, check out the [Data Fetching documentation](/docs/basic-features/data-fetching.md#getstaticprops-static-generation). #### Scenario 2: Your page paths depend on external data @@ -179,7 +179,7 @@ export async function getStaticProps({ params }) { export default Post ``` -To learn more about how `getStaticPaths` works, check out the [Data Fetching documentation](/docs/basic-features/data-fetching.md#getstaticpaths). +To learn more about how `getStaticPaths` works, check out the [Data Fetching documentation](/docs/basic-features/data-fetching.md#getstaticpaths-static-generation). ### When should I use Static Generation? @@ -233,7 +233,7 @@ export default Page As you can see, `getServerSideProps` is similar to `getStaticProps`, but the difference is that `getServerSideProps` is run on every request instead of on build time. -To learn more about how `getServerSideProps` works, check out our [Data Fetching documentation](/docs/basic-features/data-fetching.md#getserversideprops) +To learn more about how `getServerSideProps` works, check out our [Data Fetching documentation](/docs/basic-features/data-fetching.md#getserversideprops-server-side-rendering) ## Summary From f523bff142ca39131b41c0e5913d82f70413d366 Mon Sep 17 00:00:00 2001 From: Shu Uesugi Date: Thu, 5 Mar 2020 00:39:57 -0800 Subject: [PATCH 09/21] Update pages.md --- docs/basic-features/pages.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/basic-features/pages.md b/docs/basic-features/pages.md index 2fffcf3fd9d2406..ec271db9df184c6 100644 --- a/docs/basic-features/pages.md +++ b/docs/basic-features/pages.md @@ -41,7 +41,7 @@ Importantly, Next.js lets you **choose** which pre-rendering form you'd like to We **recommend** using **Static Generation** over Server-side Rendering for performance reasons. Statically generated pages can be cached by CDN to boost performance. However, in some cases, Server-side Rendering might be the only option. -Finally, you can always use **Client-side Rendering** 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](/docs/basic-features/data-fetching.md#fetching-data-on-the-client-side) documentation. +Finally, you can always use **Client-side Rendering** 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](/docs/basic-features/data-fetching.md#fetching-data-on-the-client-side) documentation. ## Static Generation (Recommended) From f2ec99497b108b81e974fc7396643ca57c71564b Mon Sep 17 00:00:00 2001 From: Shu Uesugi Date: Thu, 5 Mar 2020 00:40:46 -0800 Subject: [PATCH 10/21] Wordsmith --- docs/basic-features/pages.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/basic-features/pages.md b/docs/basic-features/pages.md index ec271db9df184c6..b088d1c6f395854 100644 --- a/docs/basic-features/pages.md +++ b/docs/basic-features/pages.md @@ -22,7 +22,7 @@ export default About Next.js supports pages with dynamic routes. For example, if you create a file called `pages/posts/[id].js`, then it will be accessible at `posts/1`, `posts/2`, etc. -> To learn more about dynamic routing, check the [Routing documentation](/docs/routing/dynamic-routes.md). +> To learn more about dynamic routing, check the [Dynamic Routing documentation](/docs/routing/dynamic-routes.md). ## Pre-rendering From 712f42bc53561941d7506fe9110bbbefc36349be Mon Sep 17 00:00:00 2001 From: Shu Uesugi Date: Thu, 5 Mar 2020 00:45:00 -0800 Subject: [PATCH 11/21] Fix link --- docs/basic-features/data-fetching.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/basic-features/data-fetching.md b/docs/basic-features/data-fetching.md index d0d3cf61f598195..3f2229584cde251 100644 --- a/docs/basic-features/data-fetching.md +++ b/docs/basic-features/data-fetching.md @@ -110,7 +110,7 @@ In development (`next dev`), `getStaticProps` will be called on every request. ## `getStaticPaths` (Static Generation) -If a page has dynamic routes ([documentation](https://nextjs.org/docs/routing/dynamic-routes)) and uses `getStaticProps` it needs to define a list of paths that have to be rendered to HTML at build time. +If a page has dynamic routes ([documentation](/docs/routing/dynamic-routes.md)) and uses `getStaticProps` it needs to define a list of paths that have to be rendered to HTML at build time. If you export an `async` function called `getStaticPaths` from a page that uses dynamic routes, Next.js will statically pre-render all the paths specified by `getStaticPaths`. From 967580ccbe2a37808b5d53a187d6e230d10c9aec Mon Sep 17 00:00:00 2001 From: Shu Uesugi Date: Thu, 5 Mar 2020 00:45:42 -0800 Subject: [PATCH 12/21] Fix heading --- docs/basic-features/data-fetching.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/basic-features/data-fetching.md b/docs/basic-features/data-fetching.md index 3f2229584cde251..b2f99c724d31b20 100644 --- a/docs/basic-features/data-fetching.md +++ b/docs/basic-features/data-fetching.md @@ -192,7 +192,7 @@ export async function getStaticProps({ params }) { export default Post ``` -#### `**fallback: true**` +#### `fallback: true` If `fallback` is `true`, then the behavior of `getStaticProps` changes: From a0f79aa751e420cee26d62f3f6f97da6c0450032 Mon Sep 17 00:00:00 2001 From: Shu Uesugi Date: Thu, 5 Mar 2020 00:50:56 -0800 Subject: [PATCH 13/21] Capitalization --- docs/basic-features/data-fetching.md | 16 ++++++++-------- docs/basic-features/pages.md | 4 ++-- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/docs/basic-features/data-fetching.md b/docs/basic-features/data-fetching.md index b2f99c724d31b20..a746a511af4770e 100644 --- a/docs/basic-features/data-fetching.md +++ b/docs/basic-features/data-fetching.md @@ -2,7 +2,7 @@ description: Next.js can handle data fetching in multiple ways for server-rendered and static pages. Learn how it works here. --- -# Data Fetching +# Data fetching > This document is for Next.js versions 9.3 and up. If you're using older versions of Next.js, refer to our [previous documentation](https://nextjs.org/docs/tag/v9.2.2/basic-features/data-fetching). @@ -53,7 +53,7 @@ function Blog({ posts }) { // This function gets called at build time on server-side. // It won't be called on client-side, so you can even do -// direct database queries. See the "Technical Details" section. +// direct database queries. See the "Technical details" section. export async function getStaticProps() { // Call an external API endpoint to get posts. const res = await fetch('https://.../posts') @@ -80,7 +80,7 @@ You should use `getStaticProps` if: - The data can be publicly cached (not user-specific). - The page must be pre-rendered (for SEO) and be very fast — `getStaticProps` generates HTML and JSON files, both of which can be cached by a CDN for performance. -### Technical Details +### Technical details #### Only runs at build time @@ -202,7 +202,7 @@ If `fallback` is `true`, then the behavior of `getStaticProps` changes: - When that's done, the browser receives the JSON for the generated path. This will be used to automatically render the page with the required props. From the user's perspective, the page will be swapped from the fallback page to the full page. - At the same time, Next.js adds this path to the list of pre-rendered pages. Subsequent requests to the same path will serve the generated page, just like other pages pre-rendered at build time. -#### Fallback Pages +#### Fallback pages In the "fallback" version of a page: @@ -265,7 +265,7 @@ This ensures that users always have a fast experience while preserving fast buil You should use `getStaticPaths` if you're statically pre-rendering pages that use dynamic routes. -### Technical Details +### Technical details #### Use together with `getStaticProps` @@ -306,7 +306,7 @@ The `context` parameter is an object containing the following keys: - `res`: [The HTTP response object](https://nodejs.org/api/http.html#http_class_http_serverresponse). - `query`: The query string. -### Simple Example +### Simple example Here's an example which uses `getServerSideProps` to fetch data at request time and pre-renders it. This example is also in the [Pages](/docs/basic-features/pages.md) documentation. @@ -334,7 +334,7 @@ You should use `getServerSideProps` only if you need to pre-render a page whose If you don't need to pre-render the data, then you should consider fetching data on the client side. [Click here to learn more](#fetching-data-on-the-client-side). -### Technical Details +### Technical details #### Only runs on server-side @@ -376,7 +376,7 @@ function Profile() { [Check out the SWR documentation to learn more](https://swr.now.sh/). -## Learn More +## Learn more We recommend you to read the following sections next: diff --git a/docs/basic-features/pages.md b/docs/basic-features/pages.md index b088d1c6f395854..9b59980bf0d604f 100644 --- a/docs/basic-features/pages.md +++ b/docs/basic-features/pages.md @@ -30,7 +30,7 @@ By default, Next.js **pre-renders** every page. This means that Next.js generate 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_.) -### Two Forms of Pre-rendering +### Two forms of Pre-rendering Next.js has two forms of pre-rendering: **Static Generation** and **Server-side Rendering**. The difference is in **when** it generates the HTML for a page. @@ -242,7 +242,7 @@ We've discussed two forms of pre-rendering for Next.js. - **Static Generation (Recommended):** The HTML is generated at **build time** and will be reused on each request. To make a page use Static Generation, just 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. -## Learn More +## Learn more We recommend you to read the following sections next: From 52f23fb4ce8606113c7a3412a1dbc6cd8889fc30 Mon Sep 17 00:00:00 2001 From: Shu Uesugi Date: Thu, 5 Mar 2020 00:53:58 -0800 Subject: [PATCH 14/21] Link to pages --- docs/basic-features/data-fetching.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/basic-features/data-fetching.md b/docs/basic-features/data-fetching.md index a746a511af4770e..0acde220d534835 100644 --- a/docs/basic-features/data-fetching.md +++ b/docs/basic-features/data-fetching.md @@ -154,7 +154,7 @@ The object returned by `getStaticPaths` must contain a boolean `fallback` key. If `fallback` is `false`, then any paths not returned by `getStaticPaths` will result in a **404 page**. You can do this if you have a small number of paths to pre-render - so they are all statically generated during build time. It's also useful when the new pages are not added often. If you add more items to the data source and need to render the new pages, you'd need to run the build again. -Here's an example which pre-renders one blog post per page called `pages/posts/[id].js`. The list of blog posts will be fetched from a CMS and returned by `getStaticPaths` . Then, for each page, it fetches the post data from a CMS using `getStaticProps`. This example is also in the **Pages** documentation. +Here's an example which pre-renders one blog post per page called `pages/posts/[id].js`. The list of blog posts will be fetched from a CMS and returned by `getStaticPaths` . Then, for each page, it fetches the post data from a CMS using `getStaticProps`. This example is also in the [Pages documentation](/docs/basic-features/pages.md). ```jsx // pages/posts/[id].js From ff75c0f40478ce0b194e368383dcf5b197f9cd5d Mon Sep 17 00:00:00 2001 From: Shu Uesugi Date: Thu, 5 Mar 2020 00:54:59 -0800 Subject: [PATCH 15/21] Add router link --- docs/basic-features/data-fetching.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/basic-features/data-fetching.md b/docs/basic-features/data-fetching.md index 0acde220d534835..c9a9469f38b6e7e 100644 --- a/docs/basic-features/data-fetching.md +++ b/docs/basic-features/data-fetching.md @@ -207,7 +207,7 @@ If `fallback` is `true`, then the behavior of `getStaticProps` changes: In the "fallback" version of a page: - The page's props will be empty. -- If you use the **router**, `router.isFallback` will be `true`. Learn more about the router **here**. +- If you use the **router**, `router.isFallback` will be `true`. Learn more about the router [here](/docs/api-reference/next/router.md)). Here's an example that uses `isFallback`: From 62252e8a6fe6155fcdcd8e9ea2a8826139d41cf2 Mon Sep 17 00:00:00 2001 From: Shu Uesugi Date: Thu, 5 Mar 2020 00:55:24 -0800 Subject: [PATCH 16/21] Fix parens --- docs/basic-features/data-fetching.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/basic-features/data-fetching.md b/docs/basic-features/data-fetching.md index c9a9469f38b6e7e..b5ab05ccc239aad 100644 --- a/docs/basic-features/data-fetching.md +++ b/docs/basic-features/data-fetching.md @@ -207,7 +207,7 @@ If `fallback` is `true`, then the behavior of `getStaticProps` changes: In the "fallback" version of a page: - The page's props will be empty. -- If you use the **router**, `router.isFallback` will be `true`. Learn more about the router [here](/docs/api-reference/next/router.md)). +- If you use the [router](/docs/api-reference/next/router.md)), `router.isFallback` will be `true`. Learn more about the router [here](/docs/api-reference/next/router.md). Here's an example that uses `isFallback`: From 018d0398d741203d24c6d340518ef4d5717456ec Mon Sep 17 00:00:00 2001 From: Shu Uesugi Date: Thu, 5 Mar 2020 00:56:35 -0800 Subject: [PATCH 17/21] Make links consistent --- docs/basic-features/data-fetching.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/basic-features/data-fetching.md b/docs/basic-features/data-fetching.md index b5ab05ccc239aad..38e8c4f6304c2b8 100644 --- a/docs/basic-features/data-fetching.md +++ b/docs/basic-features/data-fetching.md @@ -308,7 +308,7 @@ The `context` parameter is an object containing the following keys: ### Simple example -Here's an example which uses `getServerSideProps` to fetch data at request time and pre-renders it. This example is also in the [Pages](/docs/basic-features/pages.md) documentation. +Here's an example which uses `getServerSideProps` to fetch data at request time and pre-renders it. This example is also in the [Pages documentation](/docs/basic-features/pages.md). ```jsx function Page({ data }) { From 03a10940078089bc5560841954b2c243988acf84 Mon Sep 17 00:00:00 2001 From: Shu Uesugi Date: Thu, 5 Mar 2020 00:57:18 -0800 Subject: [PATCH 18/21] Use commas --- docs/basic-features/data-fetching.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/basic-features/data-fetching.md b/docs/basic-features/data-fetching.md index 38e8c4f6304c2b8..bd44e8239aba4c9 100644 --- a/docs/basic-features/data-fetching.md +++ b/docs/basic-features/data-fetching.md @@ -360,7 +360,7 @@ This approach works well for user dashboard pages, for example. Because a dashbo ### SWR -ZEIT, the team behind Next.js, has created a React hook for data fetching called [**SWR**](https://swr.now.sh/). We highly recommend it If you're fetching data on the client side. It handles caching and revalidation, focus tracking, refetching on interval, and more. And the usage is very simple: +ZEIT, the team behind Next.js, has created a React hook for data fetching called [**SWR**](https://swr.now.sh/). We highly recommend it If you're fetching data on the client side. It handles caching, revalidation, focus tracking, refetching on interval, and more. And the usage is very simple: ```jsx import useSWR from 'swr' From d538f15f39c617f8c31b13db63d7734a39e442fb Mon Sep 17 00:00:00 2001 From: Shu Uesugi Date: Thu, 5 Mar 2020 00:59:46 -0800 Subject: [PATCH 19/21] Link to fallback pages --- docs/basic-features/data-fetching.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/basic-features/data-fetching.md b/docs/basic-features/data-fetching.md index bd44e8239aba4c9..c7c1dc100df989c 100644 --- a/docs/basic-features/data-fetching.md +++ b/docs/basic-features/data-fetching.md @@ -197,7 +197,7 @@ export default Post If `fallback` is `true`, then the behavior of `getStaticProps` changes: - The paths returned from `getStaticPaths` will be rendered to HTML at build time. -- The paths that have not been generated at build time will **not** result in a 404 page. Instead, Next.js will serve a "fallback" version of the page on the first request to such a path (see "Fallback Page" below for details). +- The paths that have not been generated at build time will **not** result in a 404 page. Instead, Next.js will serve a "fallback" version of the page on the first request to such a path (see ["Fallback pages"](#fallback-pages) below for details). - In the background, Next.js will statically generate the requested path HTML and JSON. This includes running `getStaticProps`. - When that's done, the browser receives the JSON for the generated path. This will be used to automatically render the page with the required props. From the user's perspective, the page will be swapped from the fallback page to the full page. - At the same time, Next.js adds this path to the list of pre-rendered pages. Subsequent requests to the same path will serve the generated page, just like other pages pre-rendered at build time. From 4b157fc6672b18d964107d8dbe5ec7fbfe48e624 Mon Sep 17 00:00:00 2001 From: Tim Neutkens Date: Thu, 5 Mar 2020 15:15:02 +0100 Subject: [PATCH 20/21] Update data-fetching.md --- docs/basic-features/data-fetching.md | 77 ++++++++++++++-------------- 1 file changed, 38 insertions(+), 39 deletions(-) diff --git a/docs/basic-features/data-fetching.md b/docs/basic-features/data-fetching.md index c7c1dc100df989c..b56da9ac21ab4e7 100644 --- a/docs/basic-features/data-fetching.md +++ b/docs/basic-features/data-fetching.md @@ -4,17 +4,17 @@ description: Next.js can handle data fetching in multiple ways for server-render # Data fetching -> This document is for Next.js versions 9.3 and up. If you're using older versions of Next.js, refer to our [previous documentation](https://nextjs.org/docs/tag/v9.2.2/basic-features/data-fetching). +> This document is for Next.js versions 9.3 and up. If you’re using older versions of Next.js, refer to our [previous documentation](https://nextjs.org/docs/tag/v9.2.2/basic-features/data-fetching). -In the [Pages documentation](/docs/basic-features/pages.md), we've explained that Next.js has two forms of pre-rendering: **Static Generation** and **Server-side Rendering**. In this page, we'll talk in depths about data fetching strategies for each case. We recommend you to [read through the Pages documentation](/docs/basic-features/pages.md) first if you haven't done so. +In the [Pages documentation](/docs/basic-features/pages.md), we’ve explained that Next.js has two forms of pre-rendering: **Static Generation** and **Server-side Rendering**. In this page, we’ll talk in depths about data fetching strategies for each case. We recommend you to [read through the Pages documentation](/docs/basic-features/pages.md) first if you haven’t done so. -We'll talk about the three special Next.js functions you can use to fetch data for pre-rendering: +We’ll talk about the three special Next.js functions you can use to fetch data for pre-rendering: - `getStaticProps` (Static Generation): Fetch data at **build time**. - `getStaticPaths` (Static Generation): Specify [dynamic routes](/docs/routing/dynamic-routes.md) to pre-render based on data. - `getServerSideProps` (Server-side Rendering): Fetch data on **each request**. -In addition, we'll talk briefly about how to do fetch data on the client side. +In addition, we’ll talk briefly about how to do fetch data on the client side. ## `getStaticProps` (Static Generation) @@ -30,11 +30,11 @@ export async function getStaticProps(context) { The `context` parameter is an object containing the following keys: -- `params`: `params` contains the route parameters for pages using dynamic routes. For example, if the page name is `[id].js` , then `params` will look like `{ id: ... }`. To learn more, take a look at the [Dynamic Routing documentation](/docs/routing/dynamic-routes.md). You should use this together with `getStaticPaths`, which we'll explain later. +- `params`: `params` contains the route parameters for pages using dynamic routes. For example, if the page name is `[id].js` , then `params` will look like `{ id: ... }`. To learn more, take a look at the [Dynamic Routing documentation](/docs/routing/dynamic-routes.md). You should use this together with `getStaticPaths`, which we’ll explain later. ### Simple Example -Here's an example which uses `getStaticProps` to fetch a list of blog posts from a CMS (content management system). This example is also in the [Pages documentation](/docs/basic-features/pages.md). +Here’s an example which uses `getStaticProps` to fetch a list of blog posts from a CMS (content management system). This example is also in the [Pages documentation](/docs/basic-features/pages.md). ```jsx // You can use any data fetching library @@ -75,7 +75,7 @@ export default Blog You should use `getStaticProps` if: -- The data required to render the page is available at build time ahead of a user's request. +- The data required to render the page is available at build time ahead of a user’s request. - The data comes from headless CMS. - The data can be publicly cached (not user-specific). - The page must be pre-rendered (for SEO) and be very fast — `getStaticProps` generates HTML and JSON files, both of which can be cached by a CDN for performance. @@ -84,25 +84,25 @@ You should use `getStaticProps` if: #### Only runs at build time -Because `getStaticProps` runs at build time, it does **not** receive data that's only available during request time, such as query parameters or HTTP headers as it generates static HTML. +Because `getStaticProps` runs at build time, it does **not** receive data that’s only available during request time, such as query parameters or HTTP headers as it generates static HTML. #### Write server-side code directly -Note that `getStaticProps` runs only on the server-side. It will never be run on the client-side. It won't even be included in the JS bundle for the browser. That means you can write code such as direct database queries without them being sent to browsers. You should not fetch an **API route** from `getStaticProps` — instead, you can write the server-side code directly in `getStaticProps`. +Note that `getStaticProps` runs only on the server-side. It will never be run on the client-side. It won’t even be included in the JS bundle for the browser. That means you can write code such as direct database queries without them being sent to browsers. You should not fetch an **API route** from `getStaticProps` — instead, you can write the server-side code directly in `getStaticProps`. #### Statically Generates both HTML and JSON When a page with `getStaticProps` is pre-rendered at build time, in addition to the page HTML file, Next.js generates a JSON file holding the result of running `getStaticProps`. -This JSON file will be used in client-side routing through `next/link` ([documentation](/docs/api-reference/next/link.md)) or `next/router` ([documentation](/docs/api-reference/next/router.md)). When you navigate to a page that's pre-rendered using `getStaticProps`, Next.js fetches this JSON file (pre-computed at build time) and uses it as the props for the page component. This means that client-side page transitions will **not** call `getStaticProps` as only the exported JSON is used. +This JSON file will be used in client-side routing through `next/link` ([documentation](/docs/api-reference/next/link.md)) or `next/router` ([documentation](/docs/api-reference/next/router.md)). When you navigate to a page that’s pre-rendered using `getStaticProps`, Next.js fetches this JSON file (pre-computed at build time) and uses it as the props for the page component. This means that client-side page transitions will **not** call `getStaticProps` as only the exported JSON is used. #### Only allowed in a page -`getStaticProps` can only be exported from a **page**. You can't export it from non-page files. +`getStaticProps` can only be exported from a **page**. You can’t export it from non-page files. One of the reasons for this restriction is that React needs to have all the required data before the page is rendered. -Also, you must use `export` — it will **not** work if you add `getStaticProps` as a property of the page component. +Also, you must use `export async function getStaticProps() {}` — it will **not** work if you add `getStaticProps` as a property of the page component. #### Runs on every request in development @@ -152,9 +152,9 @@ The object returned by `getStaticPaths` must contain a boolean `fallback` key. #### `fallback: false` -If `fallback` is `false`, then any paths not returned by `getStaticPaths` will result in a **404 page**. You can do this if you have a small number of paths to pre-render - so they are all statically generated during build time. It's also useful when the new pages are not added often. If you add more items to the data source and need to render the new pages, you'd need to run the build again. +If `fallback` is `false`, then any paths not returned by `getStaticPaths` will result in a **404 page**. You can do this if you have a small number of paths to pre-render - so they are all statically generated during build time. It’s also useful when the new pages are not added often. If you add more items to the data source and need to render the new pages, you’d need to run the build again. -Here's an example which pre-renders one blog post per page called `pages/posts/[id].js`. The list of blog posts will be fetched from a CMS and returned by `getStaticPaths` . Then, for each page, it fetches the post data from a CMS using `getStaticProps`. This example is also in the [Pages documentation](/docs/basic-features/pages.md). +Here’s an example which pre-renders one blog post per page called `pages/posts/[id].js`. The list of blog posts will be fetched from a CMS and returned by `getStaticPaths` . Then, for each page, it fetches the post data from a CMS using `getStaticProps`. This example is also in the [Pages documentation](/docs/basic-features/pages.md). ```jsx // pages/posts/[id].js @@ -197,19 +197,19 @@ export default Post If `fallback` is `true`, then the behavior of `getStaticProps` changes: - The paths returned from `getStaticPaths` will be rendered to HTML at build time. -- The paths that have not been generated at build time will **not** result in a 404 page. Instead, Next.js will serve a "fallback" version of the page on the first request to such a path (see ["Fallback pages"](#fallback-pages) below for details). +- The paths that have not been generated at build time will **not** result in a 404 page. Instead, Next.js will serve a “fallback” version of the page on the first request to such a path (see [“Fallback pages”](#fallback-pages) below for details). - In the background, Next.js will statically generate the requested path HTML and JSON. This includes running `getStaticProps`. -- When that's done, the browser receives the JSON for the generated path. This will be used to automatically render the page with the required props. From the user's perspective, the page will be swapped from the fallback page to the full page. +- When that’s done, the browser receives the JSON for the generated path. This will be used to automatically render the page with the required props. From the user’s perspective, the page will be swapped from the fallback page to the full page. - At the same time, Next.js adds this path to the list of pre-rendered pages. Subsequent requests to the same path will serve the generated page, just like other pages pre-rendered at build time. #### Fallback pages -In the "fallback" version of a page: +In the “fallback” version of a page: -- The page's props will be empty. -- If you use the [router](/docs/api-reference/next/router.md)), `router.isFallback` will be `true`. Learn more about the router [here](/docs/api-reference/next/router.md). +- The page’s props will be empty. +- Using the [router](/docs/api-reference/next/router.md)), you can detect if the fallback is being rendered, `router.isFallback` will be `true`. -Here's an example that uses `isFallback`: +Here’s an example that uses `isFallback`: ```jsx // pages/posts/[id].js @@ -257,13 +257,13 @@ export default Post `fallback: true` is useful if your app has a very large number of static pages that depend on data (think: a very large e-commerce site). You want to pre-render all product pages, but then your builds would take forever. -Instead, you may statically generate a small subset of pages and use `fallback: true` for the rest. When someone requests a page that's not generated yet, the user will see the page with a loading indicator. Shortly after, `getStaticProps` finishes and the page will be rendered with the requested data. From now on, everyone who requests the same page will get the statically pre-rendered page. +Instead, you may statically generate a small subset of pages and use `fallback: true` for the rest. When someone requests a page that’s not generated yet, the user will see the page with a loading indicator. Shortly after, `getStaticProps` finishes and the page will be rendered with the requested data. From now on, everyone who requests the same page will get the statically pre-rendered page. This ensures that users always have a fast experience while preserving fast builds and the benefits of Static Generation. ### When should I use `getStaticPaths`? -You should use `getStaticPaths` if you're statically pre-rendering pages that use dynamic routes. +You should use `getStaticPaths` if you’re statically pre-rendering pages that use dynamic routes. ### Technical details @@ -279,9 +279,9 @@ You cannot use `getStaticPaths` with `getServerSideProps`. #### Only allowed in a page -`getStaticPaths` can only be exported from a **page**. You can't export it from non-page files. +`getStaticPaths` can only be exported from a **page**. You can’t export it from non-page files. -Also, you must use `export` — it will **not** work if you add `getStaticPaths` as a property of the page component. +Also, you must use `export async function getStaticPaths() {}` — it will **not** work if you add `getStaticPaths` as a property of the page component. #### Runs on every request in development @@ -308,7 +308,7 @@ The `context` parameter is an object containing the following keys: ### Simple example -Here's an example which uses `getServerSideProps` to fetch data at request time and pre-renders it. This example is also in the [Pages documentation](/docs/basic-features/pages.md). +Here’s an example which uses `getServerSideProps` to fetch data at request time and pre-renders it. This example is also in the [Pages documentation](/docs/basic-features/pages.md). ```jsx function Page({ data }) { @@ -330,9 +330,9 @@ export default Page ### When should I use `getServerSideProps`? -You should use `getServerSideProps` only if you need to pre-render a page whose data must be fetched on the request time. Time to first byte (TTFB) will be slower than `getStaticProps` because the server must compute the result on every request, and the result cannot be cached by CDN. +You should use `getServerSideProps` only if you need to pre-render a page whose data must be fetched at request time. Time to first byte (TTFB) will be slower than `getStaticProps` because the server must compute the result on every request, and the result cannot be cached by a CDN without extra . -If you don't need to pre-render the data, then you should consider fetching data on the client side. [Click here to learn more](#fetching-data-on-the-client-side). +If you don’t need to pre-render the data, then you should consider fetching data on the client side. [Click here to learn more](#fetching-data-on-the-client-side). ### Technical details @@ -341,26 +341,25 @@ If you don't need to pre-render the data, then you should consider fetching data `getServerSideProps` only runs on server-side and never runs on the browser. If a page uses `getServerSideProps` , then: - When you request this page directly, `getServerSideProps` runs at the request time, and this page will be pre-rendered with the returned props. -- When you request this page on client-side page transitions, the browser sends an API request to Next.js, which runs `getServerSideProps`. It'll return a JSON that contains the result of running `getServerSideProps`, and the JSON will be used to render the page. All this work will be handled automatically by Next.js, so you don't need to do anything extra as long as you have `getServerSideProps` defined. +- When you request this page on client-side page transitions through `next/link` ([documentation](/docs/api-reference/next/link.md)), Next.js sends an API request to server, which runs `getServerSideProps`. It’ll return a JSON that contains the result of running `getServerSideProps`, and the JSON will be used to render the page. All this work will be handled automatically by Next.js, so you don’t need to do anything extra as long as you have `getServerSideProps` defined. #### Only allowed in a page -`getServerSideProps` can only be exported from a **page**. You can't export it from non-page files. +`getServerSideProps` can only be exported from a **page**. You can’t export it from non-page files. -Also, you must use `export` — it will **not** work if you add `getServerSideProps` as a property of the page component. +Also, you must use `export async function getServerSideProps() {}` — it will **not** work if you add `getServerSideProps` as a property of the page component. ## Fetching data on the client side +If your page contains frequently updating data, and you don’t need to pre-render the data, you can fetch the data on the client side. An example of this is user-specific data. Here’s how it works: -If your page contains frequently updating data, and you don't need to pre-render the data, you can fetch the data on the client side. Here's how it works: - -- First, immediately show the page without data. Parts of the page can be pre-rendered using Static Generation (without data). You can show loading states for missing data. +- First, immediately show the page without data. Parts of the page can be pre-rendered using Static Generation. You can show loading states for missing data. - Then, fetch the data on the client side and display it when ready. -This approach works well for user dashboard pages, for example. Because a dashboard is a private, user-specific page, SEO is irrelevant and the page doesn't need to be pre-rendered. And the data is frequently updated, which requires request-time data fetching. +This approach works well for user dashboard pages, for example. Because a dashboard is a private, user-specific page, SEO is not relevant and the page doesn’t need to be pre-rendered. The data is frequently updated, which requires request-time data fetching. ### SWR -ZEIT, the team behind Next.js, has created a React hook for data fetching called [**SWR**](https://swr.now.sh/). We highly recommend it If you're fetching data on the client side. It handles caching, revalidation, focus tracking, refetching on interval, and more. And the usage is very simple: +The team behind Next.js has created a React hook for data fetching called [**SWR**](https://swr.now.sh/). We highly recommend it If you’re fetching data on the client side. It handles caching, revalidation, focus tracking, refetching on interval, and more. And the usage is very simple: ```jsx import useSWR from 'swr' @@ -380,15 +379,15 @@ function Profile() { We recommend you to read the following sections next: -
- + -
- +
+ TypeScript: Add TypeScript to your pages. From 28bb74d9487a90ecdb480b1fbc44c53048acff2b Mon Sep 17 00:00:00 2001 From: Tim Neutkens Date: Thu, 5 Mar 2020 15:26:04 +0100 Subject: [PATCH 21/21] Fix linting --- docs/basic-features/data-fetching.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/basic-features/data-fetching.md b/docs/basic-features/data-fetching.md index b56da9ac21ab4e7..fea4d2f75fb53f8 100644 --- a/docs/basic-features/data-fetching.md +++ b/docs/basic-features/data-fetching.md @@ -102,7 +102,7 @@ This JSON file will be used in client-side routing through `next/link` ([documen One of the reasons for this restriction is that React needs to have all the required data before the page is rendered. -Also, you must use `export async function getStaticProps() {}` — it will **not** work if you add `getStaticProps` as a property of the page component. +Also, you must use `export async function getStaticProps() {}` — it will **not** work if you add `getStaticProps` as a property of the page component. #### Runs on every request in development @@ -341,7 +341,7 @@ If you don’t need to pre-render the data, then you should consider fetching da `getServerSideProps` only runs on server-side and never runs on the browser. If a page uses `getServerSideProps` , then: - When you request this page directly, `getServerSideProps` runs at the request time, and this page will be pre-rendered with the returned props. -- When you request this page on client-side page transitions through `next/link` ([documentation](/docs/api-reference/next/link.md)), Next.js sends an API request to server, which runs `getServerSideProps`. It’ll return a JSON that contains the result of running `getServerSideProps`, and the JSON will be used to render the page. All this work will be handled automatically by Next.js, so you don’t need to do anything extra as long as you have `getServerSideProps` defined. +- When you request this page on client-side page transitions through `next/link` ([documentation](/docs/api-reference/next/link.md)), Next.js sends an API request to server, which runs `getServerSideProps`. It’ll return a JSON that contains the result of running `getServerSideProps`, and the JSON will be used to render the page. All this work will be handled automatically by Next.js, so you don’t need to do anything extra as long as you have `getServerSideProps` defined. #### Only allowed in a page @@ -350,6 +350,7 @@ If you don’t need to pre-render the data, then you should consider fetching da Also, you must use `export async function getServerSideProps() {}` — it will **not** work if you add `getServerSideProps` as a property of the page component. ## Fetching data on the client side + If your page contains frequently updating data, and you don’t need to pre-render the data, you can fetch the data on the client side. An example of this is user-specific data. Here’s how it works: - First, immediately show the page without data. Parts of the page can be pre-rendered using Static Generation. You can show loading states for missing data.