From 0518026ba53a1c11d97840d556e2b33829b2717c Mon Sep 17 00:00:00 2001 From: molebox Date: Thu, 16 Dec 2021 11:05:46 +0100 Subject: [PATCH 01/70] Conflicts --- .../data-fetching/getInitialProps.md | 2 +- .../data-fetching/getServerSideProps.md | 111 +++ .../data-fetching/getStaticPaths.md | 212 +++++ .../data-fetching/getStaticProps.md | 237 +++++ docs/basic-features/data-fetching.md | 882 ------------------ .../data-fetching/data-fetching.md | 165 ++++ .../data-fetching/getServerSideProps.md | 108 +++ .../data-fetching/getStaticPaths.md | 48 + .../data-fetching/getStaticProps.md | 103 ++ docs/manifest.json | 52 +- 10 files changed, 1020 insertions(+), 900 deletions(-) create mode 100644 docs/api-reference/data-fetching/getServerSideProps.md create mode 100644 docs/api-reference/data-fetching/getStaticPaths.md create mode 100644 docs/api-reference/data-fetching/getStaticProps.md delete mode 100644 docs/basic-features/data-fetching.md create mode 100644 docs/basic-features/data-fetching/data-fetching.md create mode 100644 docs/basic-features/data-fetching/getServerSideProps.md create mode 100644 docs/basic-features/data-fetching/getStaticPaths.md create mode 100644 docs/basic-features/data-fetching/getStaticProps.md diff --git a/docs/api-reference/data-fetching/getInitialProps.md b/docs/api-reference/data-fetching/getInitialProps.md index 611533a9b3fc0..7df96387f9982 100644 --- a/docs/api-reference/data-fetching/getInitialProps.md +++ b/docs/api-reference/data-fetching/getInitialProps.md @@ -8,7 +8,7 @@ description: Enable Server-Side Rendering in a page and do initial data populati > > If you're using Next.js 9.3 or newer, we recommend that you use `getStaticProps` or `getServerSideProps` instead of `getInitialProps`. > -> These new data fetching methods allow you to have a granular choice between static generation and server-side rendering. Learn more on the documentation for [Pages](/docs/basic-features/pages.md) and [Data Fetching](/docs/basic-features/data-fetching.md). +> These new data fetching methods allow you to have a granular choice between static generation and server-side rendering. Learn more on the documentation for [Pages](/docs/basic-features/pages.md) and [Data Fetching](/docs/basic-features/data-fetching/data-fetching.md). `getInitialProps` enables [server-side rendering](/docs/basic-features/pages.md#server-side-rendering) in a page and allows you to do **initial data population**, it means sending the [page](/docs/basic-features/pages.md) with the data already populated from the server. This is especially useful for [SEO](https://en.wikipedia.org/wiki/Search_engine_optimization). diff --git a/docs/api-reference/data-fetching/getServerSideProps.md b/docs/api-reference/data-fetching/getServerSideProps.md new file mode 100644 index 0000000000000..ff3833a34d625 --- /dev/null +++ b/docs/api-reference/data-fetching/getServerSideProps.md @@ -0,0 +1,111 @@ +--- +description: Fetch data on each request with `getServerSideProps`. Learn more about this API for data fetching in Next.js. +--- + +# `getServerSideProps` (Server-side Rendering) + +
+ Version History + +| Version | Changes | +| --------- | ------------------------------------------------------------------- | +| `v10.0.0` | `locale`, `locales`, `defaultLocale`, and `notFound` options added. | +| `v9.3.0` | `getServerSideProps` introduced. | + +
+ +When exporting 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 + } +} +``` + +You can import modules in top-level scope for use in `getServerSideProps`. +Imports used will [**not be bundled for the client-side**](#write-server-side-code-directly). This means you can write **server-side code directly in `getServerSideProps`**, including reading from the filesystem or a database. + +You should not use the [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) API to call an [API route](/docs/api-routes/introduction.md) in `getServerSideProps`. + +Instead, directly import the logic used inside your API route. +You may need to slightly refactor your code for this approach. + +The `fetch()` API _can_ be used to fetch external data, such as from a Content Management System (CMS) or API. + +## Context parameter + +The `context` parameter is an object containing the following keys: + +- `params`: If this page uses a [dynamic route](/docs/routing/dynamic-routes.md), `params` contains the route parameters. If the page name is `[id].js` , then `params` will look like `{ id: ... }`. +- `req`: [The `HTTP` IncomingMessage 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`: An object representing the query string. +- `preview`: `preview` is `true` if the page is in the [Preview Mode](/docs/advanced-features/preview-mode.md) and `false` otherwise. +- `previewData`: The [preview](/docs/advanced-features/preview-mode.md) data set by `setPreviewData`. +- `resolvedUrl`: A normalized version of the request `URL` that strips the `_next/data` prefix for client transitions and includes original query values. +- `locale` contains the active locale (if enabled). +- `locales` contains all supported locales (if enabled). +- `defaultLocale` contains the configured default locale (if enabled). + +## `getServerSideProps` return values + +The `getServerSideProps` function should return an object with the following **optional** properties: + +### `props` + +The `props` object is a key value pair, where each value is received by the page component. It should be a [serializable object](https://en.wikipedia.org/wiki/Serialization) + +```jsx +export async function getServerSideProps(context) { + return { + props: { message: `Next.js is awesome` }, // will be passed to the page component as props + } +} +``` + +### `notFound` + +The `notFound` boolean allows the page to return a 404 status and page. With `notFound: true` the page will return a 404 even if there was a successfully generated page before. This is meant to support use-cases like user generated content getting removed by its author. + +```js +export async function getServerSideProps(context) { + const res = await fetch(`https://.../data`) + const data = await res.json() + + if (!data) { + return { + notFound: true, + } + } + + return { + props: { data }, // will be passed to the page component as props + } +} +``` + +### `redirect` + +The `redirect` object to allows redirecting to internal and external resources. It should match the shape of `{ destination: string, permanent: boolean }`. In some rare cases, you might need to assign a custom status code for older `HTTP` Clients to properly redirect. In these cases, you can use the `statusCode` property instead of the `permanent` property, but not both. + +```js +export async function getServerSideProps(context) { + const res = await fetch(`https://.../data`) + const data = await res.json() + + if (!data) { + return { + redirect: { + destination: '/', + permanent: false, + }, + } + } + + return { + props: {}, // will be passed to the page component as props + } +} +``` diff --git a/docs/api-reference/data-fetching/getStaticPaths.md b/docs/api-reference/data-fetching/getStaticPaths.md new file mode 100644 index 0000000000000..370de990df230 --- /dev/null +++ b/docs/api-reference/data-fetching/getStaticPaths.md @@ -0,0 +1,212 @@ +--- +description: Fetch data at build time with `getStaticProps`. +--- + +# `getStaticPaths` (Static Generation) + +
+ Version History + +| Version | Changes | +| -------- | ----------------------------------------------------------------------------------------------------------------- | +| `v9.5.0` | Stable [Incremental Static Regeneration](https://nextjs.org/blog/next-9-5#stable-incremental-static-regeneration) | +| `v9.3.0` | `getStaticPaths` introduced. | + +
+ +When exporting 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 +export async function getStaticPaths() { + return { + paths: [ + { params: { ... } } // See the "paths" section below + ], + fallback: true or false // See the "fallback" section below + }; +} +``` + +## `getStaticPaths` return values + +The `getStaticPaths` function should return an object with the following **required** properties: + +### `paths` + +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`. +- If the page uses an optional catch-all route, supply `null`, `[]`, `undefined` or `false` to render the root-most route. For example, if you supply `slug: false` for `pages/[[...slug]]`, Next.js will statically generate the page `/`. + +### `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 is 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 will need to run the build again. + +The following example 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`](/docs/api-reference/getStaticProps.md). + +```jsx +// pages/posts/[id].js + +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) => ({ + params: { id: 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 +``` + +### `fallback: true` + +
+ Examples + +
+ +If `fallback` is `true`, then the behavior of `getStaticProps` changes in the following ways: + +- The paths returned from `getStaticPaths` will be rendered to `HTML` at build time by `getStaticProps`. +- The paths that have not been generated at build time will **not** result in a 404 page. Instead, Next.js will serve a [“fallback”](#fallback-pages) version of the page on the first request to such a path. +- In the background, Next.js will statically generate the requested path `HTML` and `JSON`. This includes running `getStaticProps`. +- When complete, 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: true` is not supported when using [`next export`](/docs/advanced-features/static-html-export.md). + +#### When is `fallback: true` useful? + +`fallback: true` is useful if your app has a very large number of static pages that depend on data (such as a very large e-commerce site). If you want to pre-render all product pages, the 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 is not generated yet, the user will see the page with a loading indicator or skeleton component. + +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. + +`fallback: true` will not _update_ generated pages, for that take a look at [Incremental Static Regeneration](/docs/basic-features/data-fetching/index#incremental-static-regeneration). + +### `fallback: 'blocking'` + +If `fallback` is `'blocking'`, new paths not returned by `getStaticPaths` will wait for the `HTML` to be generated, identical to SSR (hence why _blocking_), and then be cached for future requests so it only happens once per path. + +`getStaticProps` will behave as follows: + +- The paths returned from `getStaticPaths` will be rendered to `HTML` at build time by `getStaticProps`. +- The paths that have not been generated at build time will **not** result in a 404 page. Instead, Next.js will SSR on the first request and return the generated `HTML`. +- When complete, the browser receives the `HTML` for the generated path. From the user’s perspective, it will transition from "the browser is requesting the page" to "the full page is loaded". There is no flash of loading/fallback state. +- 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: 'blocking'` will not _update_ generated pages by default. To update generated pages, use [Incremental Static Regeneration](/docs/basic-features/data-fetching/index#incremental-static-regeneration) in conjunction with `fallback: 'blocking'`. + +> `fallback: 'blocking'` is not supported when using [`next export`](/docs/advanced-features/static-html-export.md). + +### Fallback pages + +In the “fallback” version of a page: + +- 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`. + +The following example showcases using `isFallback`: + +```jsx +// pages/posts/[id].js +import { useRouter } from 'next/router' + +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 }, + // Re-generate the post at most once per second + // if a request comes in + revalidate: 1, + } +} + +export default Post +``` + +## TypeScript: Use `GetStaticPaths` + +For TypeScript, you can use the `GetStaticPaths` type from `next`: + +```ts +import { GetStaticPaths } from 'next' + +export const getStaticPaths: GetStaticPaths = async () => { + // ... +} +``` diff --git a/docs/api-reference/data-fetching/getStaticProps.md b/docs/api-reference/data-fetching/getStaticProps.md new file mode 100644 index 0000000000000..ba0dfd9b45c09 --- /dev/null +++ b/docs/api-reference/data-fetching/getStaticProps.md @@ -0,0 +1,237 @@ +--- +description: Fetch data at build time with `getStaticProps`. +--- + +# `getStaticProps` (Static Generation) + +
+ Version History + +| Version | Changes | +| --------- | ----------------------------------------------------------------------------------------------------------------- | +| `v10.0.0` | `locale`, `locales`, `defaultLocale`, and `notFound` options added. | +| `v9.5.0` | Stable [Incremental Static Regeneration](https://nextjs.org/blog/next-9-5#stable-incremental-static-regeneration) | +| `v9.3.0` | `getStaticProps` introduced. | + +
+ +Exporting an `async` function called `getStaticProps` will pre-render a page at build time using the props returned from the function: + +```jsx +export async function getStaticProps(context) { + return { + props: {}, // will be passed to the page component as props + } +} +``` + +You can import modules in top-level scope for use in `getStaticProps`. +Imports used will [**not be bundled for the client-side**](#write-server-side-code-directly). This means you can write **server-side code directly in `getStaticProps`**, including reading from the filesystem or a database. + +You should not use the [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) API to call an [API route](/docs/api-routes/introduction.md) in `getStaticProps`. + +Instead, directly import the logic used inside your API route. +You may need to slightly refactor your code for this approach. + +The `fetch()` API _can_ be used to fetch external data, such as from a Content Management System (CMS) or API. + +## Context parameter + +The `context` parameter is an object containing the following keys: + +- `params` contains the route parameters for pages using [dynamic routes](/docs/routing/dynamic-routes.md). For example, if the page name is `[id].js` , then `params` will look like `{ id: ... }`. You should use this together with `getStaticPaths`, which we’ll explain later. +- `preview` is `true` if the page is in the [Preview Mode](/docs/advanced-features/preview-mode.md) and `undefined` otherwise. +- `previewData` contains the [preview](/docs/advanced-features/preview-mode.md) data set by `setPreviewData`. +- `locale` contains the active locale (if enabled). +- `locales` contains all supported locales (if enabled). +- `defaultLocale` contains the configured default locale (if enabled). + +## `getStaticProps` return values + +The `getStaticProps` function should return an object with the following **optional** properties: + +### `props` + +The `props` object is a key value pair, where each value is received by the page component. It should be a [serializable object](https://en.wikipedia.org/wiki/Serialization) + +```jsx +export async function getStaticProps(context) { + return { + props: { message: `Next.js is awesome` }, // will be passed to the page component as props + } +} +``` + +### `revalidate` + +The `revalidate` property is the amount in seconds after which a page re-generation can occur (defaults to: `false` or no revalidating). + +```js +// This function gets called at build time on server-side. +// It may be called again, on a serverless function, if +// revalidation is enabled and a new request comes in +export async function getStaticProps() { + const res = await fetch('https://.../posts') + const posts = await res.json() + + return { + props: { + posts, + }, + // Next.js will attempt to re-generate the page: + // - When a request comes in + // - At most once every 10 seconds + revalidate: 10, // In seconds + } +} +``` + +More information is covered in [Incremental Static Regeneration](/docs/basic-features/data-fetching/data-fetching#incremental-static-regeneration) + +### `notFound` + +The `notFound` boolean allows the page to return a 404 status and page. With `notFound: true` the page will return a 404 even if there was a successfully generated page before. This is meant to support use-cases like user generated content getting removed by its author. + +```js +export async function getStaticProps(context) { + const res = await fetch(`https://.../data`) + const data = await res.json() + + if (!data) { + return { + notFound: true, + } + } + + return { + props: { data }, // will be passed to the page component as props + } +} +``` + +> **Note**: `notFound` is not needed for [`fallback: false`](/docs/api-reference/data-fetching/getStaticPaths#fallback-false) mode as only paths returned from `getStaticPaths` will be pre-rendered. + +### `redirect` + +The `redirect` object allows redirecting to internal or external resources. It should match the shape of `{ destination: string, permanent: boolean }`. In some rare cases, you might need to assign a custom status code for older `HTTP` Clients to properly redirect. In these cases, you can use the `statusCode` property instead of the `permanent` property, but not both. You can also set `basePath: false` similar to redirects in `next.config.js`. + +```js +export async function getStaticProps(context) { + const res = await fetch(`https://...`) + const data = await res.json() + + if (!data) { + return { + redirect: { + destination: '/', + permanent: false, + }, + } + } + + return { + props: { data }, // will be passed to the page component as props + } +} +``` + +Redirecting at build-time is currently not allowed and if the redirects are known at build-time they should be added in [`next.config.js`](/docs/api-reference/next.config.js/redirects.md). + +## TypeScript: Use `GetStaticProps` + +You can use the `GetStaticProps` type from `next` to type the function: + +```ts +import { GetStaticProps } from 'next' + +export const getStaticProps: GetStaticProps = async (context) => { + // ... +} +``` + +If you want to get inferred typings for your props, you can use `InferGetStaticPropsType`: + +```tsx +import { InferGetStaticPropsType } from 'next' + +type Post = { + author: string + content: string +} + +export const getStaticProps = async () => { + const res = await fetch('https://.../posts') + const posts: Post[] = await res.json() + + return { + props: { + posts, + }, + } +} + +function Blog({ posts }: InferGetStaticPropsType) { + // will resolve posts to type Post[] +} + +export default Blog +``` + +## Reading files: Use `process.cwd()` + +Files can be read directly from the filesystem in `getStaticProps`. + +In order to do so you have to get the full path to a file. + +Since Next.js compiles your code into a separate directory you can't use `__dirname` as the path it will return will be different from the pages directory. + +Instead you can use `process.cwd()` which gives you the directory where Next.js is being executed. + +```jsx +import { promises as fs } from 'fs' +import path from 'path' + +// posts will be populated at build time by getStaticProps() +function Blog({ posts }) { + return ( +
    + {posts.map((post) => ( +
  • +

    {post.filename}

    +

    {post.content}

    +
  • + ))} +
+ ) +} + +// 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() { + const postsDirectory = path.join(process.cwd(), 'posts') + const filenames = await fs.readdir(postsDirectory) + + const posts = filenames.map(async (filename) => { + const filePath = path.join(postsDirectory, filename) + const fileContents = await fs.readFile(filePath, 'utf8') + + // Generally you would parse/transform the contents + // For example you can transform markdown to HTML here + + return { + filename, + content: fileContents, + } + }) + // By returning { props: { posts } }, the Blog component + // will receive `posts` as a prop at build time + return { + props: { + posts: await Promise.all(posts), + }, + } +} + +export default Blog +``` diff --git a/docs/basic-features/data-fetching.md b/docs/basic-features/data-fetching.md deleted file mode 100644 index d7d2caaa5c1b8..0000000000000 --- a/docs/basic-features/data-fetching.md +++ /dev/null @@ -1,882 +0,0 @@ ---- -description: 'Next.js has 2 pre-rendering modes: Static Generation and Server-side rendering. Learn how they work here.' ---- - -# 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). - -
- Examples - -
- -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 depth 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 unique Next.js functions you can use to fetch data for pre-rendering: - -- [`getStaticProps`](#getstaticprops-static-generation) (Static Generation): Fetch data at **build time**. -- [`getStaticPaths`](#getstaticpaths-static-generation) (Static Generation): Specify [dynamic routes](/docs/routing/dynamic-routes.md) to pre-render pages based on data. -- [`getServerSideProps`](#getserversideprops-server-side-rendering) (Server-side Rendering): Fetch data on **each request**. - -In addition, we’ll talk briefly about how to fetch data on the client side. - -## `getStaticProps` (Static Generation) - -
- Version History - -| Version | Changes | -| --------- | ----------------------------------------------------------------------------------------------------------------- | -| `v12.0.0` | `staticPageGenerationTimeout` added. | -| `v10.0.0` | `locale`, `locales`, `defaultLocale`, and `notFound` options added. | -| `v9.5.0` | Stable [Incremental Static Regeneration](https://nextjs.org/blog/next-9-5#stable-incremental-static-regeneration) | -| `v9.3.0` | `getStaticProps` introduced. | - -
- -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`. - -```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: - -- `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. -- `preview` is `true` if the page is in the preview mode and `undefined` otherwise. See the [Preview Mode documentation](/docs/advanced-features/preview-mode.md). -- `previewData` contains the preview data set by `setPreviewData`. See the [Preview Mode documentation](/docs/advanced-features/preview-mode.md). -- `locale` contains the active locale (if you've enabled [Internationalized Routing](/docs/advanced-features/i18n-routing.md)). -- `locales` contains all supported locales (if you've enabled [Internationalized Routing](/docs/advanced-features/i18n-routing.md)). -- `defaultLocale` contains the configured default locale (if you've enabled [Internationalized Routing](/docs/advanced-features/i18n-routing.md)). - -`getStaticProps` should return an object with: - -- `props` - An **optional** object with the props that will be received by the page component. It should be a [serializable object](https://en.wikipedia.org/wiki/Serialization) -- `revalidate` - An **optional** amount in seconds after which a page re-generation can occur. Defaults to `false`. When `revalidate` is `false` it means that there is no revalidation, so the page will be cached as built until your next build. More on [Incremental Static Regeneration](#incremental-static-regeneration) -- `notFound` - An **optional** boolean value to allow the page to return a 404 status and page. Below is an example of how it works: - - ```js - export async function getStaticProps(context) { - const res = await fetch(`https://.../data`) - const data = await res.json() - - if (!data) { - return { - notFound: true, - } - } - - return { - props: { data }, // will be passed to the page component as props - } - } - ``` - - > **Note**: `notFound` is not needed for [`fallback: false`](#fallback-false) mode as only paths returned from `getStaticPaths` will be pre-rendered. - - > **Note**: With `notFound: true` the page will return a 404 even if there was a successfully generated page before. This is meant to support use-cases like user generated content getting removed by its author. - -- `redirect` - An **optional** redirect value to allow redirecting to internal and external resources. It should match the shape of `{ destination: string, permanent: boolean }`. In some rare cases, you might need to assign a custom status code for older HTTP Clients to properly redirect. In these cases, you can use the `statusCode` property instead of the `permanent` property, but not both. You can also set `basePath: false` similar to redirects in `next.config.js`. Below is an example of how it works: - - ```js - export async function getStaticProps(context) { - const res = await fetch(`https://...`) - const data = await res.json() - - if (!data) { - return { - redirect: { - destination: '/', - permanent: false, - }, - } - } - - return { - props: { data }, // will be passed to the page component as props - } - } - ``` - - > **Note**: Redirecting at build-time is currently not allowed and if the redirects are known at build-time they should be added in [`next.config.js`](/docs/api-reference/next.config.js/redirects.md). - -> **Note**: You can import modules in top-level scope for use in `getStaticProps`. -> Imports used in `getStaticProps` will [not be bundled for the client-side](#write-server-side-code-directly). -> -> This means you can write **server-side code directly in `getStaticProps`**. -> This includes reading from the filesystem or a database. - -> **Note**: You should not use [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) to -> call an API route in `getStaticProps`. -> Instead, directly import the logic used inside your API route. -> You may need to slightly refactor your code for this approach. -> -> Fetching from an external API is fine! - -### 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). - -```jsx -// posts will be populated at build time by getStaticProps() -function Blog({ posts }) { - return ( -
    - {posts.map((post) => ( -
  • {post.title}
  • - ))} -
- ) -} - -// 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. - // You can use any data fetching library - 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, - }, - } -} - -export default Blog -``` - -### 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 a 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. - -### TypeScript: Use `GetStaticProps` - -For TypeScript, you can use the `GetStaticProps` type from `next`: - -```ts -import { GetStaticProps } from 'next' - -export const getStaticProps: GetStaticProps = async (context) => { - // ... -} -``` - -If you want to get inferred typings for your props, you can use `InferGetStaticPropsType`, like this: - -```tsx -import { InferGetStaticPropsType } from 'next' - -type Post = { - author: string - content: string -} - -export const getStaticProps = async () => { - const res = await fetch('https://.../posts') - const posts: Post[] = await res.json() - - return { - props: { - posts, - }, - } -} - -function Blog({ posts }: InferGetStaticPropsType) { - // will resolve posts to type Post[] -} - -export default Blog -``` - -Note: Next.js has a default static generation timeout of 60 seconds. If no new pages complete generating within the timeout, it will attempt generation three more times. If the fourth attempt fails, the build will fail. This timeout can be modified using the following configuration: - -```js -// next.config.js -module.exports = { - // time in seconds of no pages generating during static - // generation before timing out - staticPageGenerationTimeout: 90, -} -``` - -### Incremental Static Regeneration - -
- Examples - -
- -
- Version History - -| Version | Changes | -| -------- | ---------------- | -| `v9.5.0` | Base Path added. | - -
- -Next.js allows you to create or update static pages _after_ you’ve built your site. Incremental Static Regeneration (ISR) enables you to use static-generation on a per-page basis, **without needing to rebuild the entire site**. With ISR, you can retain the benefits of static while scaling to millions of pages. - -Consider our previous [`getStaticProps` example](#simple-example), but now with Incremental Static Regeneration enabled through the `revalidate` property: - -```jsx -function Blog({ posts }) { - return ( -
    - {posts.map((post) => ( -
  • {post.title}
  • - ))} -
- ) -} - -// This function gets called at build time on server-side. -// It may be called again, on a serverless function, if -// revalidation is enabled and a new request comes in -export async function getStaticProps() { - const res = await fetch('https://.../posts') - const posts = await res.json() - - return { - props: { - posts, - }, - // Next.js will attempt to re-generate the page: - // - When a request comes in - // - At most once every 10 seconds - revalidate: 10, // In seconds - } -} - -// This function gets called at build time on server-side. -// It may be called again, on a serverless function, if -// the path has not been generated. -export async function getStaticPaths() { - 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) => ({ - params: { id: post.id }, - })) - - // We'll pre-render only these paths at build time. - // { fallback: blocking } will server-render pages - // on-demand if the path doesn't exist. - return { paths, fallback: 'blocking' } -} - -export default Blog -``` - -When a request is made to a page that was pre-rendered at build time, it will initially show the cached page. - -- Any requests to the page after the initial request and before 10 seconds are also cached and instantaneous. -- After the 10-second window, the next request will still show the cached (stale) page -- Next.js triggers a regeneration of the page in the background. -- Once the page has been successfully generated, Next.js will invalidate the cache and show the updated product page. If the background regeneration fails, the old page will stay unaltered. - -When a request is made to a path that hasn’t been generated, Next.js will server-render the page on the first request. Future requests will serve the static file from the cache. - -To learn how to persist the cache globally and handle rollbacks, learn more about [Incremental Static Regeneration](https://vercel.com/docs/next.js/incremental-static-regeneration). - -### Reading files: Use `process.cwd()` - -Files can be read directly from the filesystem in `getStaticProps`. - -In order to do so you have to get the full path to a file. - -Since Next.js compiles your code into a separate directory you can't use `__dirname` as the path it will return will be different from the pages directory. - -Instead you can use `process.cwd()` which gives you the directory where Next.js is being executed. - -```jsx -import { promises as fs } from 'fs' -import path from 'path' - -// posts will be populated at build time by getStaticProps() -function Blog({ posts }) { - return ( -
    - {posts.map((post) => ( -
  • -

    {post.filename}

    -

    {post.content}

    -
  • - ))} -
- ) -} - -// 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() { - const postsDirectory = path.join(process.cwd(), 'posts') - const filenames = await fs.readdir(postsDirectory) - - const posts = filenames.map(async (filename) => { - const filePath = path.join(postsDirectory, filename) - const fileContents = await fs.readFile(filePath, 'utf8') - - // Generally you would parse/transform the contents - // For example you can transform markdown to HTML here - - return { - filename, - content: fileContents, - } - }) - // By returning { props: { posts } }, the Blog component - // will receive `posts` as a prop at build time - return { - props: { - posts: await Promise.all(posts), - }, - } -} - -export default Blog -``` - -### 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`. - -You can use [this tool](https://next-code-elimination.vercel.app/) to verify what Next.js eliminates from the client-side bundle. - -#### 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. - -When using Incremental Static Generation `getStaticProps` will be executed out of band to generate the JSON needed for client-side navigation. You may see this in the form of multiple requests being made for the same page, however, this is intended and has no impact on end-user performance. - -#### Only allowed in a page - -`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 async function getStaticProps() {}` — it will **not** work if you add `getStaticProps` as a property of the page component. - -#### Runs on every request in development - -In development (`next dev`), `getStaticProps` will be called on every request. - -#### Preview Mode - -In some cases, you might want to temporarily bypass Static Generation and render the page at **request time** instead of build time. For example, you might be using a headless CMS and want to preview drafts before they're published. - -This use case is supported by Next.js by the feature called **Preview Mode**. Learn more on the [Preview Mode documentation](/docs/advanced-features/preview-mode.md). - -## `getStaticPaths` (Static Generation) - -
- Version History - -| Version | Changes | -| -------- | ----------------------------------------------------------------------------------------------------------------- | -| `v9.5.0` | Stable [Incremental Static Regeneration](https://nextjs.org/blog/next-9-5#stable-incremental-static-regeneration) | -| `v9.3.0` | `getStaticPaths` introduced. | - -
- -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`. - -```jsx -export async function getStaticPaths() { - return { - paths: [ - { params: { ... } } // See the "paths" section below - ], - fallback: true, false, or 'blocking' // See the "fallback" section below - }; -} -``` - -#### The `paths` key (required) - -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`. -- If the page uses an optional catch-all route, supply `null`, `[]`, `undefined` or `false` to render the root-most route. For example, if you supply `slug: false` for `pages/[[...slug]]`, Next.js will statically generate the page `/`. - -#### 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. - -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 - -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) => ({ - params: { id: 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 -``` - -#### `fallback: true` - -
- Examples - -
- -If `fallback` is `true`, then the behavior of `getStaticProps` changes: - -- The paths returned from `getStaticPaths` will be rendered to HTML at build time by `getStaticProps`. -- 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). Note: this "fallback" version will not be served for crawlers like Google and instead will render the path in `blocking` mode. -- 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, like other pages pre-rendered at build time. - -> `fallback: true` is not supported when using [`next export`](/docs/advanced-features/static-html-export.md). - -#### Fallback pages - -In the “fallback” version of a page: - -- 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`: - -```jsx -// pages/posts/[id].js -import { useRouter } from 'next/router' - -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 }, - // Re-generate the post at most once per second - // if a request comes in - revalidate: 1, - } -} - -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. - -`fallback: true` will not _update_ generated pages, for that take a look at [Incremental Static Regeneration](#incremental-static-regeneration). - -#### `fallback: 'blocking'` - -If `fallback` is `'blocking'`, new paths not returned by `getStaticPaths` will wait for the HTML to be generated, identical to SSR (hence why _blocking_), and then be cached for future requests so it only happens once per path. - -`getStaticProps` will behave as follows: - -- The paths returned from `getStaticPaths` will be rendered to HTML at build time by `getStaticProps`. -- The paths that have not been generated at build time will **not** result in a 404 page. Instead, Next.js will SSR on the first request and return the generated HTML. -- When that’s done, the browser receives the HTML for the generated path. From the user’s perspective, it will transition from "the browser is requesting the page" to "the full page is loaded". There is no flash of loading/fallback state. -- 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, like other pages pre-rendered at build time. - -`fallback: 'blocking'` will not _update_ generated pages by default. To update generated pages, use [Incremental Static Regeneration](#incremental-static-regeneration) in conjunction with `fallback: 'blocking'`. - -> `fallback: 'blocking'` is not supported when using [`next export`](/docs/advanced-features/static-html-export.md). - -### When should I use `getStaticPaths`? - -You should use `getStaticPaths` if you’re statically pre-rendering pages that use dynamic routes. - -### TypeScript: Use `GetStaticPaths` - -For TypeScript, you can use the `GetStaticPaths` type from `next`: - -```ts -import { GetStaticPaths } from 'next' - -export const getStaticPaths: GetStaticPaths = async () => { - // ... -} -``` - -### 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 async function getStaticPaths() {}` — 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) - -
- Version History - -| Version | Changes | -| --------- | ------------------------------------------------------------------- | -| `v10.0.0` | `locale`, `locales`, `defaultLocale`, and `notFound` options added. | -| `v9.3.0` | `getServerSideProps` introduced. | - -
- -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 IncomingMessage object](https://nodejs.org/api/http.html#http_class_http_incomingmessage), plus additional [built-in parsing helpers](#provided-req-middleware-in-getserversideprops). -- `res`: [The HTTP response object](https://nodejs.org/api/http.html#http_class_http_serverresponse). -- `query`: An object representing the query string. -- `preview`: `preview` is `true` if the page is in the preview mode and `false` otherwise. See the [Preview Mode documentation](/docs/advanced-features/preview-mode.md). -- `previewData`: The preview data set by `setPreviewData`. See the [Preview Mode documentation](/docs/advanced-features/preview-mode.md). -- `resolvedUrl`: A normalized version of the request URL that strips the `_next/data` prefix for client transitions and includes original query values. -- `locale` contains the active locale (if you've enabled [Internationalized Routing](/docs/advanced-features/i18n-routing.md)). -- `locales` contains all supported locales (if you've enabled [Internationalized Routing](/docs/advanced-features/i18n-routing.md)). -- `defaultLocale` contains the configured default locale (if you've enabled [Internationalized Routing](/docs/advanced-features/i18n-routing.md)). - -`getServerSideProps` should return an object with: - -- `props` - An **optional** object with the props that will be received by the page component. It should be a [serializable object](https://en.wikipedia.org/wiki/Serialization) or a Promise that resolves to a serializable object. -- `notFound` - An **optional** boolean value to allow the page to return a 404 status and page. Below is an example of how it works: - - ```js - export async function getServerSideProps(context) { - const res = await fetch(`https://...`) - const data = await res.json() - - if (!data) { - return { - notFound: true, - } - } - - return { - props: {}, // will be passed to the page component as props - } - } - ``` - -- `redirect` - An **optional** redirect value to allow redirecting to internal and external resources. It should match the shape of `{ destination: string, permanent: boolean }`. In some rare cases, you might need to assign a custom status code for older HTTP Clients to properly redirect. In these cases, you can use the `statusCode` property instead of the `permanent` property, but not both. You can also set `basePath: false` similar to redirects in `next.config.js`. Below is an example of how it works: - - ```js - export async function getServerSideProps(context) { - const res = await fetch(`https://.../data`) - const data = await res.json() - - if (!data) { - return { - redirect: { - destination: '/', - permanent: false, - }, - } - } - - return { - props: {}, // will be passed to the page component as props - } - } - ``` - -> **Note**: You can import modules in top-level scope for use in `getServerSideProps`. -> Imports used in `getServerSideProps` will not be bundled for the client-side. -> -> This means you can write **server-side code directly in `getServerSideProps`**. -> This includes reading from the filesystem or a database. - -> **Note**: You should not use [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) to -> call an API route in `getServerSideProps`. -> Instead, directly import the logic used inside your API route. -> You may need to slightly refactor your code for this approach. -> -> Fetching from an external API is fine! - -### Provided `req` middleware in `getServerSideProps` - -The `req` in the context passed to `getServerSideProps` provides built in middleware that parses the incoming request (req). That middleware is: - -- `req.cookies` - An object containing the cookies sent by the request. Defaults to `{}` - -### 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). - -```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 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 configuration. - -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). - -### TypeScript: Use `GetServerSideProps` - -For TypeScript, you can use the `GetServerSideProps` type from `next`: - -```ts -import { GetServerSideProps } from 'next' - -export const getServerSideProps: GetServerSideProps = async (context) => { - // ... -} -``` - -If you want to get inferred typings for your props, you can use `InferGetServerSidePropsType`, like this: - -```tsx -import { InferGetServerSidePropsType } from 'next' - -type Data = { ... } - -export const getServerSideProps = async () => { - const res = await fetch('https://.../data') - const data: Data = await res.json() - - return { - props: { - data, - }, - } -} - -function Page({ data }: InferGetServerSidePropsType) { - // will resolve posts to type Data -} - -export default Page -``` - -### 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 through `next/link` ([documentation](/docs/api-reference/next/link.md)) or `next/router` ([documentation](/docs/api-reference/next/router.md)), Next.js sends an API request to the server, which runs `getServerSideProps`. It’ll return 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. - -You can use [this tool](https://next-code-elimination.vercel.app/) to verify what Next.js eliminates from the client-side bundle. - -#### 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 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. -- 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 not relevant and the page doesn’t need to be pre-rendered. The data is frequently updated, which requires request-time data fetching. - -### SWR - -The team behind Next.js has created a React hook for data fetching called [**SWR**](https://swr.vercel.app/). 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 you can use it like so: - -```jsx -import useSWR from 'swr' - -const fetcher = (url) => fetch(url).then((res) => res.json()) - -function Profile() { - const { data, error } = useSWR('/api/user', fetcher) - - if (error) return
failed to load
- if (!data) return
loading...
- return
hello {data.name}!
-} -``` - -[Check out the SWR documentation to learn more](https://swr.vercel.app/). - -## Learn more - -We recommend you to read the following sections next: - - - - - - diff --git a/docs/basic-features/data-fetching/data-fetching.md b/docs/basic-features/data-fetching/data-fetching.md new file mode 100644 index 0000000000000..cf4be5edca29d --- /dev/null +++ b/docs/basic-features/data-fetching/data-fetching.md @@ -0,0 +1,165 @@ +--- +description: 'Data fetching in Next.js allows you to render your content in different ways, depending on your applications use case. These include pre-rendering with server-side rendering or static-site generation, and incremental static regeneration. Learn how to manage your application data in Next.js.' +--- + +# Data Fetching + +
+ Examples + +
+ +The [Pages documentation](/docs/basic-features/pages.md) explained that Next.js has two forms of pre-rendering: **Static Generation** and **Server-side Rendering**. In the sections below, you will learn about data fetching strategies for each case. + +It is recommended that you [read through the Pages documentation](/docs/basic-features/pages.md) first if you have not already done so. + +The three unique Next.js functions you can use to fetch data for pre-rendering are: + +- [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) (Static Generation): Fetch data at **build time**. +- [`getStaticPaths`](/docs/basic-features/data-fetching/getStaticPaths.md) (Static Generation): Specify [dynamic routes](/docs/routing/dynamic-routes.md) to pre-render pages based on data. +- [`getServerSideProps`](/docs/basic-features/data-fetching/getServerSideProps.md) (Server-side Rendering): Fetch data on **each request**. + +## Incremental Static Regeneration + +
+ Examples + +
+ +
+ Version History + +| Version | Changes | +| -------- | ---------------- | +| `v9.5.0` | Base Path added. | + +
+ +Next.js allows you to create or update static pages _after_ you’ve built your site. Incremental Static Regeneration (ISR) enables you to use static-generation on a per-page basis, **without needing to rebuild the entire site**. With ISR, you can retain the benefits of static while scaling to millions of pages. + +The following example shows how to use the `revalidate` property: + +```jsx +function Blog({ posts }) { + return ( +
    + {posts.map((post) => ( +
  • {post.title}
  • + ))} +
+ ) +} + +// This function gets called at build time on server-side. +// It may be called again, on a serverless function, if +// revalidation is enabled and a new request comes in +export async function getStaticProps() { + const res = await fetch('https://.../posts') + const posts = await res.json() + + return { + props: { + posts, + }, + // Next.js will attempt to re-generate the page: + // - When a request comes in + // - At most once every 10 seconds + revalidate: 10, // In seconds + } +} + +// This function gets called at build time on server-side. +// It may be called again, on a serverless function, if +// the path has not been generated. +export async function getStaticPaths() { + 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) => ({ + params: { id: post.id }, + })) + + // We'll pre-render only these paths at build time. + // { fallback: blocking } will server-render pages + // on-demand if the path doesn't exist. + return { paths, fallback: 'blocking' } +} + +export default Blog +``` + +When a request is made to a page that was pre-rendered at build time, it will initially show the cached page. + +- Any requests to the page after the initial request and before 10 seconds are also cached and instantaneous. +- After the 10-second window, the next request will still show the cached (stale) page +- Next.js triggers a regeneration of the page in the background. +- Once the page has been successfully generated, Next.js will invalidate the cache and show the updated product page. If the background regeneration fails, the old page remains unaltered. + +When a request is made to a path that hasn’t been generated, Next.js will server-render the page on the first request. Future requests will serve the static file from the cache. + +To learn how to persist the cache globally and handle rollbacks, learn more about [Incremental Static Regeneration](https://vercel.com/docs/next.js/incremental-static-regeneration). + +## SWR + +The team behind Next.js has created a React hook for data fetching called [**SWR**](https://swr.vercel.app/). 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 you can use it like so: + +```jsx +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.vercel.app/). + +## Learn more + +We recommend you to read the following sections next: + + + + + + diff --git a/docs/basic-features/data-fetching/getServerSideProps.md b/docs/basic-features/data-fetching/getServerSideProps.md new file mode 100644 index 0000000000000..b0cb51c136793 --- /dev/null +++ b/docs/basic-features/data-fetching/getServerSideProps.md @@ -0,0 +1,108 @@ +--- +description: Fetch data at build time with `getStaticProps` API reference. +--- + +# `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 [`getServerSideProps` API reference](/docs/api-reference/getServerSideProps.md) covers all parameters and props that can be used with `getServerSideProps`. + +### When should I use `getServerSideProps`? + +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`](/docs/data-fetching/getstaticprops.md) because the server must compute the result on every request, and the result cannot be cached by a CDN without extra configuration. + +If you do not need to pre-render the data, then you should consider fetching data on the [client side](#fetching-data-on-the-client-side). + +### TypeScript: Use `GetServerSideProps` + +For TypeScript, you can use the `GetServerSideProps` type from `next`: + +```ts +import { GetServerSideProps } from 'next' + +export const getServerSideProps: GetServerSideProps = async (context) => { + // ... +} +``` + +If you want to get inferred typings for your props, you can use `InferGetServerSidePropsType`, like this: + +```tsx +import { InferGetServerSidePropsType } from 'next' + +type Data = { ... } + +export const getServerSideProps = async () => { + const res = await fetch('https://.../data') + const data: Data = await res.json() + + return { + props: { + data, + }, + } +} + +function Page({ data }: InferGetServerSidePropsType) { + // will resolve posts to type Data +} + +export default Page +``` + +### 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 through `next/link` ([documentation](/docs/api-reference/next/link.md)) or `next/router` ([documentation](/docs/api-reference/next/router.md)), Next.js sends an API request to the server, which runs `getServerSideProps`. It’ll return 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. + +You can use [this tool](https://next-code-elimination.vercel.app/) to verify what Next.js eliminates from the client-side bundle. + +#### 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 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. +- 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 not relevant and the page doesn’t need to be pre-rendered. The data is frequently updated, which requires request-time data fetching. + +## Using `getServerSideProps` to fetch data at request time + +The following example shows how to fetch data at request time and pre-render the result. + +```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 +``` diff --git a/docs/basic-features/data-fetching/getStaticPaths.md b/docs/basic-features/data-fetching/getStaticPaths.md new file mode 100644 index 0000000000000..20cf3aee366b5 --- /dev/null +++ b/docs/basic-features/data-fetching/getStaticPaths.md @@ -0,0 +1,48 @@ +--- +description: Fetch data at build time with `getStaticProps` API reference. +--- + +# `getStaticPaths` (Static Generation) + +If a page has [dynamic routes](/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. + +When 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 +export async function getStaticPaths() { + return { + paths: [ + { params: { ... } } + ], + fallback: true // false or blocking + }; +} +``` + +The [`getStaticPaths` API reference](/docs/api-reference/getstaticpaths.md) covers all parameters and props that can be used with `getStaticPaths`. + +## 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`](/docs/basic-features/data-fetching/getStaticProps.md) + +When you use `getStaticProps` on a page with dynamic route parameters, you **must** use `getStaticPaths`. + +Note that you **cannot** use `getStaticPaths` with [`getServerSideProps`](/docs/data-fetching/getServerSideProps.md). + +### 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 **cannot** export it from non-page files. + +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 + +In development (`next dev`), `getStaticPaths` will be called on every request. diff --git a/docs/basic-features/data-fetching/getStaticProps.md b/docs/basic-features/data-fetching/getStaticProps.md new file mode 100644 index 0000000000000..ab6c60cfa857a --- /dev/null +++ b/docs/basic-features/data-fetching/getStaticProps.md @@ -0,0 +1,103 @@ +--- +description: Fetch data at build time with `getStaticProps` (Static Generation) API reference. +--- + +# `getStaticProps` (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`. + +```jsx +export async function getStaticProps(context) { + return { + props: {}, // will be passed to the page component as props + } +} +``` + +## 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 a 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. + +## Using `getStaticProps` to fetch data from a CMS + +The following example shows how you can fetch a list of blog posts from a CMS. + +```jsx +// posts will be populated at build time by getStaticProps() +function Blog({ posts }) { + return ( +
    + {posts.map((post) => ( +
  • {post.title}
  • + ))} +
+ ) +} + +// 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. + // You can use any data fetching library + 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, + }, + } +} + +export default Blog +``` + +The [`getStaticProps` API reference](/docs/api-reference/getStaticProps.md) covers all parameters and props that can be used with `getStaticProps`. + +## 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`. + +You can use the [next-code-elimination tool](https://next-code-elimination.vercel.app/) to verify what Next.js eliminates from the client-side bundle. + +### 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`](/docs/api-reference/next/link.md) or [`next/router`](/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. + +When using Incremental Static Generation `getStaticProps` will be executed out of band to generate the `JSON` needed for client-side navigation. You may see this in the form of multiple requests being made for the same page, however, this is intended and has no impact on end-user performance + +### Only allowed in a page + +`getStaticProps` can only be exported from a **page**. You **cannot** 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 async function getStaticProps() {}` — it will **not** work if you add `getStaticProps` as a property of the page component. + +### Runs on every request in development + +In development (`next dev`), `getStaticProps` will be called on every request. + +### Preview Mode + +In some cases, you might want to temporarily bypass Static Generation and render the page at **request time** instead of build time. For example, you might be using a headless CMS and want to preview drafts before they're published. + +This use case is supported in Next.js by the [**Preview Mode**](/docs/advanced-features/preview-mode.md) feature. diff --git a/docs/manifest.json b/docs/manifest.json index 340199c8ff9d7..fa985437bec9f 100644 --- a/docs/manifest.json +++ b/docs/manifest.json @@ -15,16 +15,30 @@ }, { "title": "Data Fetching", - "path": "/docs/basic-features/data-fetching.md" + "path": "/docs/basic-features/data-fetching.md", + "redirect": { + "destination": "/docs/basic-features/data-fetching/data-fetching.md", + "permanent": true + }, + "routes": [ + { + "title": "getServerSideProps", + "path": "/docs/basic-features/data-fetching/getServerSideProps.md" + }, + { + "title": "getStaticPaths", + "path": "/docs/basic-features/data-fetching/getStaticPaths.md" + }, + { + "title": "getStaticProps", + "path": "/docs/basic-features/data-fetching/getStaticProps.md" + } + ] }, { "title": "Built-in CSS Support", "path": "/docs/basic-features/built-in-css-support.md" }, - { - "title": "Layouts", - "path": "/docs/basic-features/layouts.md" - }, { "title": "Image Optimization", "path": "/docs/basic-features/image-optimization.md" @@ -33,10 +47,6 @@ "title": "Font Optimization", "path": "/docs/basic-features/font-optimization.md" }, - { - "title": "Script Optimization", - "path": "/docs/basic-features/script.md" - }, { "title": "Static File Serving", "path": "/docs/basic-features/static-file-serving.md" @@ -60,6 +70,10 @@ { "title": "Supported Browsers and Features", "path": "/docs/basic-features/supported-browsers-features.md" + }, + { + "title": "Script", + "path": "/docs/basic-features/script.md" } ] }, @@ -121,10 +135,6 @@ "title": "Authentication", "path": "/docs/authentication.md" }, - { - "title": "Testing", - "path": "/docs/testing.md" - }, { "title": "Advanced Features", "routes": [ @@ -322,6 +332,18 @@ { "title": "getInitialProps", "path": "/docs/api-reference/data-fetching/getInitialProps.md" + }, + { + "title": "getServerSideProps", + "path": "/docs/api-reference/data-fetching/getServerSideProps.md" + }, + { + "title": "getStaticPaths", + "path": "/docs/api-reference/data-fetching/getStaticPaths.md" + }, + { + "title": "getStaticProps", + "path": "/docs/api-reference/data-fetching/getStaticProps.md" } ] }, @@ -384,10 +406,6 @@ "title": "Disabling ETag Generation", "path": "/docs/api-reference/next.config.js/disabling-etag-generation.md" }, - { - "title": "Disabling HTTP Keep-Alive", - "path": "/docs/api-reference/next.config.js/disabling-http-keep-alive.md" - }, { "title": "Setting a custom build directory", "path": "/docs/api-reference/next.config.js/setting-a-custom-build-directory.md" From 72f3e3a3cadd5ff454e94c0202642245a820bf38 Mon Sep 17 00:00:00 2001 From: Rich Haines Date: Tue, 12 Oct 2021 11:00:16 +0200 Subject: [PATCH 02/70] Fixed titles --- .../data-fetching/getServerSideProps.md | 4 ++-- docs/api-reference/data-fetching/getStaticPaths.md | 4 ++-- docs/api-reference/data-fetching/getStaticProps.md | 4 ++-- .../data-fetching/getServerSideProps.md | 14 +++++++------- .../basic-features/data-fetching/getStaticPaths.md | 4 ++-- .../basic-features/data-fetching/getStaticProps.md | 4 ++-- 6 files changed, 17 insertions(+), 17 deletions(-) diff --git a/docs/api-reference/data-fetching/getServerSideProps.md b/docs/api-reference/data-fetching/getServerSideProps.md index ff3833a34d625..8b9a3fa96d7c7 100644 --- a/docs/api-reference/data-fetching/getServerSideProps.md +++ b/docs/api-reference/data-fetching/getServerSideProps.md @@ -2,7 +2,7 @@ description: Fetch data on each request with `getServerSideProps`. Learn more about this API for data fetching in Next.js. --- -# `getServerSideProps` (Server-side Rendering) +# `getServerSideProps`
Version History @@ -14,7 +14,7 @@ description: Fetch data on each request with `getServerSideProps`. Learn more ab
-When exporting an `async` function called `getServerSideProps` from a page, Next.js will pre-render this page on each request using the data returned by `getServerSideProps`. +When exporting an `async` function called `getServerSideProps` (server-side rendering) 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) { diff --git a/docs/api-reference/data-fetching/getStaticPaths.md b/docs/api-reference/data-fetching/getStaticPaths.md index 370de990df230..cebc44542af81 100644 --- a/docs/api-reference/data-fetching/getStaticPaths.md +++ b/docs/api-reference/data-fetching/getStaticPaths.md @@ -2,7 +2,7 @@ description: Fetch data at build time with `getStaticProps`. --- -# `getStaticPaths` (Static Generation) +# `getStaticPaths`
Version History @@ -14,7 +14,7 @@ description: Fetch data at build time with `getStaticProps`.
-When exporting an `async` function called `getStaticPaths` from a page that uses dynamic routes, Next.js will statically pre-render all the paths specified by `getStaticPaths`. +When exporting an `async` function called `getStaticPaths` (static generation) from a page that uses dynamic routes, Next.js will statically pre-render all the paths specified by `getStaticPaths`. ```jsx export async function getStaticPaths() { diff --git a/docs/api-reference/data-fetching/getStaticProps.md b/docs/api-reference/data-fetching/getStaticProps.md index ba0dfd9b45c09..eea9593163754 100644 --- a/docs/api-reference/data-fetching/getStaticProps.md +++ b/docs/api-reference/data-fetching/getStaticProps.md @@ -2,7 +2,7 @@ description: Fetch data at build time with `getStaticProps`. --- -# `getStaticProps` (Static Generation) +# `getStaticProps`
Version History @@ -15,7 +15,7 @@ description: Fetch data at build time with `getStaticProps`.
-Exporting an `async` function called `getStaticProps` will pre-render a page at build time using the props returned from the function: +Exporting an `async` function called `getStaticProps` (static generation) will pre-render a page at build time using the props returned from the function: ```jsx export async function getStaticProps(context) { diff --git a/docs/basic-features/data-fetching/getServerSideProps.md b/docs/basic-features/data-fetching/getServerSideProps.md index b0cb51c136793..c36ea5a75cfb2 100644 --- a/docs/basic-features/data-fetching/getServerSideProps.md +++ b/docs/basic-features/data-fetching/getServerSideProps.md @@ -2,9 +2,9 @@ description: Fetch data at build time with `getStaticProps` API reference. --- -# `getServerSideProps` (Server-side Rendering) +# `getServerSideProps` -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`. +If you export an `async` function called `getServerSideProps` (server-side rendering) 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) { @@ -16,13 +16,13 @@ export async function getServerSideProps(context) { The [`getServerSideProps` API reference](/docs/api-reference/getServerSideProps.md) covers all parameters and props that can be used with `getServerSideProps`. -### When should I use `getServerSideProps`? +## When should I use `getServerSideProps`? 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`](/docs/data-fetching/getstaticprops.md) because the server must compute the result on every request, and the result cannot be cached by a CDN without extra configuration. If you do not need to pre-render the data, then you should consider fetching data on the [client side](#fetching-data-on-the-client-side). -### TypeScript: Use `GetServerSideProps` +## TypeScript: Use `GetServerSideProps` For TypeScript, you can use the `GetServerSideProps` type from `next`: @@ -59,9 +59,9 @@ function Page({ data }: InferGetServerSidePropsType) export default Page ``` -### Technical details +## Technical details -#### Only runs on server-side +### Only runs on server-side `getServerSideProps` only runs on server-side and never runs on the browser. If a page uses `getServerSideProps`, then: @@ -70,7 +70,7 @@ export default Page You can use [this tool](https://next-code-elimination.vercel.app/) to verify what Next.js eliminates from the client-side bundle. -#### Only allowed in a page +### Only allowed in a page `getServerSideProps` can only be exported from a **page**. You can’t export it from non-page files. diff --git a/docs/basic-features/data-fetching/getStaticPaths.md b/docs/basic-features/data-fetching/getStaticPaths.md index 20cf3aee366b5..d5568ca84fe53 100644 --- a/docs/basic-features/data-fetching/getStaticPaths.md +++ b/docs/basic-features/data-fetching/getStaticPaths.md @@ -2,11 +2,11 @@ description: Fetch data at build time with `getStaticProps` API reference. --- -# `getStaticPaths` (Static Generation) +# `getStaticPaths` If a page has [dynamic routes](/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. -When 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`. +When you export an `async` function called `getStaticPaths` (static generation) from a page that uses dynamic routes, Next.js will statically pre-render all the paths specified by `getStaticPaths`. ```jsx export async function getStaticPaths() { diff --git a/docs/basic-features/data-fetching/getStaticProps.md b/docs/basic-features/data-fetching/getStaticProps.md index ab6c60cfa857a..04991a9ef9cf1 100644 --- a/docs/basic-features/data-fetching/getStaticProps.md +++ b/docs/basic-features/data-fetching/getStaticProps.md @@ -2,9 +2,9 @@ description: Fetch data at build time with `getStaticProps` (Static Generation) API reference. --- -# `getStaticProps` (Static Generation) +# `getStaticProps` -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`. +If you export an `async` function called `getStaticProps` (static generation) from a page, Next.js will pre-render this page at build time using the props returned by `getStaticProps`. ```jsx export async function getStaticProps(context) { From 72c8730d6e1a7e7b742f05c2ea5890e62f7d5d21 Mon Sep 17 00:00:00 2001 From: Rich Haines Date: Tue, 12 Oct 2021 11:05:54 +0200 Subject: [PATCH 03/70] Missing route path --- docs/basic-features/data-fetching/getServerSideProps.md | 4 ++-- docs/basic-features/data-fetching/getStaticPaths.md | 2 +- docs/basic-features/data-fetching/getStaticProps.md | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/basic-features/data-fetching/getServerSideProps.md b/docs/basic-features/data-fetching/getServerSideProps.md index c36ea5a75cfb2..10dd0d74411a9 100644 --- a/docs/basic-features/data-fetching/getServerSideProps.md +++ b/docs/basic-features/data-fetching/getServerSideProps.md @@ -14,11 +14,11 @@ export async function getServerSideProps(context) { } ``` -The [`getServerSideProps` API reference](/docs/api-reference/getServerSideProps.md) covers all parameters and props that can be used with `getServerSideProps`. +The [`getServerSideProps` API reference](/docs/api-reference/data-fetching/getServerSideProps.md) covers all parameters and props that can be used with `getServerSideProps`. ## When should I use `getServerSideProps`? -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`](/docs/data-fetching/getstaticprops.md) because the server must compute the result on every request, and the result cannot be cached by a CDN without extra configuration. +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`](/docs/data-fetching/getStaticProps.md) because the server must compute the result on every request, and the result cannot be cached by a CDN without extra configuration. If you do not need to pre-render the data, then you should consider fetching data on the [client side](#fetching-data-on-the-client-side). diff --git a/docs/basic-features/data-fetching/getStaticPaths.md b/docs/basic-features/data-fetching/getStaticPaths.md index d5568ca84fe53..7a8c538f671d0 100644 --- a/docs/basic-features/data-fetching/getStaticPaths.md +++ b/docs/basic-features/data-fetching/getStaticPaths.md @@ -19,7 +19,7 @@ export async function getStaticPaths() { } ``` -The [`getStaticPaths` API reference](/docs/api-reference/getstaticpaths.md) covers all parameters and props that can be used with `getStaticPaths`. +The [`getStaticPaths` API reference](/docs/api-reference/data-fetching/getStaticPaths.md) covers all parameters and props that can be used with `getStaticPaths`. ## When should I use `getStaticPaths`? diff --git a/docs/basic-features/data-fetching/getStaticProps.md b/docs/basic-features/data-fetching/getStaticProps.md index 04991a9ef9cf1..f5f82e5106d8a 100644 --- a/docs/basic-features/data-fetching/getStaticProps.md +++ b/docs/basic-features/data-fetching/getStaticProps.md @@ -60,7 +60,7 @@ export async function getStaticProps() { export default Blog ``` -The [`getStaticProps` API reference](/docs/api-reference/getStaticProps.md) covers all parameters and props that can be used with `getStaticProps`. +The [`getStaticProps` API reference](/docs/api-reference/data-fetching/getStaticProps.md) covers all parameters and props that can be used with `getStaticProps`. ## Technical details From bf621341a56bf1f1f09dde12f1cb0f24bd11e600 Mon Sep 17 00:00:00 2001 From: Rich Haines Date: Tue, 12 Oct 2021 11:13:29 +0200 Subject: [PATCH 04/70] Data fetching route was missing --- docs/manifest.json | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/manifest.json b/docs/manifest.json index fa985437bec9f..f6db938b2db75 100644 --- a/docs/manifest.json +++ b/docs/manifest.json @@ -21,6 +21,10 @@ "permanent": true }, "routes": [ + { + "title": "Data Fetching Overview", + "path": "/docs/basic-features/data-fetching/data-fetching.md" + }, { "title": "getServerSideProps", "path": "/docs/basic-features/data-fetching/getServerSideProps.md" From a4f471fda57493558190696ef3f6cdf67e8b6963 Mon Sep 17 00:00:00 2001 From: Rich Haines Date: Tue, 12 Oct 2021 11:16:37 +0200 Subject: [PATCH 05/70] Changed title of data fetching sidenav item --- docs/basic-features/data-fetching/data-fetching.md | 2 +- docs/manifest.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/basic-features/data-fetching/data-fetching.md b/docs/basic-features/data-fetching/data-fetching.md index cf4be5edca29d..933ec6bf2ad8a 100644 --- a/docs/basic-features/data-fetching/data-fetching.md +++ b/docs/basic-features/data-fetching/data-fetching.md @@ -2,7 +2,7 @@ description: 'Data fetching in Next.js allows you to render your content in different ways, depending on your applications use case. These include pre-rendering with server-side rendering or static-site generation, and incremental static regeneration. Learn how to manage your application data in Next.js.' --- -# Data Fetching +# Data Fetching Overview
Examples diff --git a/docs/manifest.json b/docs/manifest.json index f6db938b2db75..fec1df9a8c90c 100644 --- a/docs/manifest.json +++ b/docs/manifest.json @@ -22,7 +22,7 @@ }, "routes": [ { - "title": "Data Fetching Overview", + "title": "Overview", "path": "/docs/basic-features/data-fetching/data-fetching.md" }, { From 363da6043016455c7913e2eacc020a84d3a2883f Mon Sep 17 00:00:00 2001 From: Rich Haines Date: Tue, 12 Oct 2021 13:49:41 +0200 Subject: [PATCH 06/70] inline codeblocks --- docs/api-reference/data-fetching/getServerSideProps.md | 6 +++--- docs/api-reference/data-fetching/getStaticPaths.md | 4 ++-- docs/api-reference/data-fetching/getStaticProps.md | 6 +++--- docs/basic-features/data-fetching/data-fetching.md | 4 ++-- docs/basic-features/data-fetching/getServerSideProps.md | 6 +++--- docs/basic-features/data-fetching/getStaticPaths.md | 2 +- docs/basic-features/data-fetching/getStaticProps.md | 8 ++++---- 7 files changed, 18 insertions(+), 18 deletions(-) diff --git a/docs/api-reference/data-fetching/getServerSideProps.md b/docs/api-reference/data-fetching/getServerSideProps.md index 8b9a3fa96d7c7..732f7f9f766ec 100644 --- a/docs/api-reference/data-fetching/getServerSideProps.md +++ b/docs/api-reference/data-fetching/getServerSideProps.md @@ -27,12 +27,12 @@ export async function getServerSideProps(context) { You can import modules in top-level scope for use in `getServerSideProps`. Imports used will [**not be bundled for the client-side**](#write-server-side-code-directly). This means you can write **server-side code directly in `getServerSideProps`**, including reading from the filesystem or a database. -You should not use the [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) API to call an [API route](/docs/api-routes/introduction.md) in `getServerSideProps`. +You should not use the [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) `API` to call an [API route](/docs/api-routes/introduction.md) in `getServerSideProps`. -Instead, directly import the logic used inside your API route. +Instead, directly import the logic used inside your `API` route. You may need to slightly refactor your code for this approach. -The `fetch()` API _can_ be used to fetch external data, such as from a Content Management System (CMS) or API. +The `fetch()` `API` _can_ be used to fetch external data, such as from a Content Management System (CMS) or `API`. ## Context parameter diff --git a/docs/api-reference/data-fetching/getStaticPaths.md b/docs/api-reference/data-fetching/getStaticPaths.md index cebc44542af81..2d581e0134482 100644 --- a/docs/api-reference/data-fetching/getStaticPaths.md +++ b/docs/api-reference/data-fetching/getStaticPaths.md @@ -127,7 +127,7 @@ Shortly after, `getStaticProps` finishes and the page will be rendered with the This ensures that users always have a fast experience while preserving fast builds and the benefits of Static Generation. -`fallback: true` will not _update_ generated pages, for that take a look at [Incremental Static Regeneration](/docs/basic-features/data-fetching/index#incremental-static-regeneration). +`fallback: true` will not _update_ generated pages, for that take a look at [Incremental Static Regeneration](/docs/basic-features/data-fetching/data-fetching#incremental-static-regeneration). ### `fallback: 'blocking'` @@ -140,7 +140,7 @@ If `fallback` is `'blocking'`, new paths not returned by `getStaticPaths` will w - When complete, the browser receives the `HTML` for the generated path. From the user’s perspective, it will transition from "the browser is requesting the page" to "the full page is loaded". There is no flash of loading/fallback state. - 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: 'blocking'` will not _update_ generated pages by default. To update generated pages, use [Incremental Static Regeneration](/docs/basic-features/data-fetching/index#incremental-static-regeneration) in conjunction with `fallback: 'blocking'`. +`fallback: 'blocking'` will not _update_ generated pages by default. To update generated pages, use [Incremental Static Regeneration](/docs/basic-features/data-fetching/data-fetching#incremental-static-regeneration) in conjunction with `fallback: 'blocking'`. > `fallback: 'blocking'` is not supported when using [`next export`](/docs/advanced-features/static-html-export.md). diff --git a/docs/api-reference/data-fetching/getStaticProps.md b/docs/api-reference/data-fetching/getStaticProps.md index eea9593163754..c0530cbaf4e2f 100644 --- a/docs/api-reference/data-fetching/getStaticProps.md +++ b/docs/api-reference/data-fetching/getStaticProps.md @@ -28,12 +28,12 @@ export async function getStaticProps(context) { You can import modules in top-level scope for use in `getStaticProps`. Imports used will [**not be bundled for the client-side**](#write-server-side-code-directly). This means you can write **server-side code directly in `getStaticProps`**, including reading from the filesystem or a database. -You should not use the [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) API to call an [API route](/docs/api-routes/introduction.md) in `getStaticProps`. +You should not use the [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) `API` to call an [`API` route](/docs/api-routes/introduction.md) in `getStaticProps`. -Instead, directly import the logic used inside your API route. +Instead, directly import the logic used inside your `API` route. You may need to slightly refactor your code for this approach. -The `fetch()` API _can_ be used to fetch external data, such as from a Content Management System (CMS) or API. +The `fetch()` `API` _can_ be used to fetch external data, such as from a Content Management System (CMS) or `API`. ## Context parameter diff --git a/docs/basic-features/data-fetching/data-fetching.md b/docs/basic-features/data-fetching/data-fetching.md index 933ec6bf2ad8a..f508d64e494af 100644 --- a/docs/basic-features/data-fetching/data-fetching.md +++ b/docs/basic-features/data-fetching/data-fetching.md @@ -119,11 +119,11 @@ When a request is made to a page that was pre-rendered at build time, it will in When a request is made to a path that hasn’t been generated, Next.js will server-render the page on the first request. Future requests will serve the static file from the cache. -To learn how to persist the cache globally and handle rollbacks, learn more about [Incremental Static Regeneration](https://vercel.com/docs/next.js/incremental-static-regeneration). +[Incremental Static Regeneration](https://vercel.com/docs/next.js/incremental-static-regeneration) covers how to persist the cache globally and handle rollbacks. ## SWR -The team behind Next.js has created a React hook for data fetching called [**SWR**](https://swr.vercel.app/). 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 you can use it like so: +The team behind Next.js has created a React hook for data fetching called [**SWR**](https://swr.vercel.app/). It is highly recommend if you are fetching data on the client side. It handles caching, revalidation, focus tracking, refetching on interval, and more. ```jsx import useSWR from 'swr' diff --git a/docs/basic-features/data-fetching/getServerSideProps.md b/docs/basic-features/data-fetching/getServerSideProps.md index 10dd0d74411a9..3a76290fdd7b0 100644 --- a/docs/basic-features/data-fetching/getServerSideProps.md +++ b/docs/basic-features/data-fetching/getServerSideProps.md @@ -18,7 +18,7 @@ The [`getServerSideProps` API reference](/docs/api-reference/data-fetching/getSe ## When should I use `getServerSideProps`? -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`](/docs/data-fetching/getStaticProps.md) because the server must compute the result on every request, and the result cannot be cached by a CDN without extra configuration. +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`](/docs/basic-features/data-fetching/getStaticProps.md) because the server must compute the result on every request, and the result cannot be cached by a CDN without extra configuration. If you do not need to pre-render the data, then you should consider fetching data on the [client side](#fetching-data-on-the-client-side). @@ -34,7 +34,7 @@ export const getServerSideProps: GetServerSideProps = async (context) => { } ``` -If you want to get inferred typings for your props, you can use `InferGetServerSidePropsType`, like this: +If you want to get inferred typings for your props, you can use `InferGetServerSidePropsType`: ```tsx import { InferGetServerSidePropsType } from 'next' @@ -66,7 +66,7 @@ export default Page `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)) or `next/router` ([documentation](/docs/api-reference/next/router.md)), Next.js sends an API request to the server, which runs `getServerSideProps`. It’ll return 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)) or `next/router` ([documentation](/docs/api-reference/next/router.md)), Next.js sends an `API` request to the server, which runs `getServerSideProps`. It’ll return `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. You can use [this tool](https://next-code-elimination.vercel.app/) to verify what Next.js eliminates from the client-side bundle. diff --git a/docs/basic-features/data-fetching/getStaticPaths.md b/docs/basic-features/data-fetching/getStaticPaths.md index 7a8c538f671d0..7032835e0b056 100644 --- a/docs/basic-features/data-fetching/getStaticPaths.md +++ b/docs/basic-features/data-fetching/getStaticPaths.md @@ -31,7 +31,7 @@ You should use `getStaticPaths` if you’re statically pre-rendering pages that When you use `getStaticProps` on a page with dynamic route parameters, you **must** use `getStaticPaths`. -Note that you **cannot** use `getStaticPaths` with [`getServerSideProps`](/docs/data-fetching/getServerSideProps.md). +Note that you **cannot** use `getStaticPaths` with [`getServerSideProps`](/docs/basic-features/data-fetching/getServerSideProps.md). ### Only runs at build time on server-side diff --git a/docs/basic-features/data-fetching/getStaticProps.md b/docs/basic-features/data-fetching/getStaticProps.md index f5f82e5106d8a..89faec8e4f99e 100644 --- a/docs/basic-features/data-fetching/getStaticProps.md +++ b/docs/basic-features/data-fetching/getStaticProps.md @@ -21,7 +21,7 @@ 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 a 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. +- 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. ## Using `getStaticProps` to fetch data from a CMS @@ -66,11 +66,11 @@ The [`getStaticProps` API reference](/docs/api-reference/data-fetching/getStatic ### 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. +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`. @@ -78,7 +78,7 @@ You can use the [next-code-elimination tool](https://next-code-elimination.verce ### 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`. +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`](/docs/api-reference/next/link.md) or [`next/router`](/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. From 45192e1a57c1905e19186e8d24c048aef77a6224 Mon Sep 17 00:00:00 2001 From: molebox Date: Fri, 29 Oct 2021 11:21:24 +0200 Subject: [PATCH 07/70] Conflicts - rebase on canary continue --- docs/manifest.json | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/docs/manifest.json b/docs/manifest.json index fec1df9a8c90c..a6d36db847ed3 100644 --- a/docs/manifest.json +++ b/docs/manifest.json @@ -43,6 +43,10 @@ "title": "Built-in CSS Support", "path": "/docs/basic-features/built-in-css-support.md" }, + { + "title": "Layouts", + "path": "/docs/basic-features/layouts.md" + }, { "title": "Image Optimization", "path": "/docs/basic-features/image-optimization.md" @@ -139,6 +143,10 @@ "title": "Authentication", "path": "/docs/authentication.md" }, + { + "title": "Testing", + "path": "/docs/testing.md" + }, { "title": "Advanced Features", "routes": [ @@ -410,6 +418,10 @@ "title": "Disabling ETag Generation", "path": "/docs/api-reference/next.config.js/disabling-etag-generation.md" }, + { + "title": "Disabling HTTP Keep-Alive", + "path": "/docs/api-reference/next.config.js/disabling-http-keep-alive.md" + }, { "title": "Setting a custom build directory", "path": "/docs/api-reference/next.config.js/setting-a-custom-build-directory.md" From 16a6afceadb6ece36b43f0200d9010fadeeac59d Mon Sep 17 00:00:00 2001 From: molebox Date: Fri, 29 Oct 2021 12:39:21 +0200 Subject: [PATCH 08/70] Moved TS to top level of main pages --- .../data-fetching/getStaticPaths.md | 12 ------ .../data-fetching/getStaticProps.md | 40 ------------------- .../data-fetching/getStaticPaths.md | 12 ++++++ .../data-fetching/getStaticProps.md | 40 +++++++++++++++++++ 4 files changed, 52 insertions(+), 52 deletions(-) diff --git a/docs/api-reference/data-fetching/getStaticPaths.md b/docs/api-reference/data-fetching/getStaticPaths.md index 2d581e0134482..c3b10db6eec55 100644 --- a/docs/api-reference/data-fetching/getStaticPaths.md +++ b/docs/api-reference/data-fetching/getStaticPaths.md @@ -198,15 +198,3 @@ export async function getStaticProps({ params }) { export default Post ``` - -## TypeScript: Use `GetStaticPaths` - -For TypeScript, you can use the `GetStaticPaths` type from `next`: - -```ts -import { GetStaticPaths } from 'next' - -export const getStaticPaths: GetStaticPaths = async () => { - // ... -} -``` diff --git a/docs/api-reference/data-fetching/getStaticProps.md b/docs/api-reference/data-fetching/getStaticProps.md index c0530cbaf4e2f..3258be6bbcfba 100644 --- a/docs/api-reference/data-fetching/getStaticProps.md +++ b/docs/api-reference/data-fetching/getStaticProps.md @@ -137,46 +137,6 @@ export async function getStaticProps(context) { Redirecting at build-time is currently not allowed and if the redirects are known at build-time they should be added in [`next.config.js`](/docs/api-reference/next.config.js/redirects.md). -## TypeScript: Use `GetStaticProps` - -You can use the `GetStaticProps` type from `next` to type the function: - -```ts -import { GetStaticProps } from 'next' - -export const getStaticProps: GetStaticProps = async (context) => { - // ... -} -``` - -If you want to get inferred typings for your props, you can use `InferGetStaticPropsType`: - -```tsx -import { InferGetStaticPropsType } from 'next' - -type Post = { - author: string - content: string -} - -export const getStaticProps = async () => { - const res = await fetch('https://.../posts') - const posts: Post[] = await res.json() - - return { - props: { - posts, - }, - } -} - -function Blog({ posts }: InferGetStaticPropsType) { - // will resolve posts to type Post[] -} - -export default Blog -``` - ## Reading files: Use `process.cwd()` Files can be read directly from the filesystem in `getStaticProps`. diff --git a/docs/basic-features/data-fetching/getStaticPaths.md b/docs/basic-features/data-fetching/getStaticPaths.md index 7032835e0b056..783c5b11007ff 100644 --- a/docs/basic-features/data-fetching/getStaticPaths.md +++ b/docs/basic-features/data-fetching/getStaticPaths.md @@ -25,6 +25,18 @@ The [`getStaticPaths` API reference](/docs/api-reference/data-fetching/getStatic You should use `getStaticPaths` if you’re statically pre-rendering pages that use dynamic routes. +## TypeScript: Use `GetStaticPaths` + +For TypeScript, you can use the `GetStaticPaths` type from `next`: + +```ts +import { GetStaticPaths } from 'next' + +export const getStaticPaths: GetStaticPaths = async () => { + // ... +} +``` + ## Technical details ### Use together with [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) diff --git a/docs/basic-features/data-fetching/getStaticProps.md b/docs/basic-features/data-fetching/getStaticProps.md index 89faec8e4f99e..b82664cc74912 100644 --- a/docs/basic-features/data-fetching/getStaticProps.md +++ b/docs/basic-features/data-fetching/getStaticProps.md @@ -23,6 +23,46 @@ 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. +## TypeScript: Use `GetStaticProps` + +You can use the `GetStaticProps` type from `next` to type the function: + +```ts +import { GetStaticProps } from 'next' + +export const getStaticProps: GetStaticProps = async (context) => { + // ... +} +``` + +If you want to get inferred typings for your props, you can use `InferGetStaticPropsType`: + +```tsx +import { InferGetStaticPropsType } from 'next' + +type Post = { + author: string + content: string +} + +export const getStaticProps = async () => { + const res = await fetch('https://.../posts') + const posts: Post[] = await res.json() + + return { + props: { + posts, + }, + } +} + +function Blog({ posts }: InferGetStaticPropsType) { + // will resolve posts to type Post[] +} + +export default Blog +``` + ## Using `getStaticProps` to fetch data from a CMS The following example shows how you can fetch a list of blog posts from a CMS. From f7f60e80e355a30e9159d727c5ee268545a0dcfd Mon Sep 17 00:00:00 2001 From: molebox Date: Tue, 2 Nov 2021 10:03:34 +0100 Subject: [PATCH 09/70] Pulled out ISR and SWR, added cards, fixed routes --- .../data-fetching/getInitialProps.md | 2 +- .../data-fetching/data-fetching.md | 165 ------------------ docs/manifest.json | 14 +- 3 files changed, 12 insertions(+), 169 deletions(-) delete mode 100644 docs/basic-features/data-fetching/data-fetching.md diff --git a/docs/api-reference/data-fetching/getInitialProps.md b/docs/api-reference/data-fetching/getInitialProps.md index 7df96387f9982..565f1cb5b4983 100644 --- a/docs/api-reference/data-fetching/getInitialProps.md +++ b/docs/api-reference/data-fetching/getInitialProps.md @@ -8,7 +8,7 @@ description: Enable Server-Side Rendering in a page and do initial data populati > > If you're using Next.js 9.3 or newer, we recommend that you use `getStaticProps` or `getServerSideProps` instead of `getInitialProps`. > -> These new data fetching methods allow you to have a granular choice between static generation and server-side rendering. Learn more on the documentation for [Pages](/docs/basic-features/pages.md) and [Data Fetching](/docs/basic-features/data-fetching/data-fetching.md). +> These new data fetching methods allow you to have a granular choice between static generation and server-side rendering. Learn more on the documentation for [Pages](/docs/basic-features/pages.md) and [Data Fetching](/docs/basic-features/data-fetching/index.md). `getInitialProps` enables [server-side rendering](/docs/basic-features/pages.md#server-side-rendering) in a page and allows you to do **initial data population**, it means sending the [page](/docs/basic-features/pages.md) with the data already populated from the server. This is especially useful for [SEO](https://en.wikipedia.org/wiki/Search_engine_optimization). diff --git a/docs/basic-features/data-fetching/data-fetching.md b/docs/basic-features/data-fetching/data-fetching.md deleted file mode 100644 index f508d64e494af..0000000000000 --- a/docs/basic-features/data-fetching/data-fetching.md +++ /dev/null @@ -1,165 +0,0 @@ ---- -description: 'Data fetching in Next.js allows you to render your content in different ways, depending on your applications use case. These include pre-rendering with server-side rendering or static-site generation, and incremental static regeneration. Learn how to manage your application data in Next.js.' ---- - -# Data Fetching Overview - -
- Examples - -
- -The [Pages documentation](/docs/basic-features/pages.md) explained that Next.js has two forms of pre-rendering: **Static Generation** and **Server-side Rendering**. In the sections below, you will learn about data fetching strategies for each case. - -It is recommended that you [read through the Pages documentation](/docs/basic-features/pages.md) first if you have not already done so. - -The three unique Next.js functions you can use to fetch data for pre-rendering are: - -- [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) (Static Generation): Fetch data at **build time**. -- [`getStaticPaths`](/docs/basic-features/data-fetching/getStaticPaths.md) (Static Generation): Specify [dynamic routes](/docs/routing/dynamic-routes.md) to pre-render pages based on data. -- [`getServerSideProps`](/docs/basic-features/data-fetching/getServerSideProps.md) (Server-side Rendering): Fetch data on **each request**. - -## Incremental Static Regeneration - -
- Examples - -
- -
- Version History - -| Version | Changes | -| -------- | ---------------- | -| `v9.5.0` | Base Path added. | - -
- -Next.js allows you to create or update static pages _after_ you’ve built your site. Incremental Static Regeneration (ISR) enables you to use static-generation on a per-page basis, **without needing to rebuild the entire site**. With ISR, you can retain the benefits of static while scaling to millions of pages. - -The following example shows how to use the `revalidate` property: - -```jsx -function Blog({ posts }) { - return ( -
    - {posts.map((post) => ( -
  • {post.title}
  • - ))} -
- ) -} - -// This function gets called at build time on server-side. -// It may be called again, on a serverless function, if -// revalidation is enabled and a new request comes in -export async function getStaticProps() { - const res = await fetch('https://.../posts') - const posts = await res.json() - - return { - props: { - posts, - }, - // Next.js will attempt to re-generate the page: - // - When a request comes in - // - At most once every 10 seconds - revalidate: 10, // In seconds - } -} - -// This function gets called at build time on server-side. -// It may be called again, on a serverless function, if -// the path has not been generated. -export async function getStaticPaths() { - 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) => ({ - params: { id: post.id }, - })) - - // We'll pre-render only these paths at build time. - // { fallback: blocking } will server-render pages - // on-demand if the path doesn't exist. - return { paths, fallback: 'blocking' } -} - -export default Blog -``` - -When a request is made to a page that was pre-rendered at build time, it will initially show the cached page. - -- Any requests to the page after the initial request and before 10 seconds are also cached and instantaneous. -- After the 10-second window, the next request will still show the cached (stale) page -- Next.js triggers a regeneration of the page in the background. -- Once the page has been successfully generated, Next.js will invalidate the cache and show the updated product page. If the background regeneration fails, the old page remains unaltered. - -When a request is made to a path that hasn’t been generated, Next.js will server-render the page on the first request. Future requests will serve the static file from the cache. - -[Incremental Static Regeneration](https://vercel.com/docs/next.js/incremental-static-regeneration) covers how to persist the cache globally and handle rollbacks. - -## SWR - -The team behind Next.js has created a React hook for data fetching called [**SWR**](https://swr.vercel.app/). It is highly recommend if you are fetching data on the client side. It handles caching, revalidation, focus tracking, refetching on interval, and more. - -```jsx -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.vercel.app/). - -## Learn more - -We recommend you to read the following sections next: - - - - - - diff --git a/docs/manifest.json b/docs/manifest.json index a6d36db847ed3..06072475c14e5 100644 --- a/docs/manifest.json +++ b/docs/manifest.json @@ -17,13 +17,13 @@ "title": "Data Fetching", "path": "/docs/basic-features/data-fetching.md", "redirect": { - "destination": "/docs/basic-features/data-fetching/data-fetching.md", + "destination": "/docs/basic-features/data-fetching/index.md", "permanent": true }, "routes": [ { "title": "Overview", - "path": "/docs/basic-features/data-fetching/data-fetching.md" + "path": "/docs/basic-features/data-fetching/index.md" }, { "title": "getServerSideProps", @@ -36,6 +36,14 @@ { "title": "getStaticProps", "path": "/docs/basic-features/data-fetching/getStaticProps.md" + }, + { + "title": "Incremental Static Regeneration", + "path": "/docs/basic-features/data-fetching/incremental-static-regeneration.md" + }, + { + "title": "SWR", + "path": "/docs/basic-features/data-fetching/swr.md" } ] }, @@ -80,7 +88,7 @@ "path": "/docs/basic-features/supported-browsers-features.md" }, { - "title": "Script", + "title": "Handling Script", "path": "/docs/basic-features/script.md" } ] From 91376698dc64324261c39ad1e8e71c28b8945229 Mon Sep 17 00:00:00 2001 From: molebox Date: Tue, 2 Nov 2021 10:04:14 +0100 Subject: [PATCH 10/70] Pulled out ISR and SWR, added cards, fixed routes --- .../incremental-static-regeneration.md | 88 +++++++++++++++++++ docs/basic-features/data-fetching/index.md | 87 ++++++++++++++++++ docs/basic-features/data-fetching/swr.md | 21 +++++ 3 files changed, 196 insertions(+) create mode 100644 docs/basic-features/data-fetching/incremental-static-regeneration.md create mode 100644 docs/basic-features/data-fetching/index.md create mode 100644 docs/basic-features/data-fetching/swr.md diff --git a/docs/basic-features/data-fetching/incremental-static-regeneration.md b/docs/basic-features/data-fetching/incremental-static-regeneration.md new file mode 100644 index 0000000000000..e82c8053f779a --- /dev/null +++ b/docs/basic-features/data-fetching/incremental-static-regeneration.md @@ -0,0 +1,88 @@ +--- +description: 'Learn how to create or update static pages at runtime with Incremental Static Regeneration.' +--- + +# Incremental Static Regeneration + +
+ Examples + +
+ +
+ Version History + +| Version | Changes | +| -------- | ---------------- | +| `v9.5.0` | Base Path added. | + +
+ +Next.js allows you to create or update static pages _after_ you’ve built your site. Incremental Static Regeneration (ISR) enables you to use static-generation on a per-page basis, **without needing to rebuild the entire site**. With ISR, you can retain the benefits of static while scaling to millions of pages. + +To use ISR add the `revalidate` prop to `getStaticProps`: + +```jsx +function Blog({ posts }) { + return ( +
    + {posts.map((post) => ( +
  • {post.title}
  • + ))} +
+ ) +} + +// This function gets called at build time on server-side. +// It may be called again, on a serverless function, if +// revalidation is enabled and a new request comes in +export async function getStaticProps() { + const res = await fetch('https://.../posts') + const posts = await res.json() + + return { + props: { + posts, + }, + // Next.js will attempt to re-generate the page: + // - When a request comes in + // - At most once every 10 seconds + revalidate: 10, // In seconds + } +} + +// This function gets called at build time on server-side. +// It may be called again, on a serverless function, if +// the path has not been generated. +export async function getStaticPaths() { + 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) => ({ + params: { id: post.id }, + })) + + // We'll pre-render only these paths at build time. + // { fallback: blocking } will server-render pages + // on-demand if the path doesn't exist. + return { paths, fallback: 'blocking' } +} + +export default Blog +``` + +When a request is made to a page that was pre-rendered at build time, it will initially show the cached page. + +- Any requests to the page after the initial request and before 10 seconds are also cached and instantaneous. +- After the 10-second window, the next request will still show the cached (stale) page +- Next.js triggers a regeneration of the page in the background. +- Once the page has been successfully generated, Next.js will invalidate the cache and show the updated product page. If the background regeneration fails, the old page remains unaltered. + +When a request is made to a path that hasn’t been generated, Next.js will server-render the page on the first request. Future requests will serve the static file from the cache. + +[Incremental Static Regeneration](https://vercel.com/docs/next.js/incremental-static-regeneration) covers how to persist the cache globally and handle rollbacks. diff --git a/docs/basic-features/data-fetching/index.md b/docs/basic-features/data-fetching/index.md new file mode 100644 index 0000000000000..a1906a96d5a1a --- /dev/null +++ b/docs/basic-features/data-fetching/index.md @@ -0,0 +1,87 @@ +--- +description: 'Data fetching in Next.js allows you to render your content in different ways, depending on your applications use case. These include pre-rendering with server-side rendering or static-site generation, and incremental static regeneration. Learn how to manage your application data in Next.js.' +--- + +# Data Fetching Overview + +
+ Examples + +
+ +Data fetching in Next.js allows you to render your content in different ways, depending on your applications use case. These include pre-rendering with **Server-side Rendering** or **Static Generation**, and updating or creating content at runtime with **Incremental Static Regeneration**. + + + + + + + + + + + +## Learn more + + + + + + diff --git a/docs/basic-features/data-fetching/swr.md b/docs/basic-features/data-fetching/swr.md new file mode 100644 index 0000000000000..750fe10c8e8ef --- /dev/null +++ b/docs/basic-features/data-fetching/swr.md @@ -0,0 +1,21 @@ +--- +description: 'Learn how to use SWR, a data fetching React hook that handles caching, revalidation, focus tracking, refetching on interval and more.' +--- + +# SWR + +The team behind Next.js has created a React hook for data fetching called [**SWR**](https://swr.vercel.app/). It is highly recommend if you are fetching data on the client side. It handles caching, revalidation, focus tracking, refetching on interval, and more. + +```jsx +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.vercel.app/). From 02f6e4d2f03f8b330ce8fedcdcdc1cc892de495e Mon Sep 17 00:00:00 2001 From: molebox Date: Fri, 12 Nov 2021 10:12:39 +0100 Subject: [PATCH 11/70] Removed redirect, moved to next-site --- docs/manifest.json | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/docs/manifest.json b/docs/manifest.json index 06072475c14e5..7acf3474f65e4 100644 --- a/docs/manifest.json +++ b/docs/manifest.json @@ -15,11 +15,7 @@ }, { "title": "Data Fetching", - "path": "/docs/basic-features/data-fetching.md", - "redirect": { - "destination": "/docs/basic-features/data-fetching/index.md", - "permanent": true - }, + "path": "/docs/basic-features/data-fetching/index.md", "routes": [ { "title": "Overview", From 7579859934de5def2a8515abe8e42db506833d41 Mon Sep 17 00:00:00 2001 From: molebox Date: Fri, 12 Nov 2021 15:05:05 +0100 Subject: [PATCH 12/70] conflicts --- .../data-fetching/getInitialProps.md | 5 + .../data-fetching/getServerSideProps.md | 25 ++- .../data-fetching/getStaticPaths.md | 39 +++++ .../data-fetching/getStaticProps.md | 69 +++++++- .../data-fetching/data-fetching.md | 165 ++++++++++++++++++ .../data-fetching/getServerSideProps.md | 50 +++++- .../data-fetching/getStaticPaths.md | 28 ++- .../data-fetching/getStaticProps.md | 37 +++- docs/manifest.json | 14 +- 9 files changed, 413 insertions(+), 19 deletions(-) create mode 100644 docs/basic-features/data-fetching/data-fetching.md diff --git a/docs/api-reference/data-fetching/getInitialProps.md b/docs/api-reference/data-fetching/getInitialProps.md index 565f1cb5b4983..e0b10f8d01765 100644 --- a/docs/api-reference/data-fetching/getInitialProps.md +++ b/docs/api-reference/data-fetching/getInitialProps.md @@ -8,7 +8,12 @@ description: Enable Server-Side Rendering in a page and do initial data populati > > If you're using Next.js 9.3 or newer, we recommend that you use `getStaticProps` or `getServerSideProps` instead of `getInitialProps`. > +> <<<<<<< HEAD > These new data fetching methods allow you to have a granular choice between static generation and server-side rendering. Learn more on the documentation for [Pages](/docs/basic-features/pages.md) and [Data Fetching](/docs/basic-features/data-fetching/index.md). +> ======= +> These new data fetching methods allow you to have a granular choice between static generation and server-side rendering. Learn more on the documentation for [Pages](/docs/basic-features/pages.md) and [Data Fetching](/docs/basic-features/data-fetching/data-fetching.md). +> +> > > > > > > 1d3d662c4 (merge conflicts) `getInitialProps` enables [server-side rendering](/docs/basic-features/pages.md#server-side-rendering) in a page and allows you to do **initial data population**, it means sending the [page](/docs/basic-features/pages.md) with the data already populated from the server. This is especially useful for [SEO](https://en.wikipedia.org/wiki/Search_engine_optimization). diff --git a/docs/api-reference/data-fetching/getServerSideProps.md b/docs/api-reference/data-fetching/getServerSideProps.md index 732f7f9f766ec..dd69927eed9b6 100644 --- a/docs/api-reference/data-fetching/getServerSideProps.md +++ b/docs/api-reference/data-fetching/getServerSideProps.md @@ -2,8 +2,16 @@ description: Fetch data on each request with `getServerSideProps`. Learn more about this API for data fetching in Next.js. --- +<<<<<<< HEAD + # `getServerSideProps` +======= + +# `getServerSideProps` (Server-side Rendering) + +> > > > > > > 1d3d662c4 (merge conflicts) +
Version History @@ -14,7 +22,12 @@ description: Fetch data on each request with `getServerSideProps`. Learn more ab
+<<<<<<< HEAD When exporting an `async` function called `getServerSideProps` (server-side rendering) from a page, Next.js will pre-render this page on each request using the data returned by `getServerSideProps`. +======= +When exporting an `async` function called `getServerSideProps` from a page, Next.js will pre-render this page on each request using the data returned by `getServerSideProps`. + +> > > > > > > 1d3d662c4 (merge conflicts) ```js export async function getServerSideProps(context) { @@ -27,12 +40,22 @@ export async function getServerSideProps(context) { You can import modules in top-level scope for use in `getServerSideProps`. Imports used will [**not be bundled for the client-side**](#write-server-side-code-directly). This means you can write **server-side code directly in `getServerSideProps`**, including reading from the filesystem or a database. +<<<<<<< HEAD You should not use the [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) `API` to call an [API route](/docs/api-routes/introduction.md) in `getServerSideProps`. Instead, directly import the logic used inside your `API` route. You may need to slightly refactor your code for this approach. -The `fetch()` `API` _can_ be used to fetch external data, such as from a Content Management System (CMS) or `API`. +# The `fetch()` `API` _can_ be used to fetch external data, such as from a Content Management System (CMS) or `API`. + +You should not use the [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) API to call an [API route](/docs/api-routes/introduction.md) in `getServerSideProps`. + +Instead, directly import the logic used inside your API route. +You may need to slightly refactor your code for this approach. + +The `fetch()` API _can_ be used to fetch external data, such as from a Content Management System (CMS) or API. + +> > > > > > > 1d3d662c4 (merge conflicts) ## Context parameter diff --git a/docs/api-reference/data-fetching/getStaticPaths.md b/docs/api-reference/data-fetching/getStaticPaths.md index c3b10db6eec55..058b4d7b0af63 100644 --- a/docs/api-reference/data-fetching/getStaticPaths.md +++ b/docs/api-reference/data-fetching/getStaticPaths.md @@ -2,8 +2,16 @@ description: Fetch data at build time with `getStaticProps`. --- +<<<<<<< HEAD + # `getStaticPaths` +======= + +# `getStaticPaths` (Static Generation) + +> > > > > > > 1d3d662c4 (merge conflicts) +
Version History @@ -14,7 +22,12 @@ description: Fetch data at build time with `getStaticProps`.
+<<<<<<< HEAD When exporting an `async` function called `getStaticPaths` (static generation) from a page that uses dynamic routes, Next.js will statically pre-render all the paths specified by `getStaticPaths`. +======= +When exporting an `async` function called `getStaticPaths` from a page that uses dynamic routes, Next.js will statically pre-render all the paths specified by `getStaticPaths`. + +> > > > > > > 1d3d662c4 (merge conflicts) ```jsx export async function getStaticPaths() { @@ -127,7 +140,12 @@ Shortly after, `getStaticProps` finishes and the page will be rendered with the This ensures that users always have a fast experience while preserving fast builds and the benefits of Static Generation. +<<<<<<< HEAD `fallback: true` will not _update_ generated pages, for that take a look at [Incremental Static Regeneration](/docs/basic-features/data-fetching/data-fetching#incremental-static-regeneration). +======= +`fallback: true` will not _update_ generated pages, for that take a look at [Incremental Static Regeneration](/docs/basic-features/data-fetching/index#incremental-static-regeneration). + +> > > > > > > 1d3d662c4 (merge conflicts) ### `fallback: 'blocking'` @@ -140,7 +158,12 @@ If `fallback` is `'blocking'`, new paths not returned by `getStaticPaths` will w - When complete, the browser receives the `HTML` for the generated path. From the user’s perspective, it will transition from "the browser is requesting the page" to "the full page is loaded". There is no flash of loading/fallback state. - 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. +<<<<<<< HEAD `fallback: 'blocking'` will not _update_ generated pages by default. To update generated pages, use [Incremental Static Regeneration](/docs/basic-features/data-fetching/data-fetching#incremental-static-regeneration) in conjunction with `fallback: 'blocking'`. +======= +`fallback: 'blocking'` will not _update_ generated pages by default. To update generated pages, use [Incremental Static Regeneration](/docs/basic-features/data-fetching/index#incremental-static-regeneration) in conjunction with `fallback: 'blocking'`. + +> > > > > > > 1d3d662c4 (merge conflicts) > `fallback: 'blocking'` is not supported when using [`next export`](/docs/advanced-features/static-html-export.md). @@ -198,3 +221,19 @@ export async function getStaticProps({ params }) { export default Post ``` + +# <<<<<<< HEAD + +## TypeScript: Use `GetStaticPaths` + +For TypeScript, you can use the `GetStaticPaths` type from `next`: + +```ts +import { GetStaticPaths } from 'next' + +export const getStaticPaths: GetStaticPaths = async () => { + // ... +} +``` + +> > > > > > > 1d3d662c4 (merge conflicts) diff --git a/docs/api-reference/data-fetching/getStaticProps.md b/docs/api-reference/data-fetching/getStaticProps.md index 3258be6bbcfba..4fbd8c434dbe9 100644 --- a/docs/api-reference/data-fetching/getStaticProps.md +++ b/docs/api-reference/data-fetching/getStaticProps.md @@ -2,8 +2,16 @@ description: Fetch data at build time with `getStaticProps`. --- +<<<<<<< HEAD + # `getStaticProps` +======= + +# `getStaticProps` (Static Generation) + +> > > > > > > 1d3d662c4 (merge conflicts) +
Version History @@ -15,7 +23,12 @@ description: Fetch data at build time with `getStaticProps`.
+<<<<<<< HEAD Exporting an `async` function called `getStaticProps` (static generation) will pre-render a page at build time using the props returned from the function: +======= +Exporting an `async` function called `getStaticProps` will pre-render a page at build time using the props returned from the function: + +> > > > > > > 1d3d662c4 (merge conflicts) ```jsx export async function getStaticProps(context) { @@ -28,12 +41,22 @@ export async function getStaticProps(context) { You can import modules in top-level scope for use in `getStaticProps`. Imports used will [**not be bundled for the client-side**](#write-server-side-code-directly). This means you can write **server-side code directly in `getStaticProps`**, including reading from the filesystem or a database. +<<<<<<< HEAD You should not use the [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) `API` to call an [`API` route](/docs/api-routes/introduction.md) in `getStaticProps`. Instead, directly import the logic used inside your `API` route. You may need to slightly refactor your code for this approach. -The `fetch()` `API` _can_ be used to fetch external data, such as from a Content Management System (CMS) or `API`. +# The `fetch()` `API` _can_ be used to fetch external data, such as from a Content Management System (CMS) or `API`. + +You should not use the [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) API to call an [API route](/docs/api-routes/introduction.md) in `getStaticProps`. + +Instead, directly import the logic used inside your API route. +You may need to slightly refactor your code for this approach. + +The `fetch()` API _can_ be used to fetch external data, such as from a Content Management System (CMS) or API. + +> > > > > > > 1d3d662c4 (merge conflicts) ## Context parameter @@ -137,6 +160,50 @@ export async function getStaticProps(context) { Redirecting at build-time is currently not allowed and if the redirects are known at build-time they should be added in [`next.config.js`](/docs/api-reference/next.config.js/redirects.md). +# <<<<<<< HEAD + +## TypeScript: Use `GetStaticProps` + +You can use the `GetStaticProps` type from `next` to type the function: + +```ts +import { GetStaticProps } from 'next' + +export const getStaticProps: GetStaticProps = async (context) => { + // ... +} +``` + +If you want to get inferred typings for your props, you can use `InferGetStaticPropsType`: + +```tsx +import { InferGetStaticPropsType } from 'next' + +type Post = { + author: string + content: string +} + +export const getStaticProps = async () => { + const res = await fetch('https://.../posts') + const posts: Post[] = await res.json() + + return { + props: { + posts, + }, + } +} + +function Blog({ posts }: InferGetStaticPropsType) { + // will resolve posts to type Post[] +} + +export default Blog +``` + +> > > > > > > 1d3d662c4 (merge conflicts) + ## Reading files: Use `process.cwd()` Files can be read directly from the filesystem in `getStaticProps`. diff --git a/docs/basic-features/data-fetching/data-fetching.md b/docs/basic-features/data-fetching/data-fetching.md new file mode 100644 index 0000000000000..cf4be5edca29d --- /dev/null +++ b/docs/basic-features/data-fetching/data-fetching.md @@ -0,0 +1,165 @@ +--- +description: 'Data fetching in Next.js allows you to render your content in different ways, depending on your applications use case. These include pre-rendering with server-side rendering or static-site generation, and incremental static regeneration. Learn how to manage your application data in Next.js.' +--- + +# Data Fetching + +
+ Examples + +
+ +The [Pages documentation](/docs/basic-features/pages.md) explained that Next.js has two forms of pre-rendering: **Static Generation** and **Server-side Rendering**. In the sections below, you will learn about data fetching strategies for each case. + +It is recommended that you [read through the Pages documentation](/docs/basic-features/pages.md) first if you have not already done so. + +The three unique Next.js functions you can use to fetch data for pre-rendering are: + +- [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) (Static Generation): Fetch data at **build time**. +- [`getStaticPaths`](/docs/basic-features/data-fetching/getStaticPaths.md) (Static Generation): Specify [dynamic routes](/docs/routing/dynamic-routes.md) to pre-render pages based on data. +- [`getServerSideProps`](/docs/basic-features/data-fetching/getServerSideProps.md) (Server-side Rendering): Fetch data on **each request**. + +## Incremental Static Regeneration + +
+ Examples + +
+ +
+ Version History + +| Version | Changes | +| -------- | ---------------- | +| `v9.5.0` | Base Path added. | + +
+ +Next.js allows you to create or update static pages _after_ you’ve built your site. Incremental Static Regeneration (ISR) enables you to use static-generation on a per-page basis, **without needing to rebuild the entire site**. With ISR, you can retain the benefits of static while scaling to millions of pages. + +The following example shows how to use the `revalidate` property: + +```jsx +function Blog({ posts }) { + return ( +
    + {posts.map((post) => ( +
  • {post.title}
  • + ))} +
+ ) +} + +// This function gets called at build time on server-side. +// It may be called again, on a serverless function, if +// revalidation is enabled and a new request comes in +export async function getStaticProps() { + const res = await fetch('https://.../posts') + const posts = await res.json() + + return { + props: { + posts, + }, + // Next.js will attempt to re-generate the page: + // - When a request comes in + // - At most once every 10 seconds + revalidate: 10, // In seconds + } +} + +// This function gets called at build time on server-side. +// It may be called again, on a serverless function, if +// the path has not been generated. +export async function getStaticPaths() { + 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) => ({ + params: { id: post.id }, + })) + + // We'll pre-render only these paths at build time. + // { fallback: blocking } will server-render pages + // on-demand if the path doesn't exist. + return { paths, fallback: 'blocking' } +} + +export default Blog +``` + +When a request is made to a page that was pre-rendered at build time, it will initially show the cached page. + +- Any requests to the page after the initial request and before 10 seconds are also cached and instantaneous. +- After the 10-second window, the next request will still show the cached (stale) page +- Next.js triggers a regeneration of the page in the background. +- Once the page has been successfully generated, Next.js will invalidate the cache and show the updated product page. If the background regeneration fails, the old page remains unaltered. + +When a request is made to a path that hasn’t been generated, Next.js will server-render the page on the first request. Future requests will serve the static file from the cache. + +To learn how to persist the cache globally and handle rollbacks, learn more about [Incremental Static Regeneration](https://vercel.com/docs/next.js/incremental-static-regeneration). + +## SWR + +The team behind Next.js has created a React hook for data fetching called [**SWR**](https://swr.vercel.app/). 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 you can use it like so: + +```jsx +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.vercel.app/). + +## Learn more + +We recommend you to read the following sections next: + + + + + + diff --git a/docs/basic-features/data-fetching/getServerSideProps.md b/docs/basic-features/data-fetching/getServerSideProps.md index 3a76290fdd7b0..6f6dfccbd81b2 100644 --- a/docs/basic-features/data-fetching/getServerSideProps.md +++ b/docs/basic-features/data-fetching/getServerSideProps.md @@ -2,9 +2,17 @@ description: Fetch data at build time with `getStaticProps` API reference. --- +<<<<<<< HEAD + # `getServerSideProps` -If you export an `async` function called `getServerSideProps` (server-side rendering) from a page, Next.js will pre-render this page on each request using the data returned by `getServerSideProps`. +# If you export an `async` function called `getServerSideProps` (server-side rendering) from a page, Next.js will pre-render this page on each request using the data returned by `getServerSideProps`. + +# `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`. + +> > > > > > > 1d3d662c4 (merge conflicts) ```js export async function getServerSideProps(context) { @@ -14,6 +22,7 @@ export async function getServerSideProps(context) { } ``` +<<<<<<< HEAD The [`getServerSideProps` API reference](/docs/api-reference/data-fetching/getServerSideProps.md) covers all parameters and props that can be used with `getServerSideProps`. ## When should I use `getServerSideProps`? @@ -24,6 +33,19 @@ If you do not need to pre-render the data, then you should consider fetching dat ## TypeScript: Use `GetServerSideProps` +======= +The [`getServerSideProps` API reference](/docs/api-reference/getServerSideProps.md) covers all parameters and props that can be used with `getServerSideProps`. + +### When should I use `getServerSideProps`? + +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`](/docs/data-fetching/getstaticprops.md) because the server must compute the result on every request, and the result cannot be cached by a CDN without extra configuration. + +If you do not need to pre-render the data, then you should consider fetching data on the [client side](#fetching-data-on-the-client-side). + +### TypeScript: Use `GetServerSideProps` + +> > > > > > > 1d3d662c4 (merge conflicts) + For TypeScript, you can use the `GetServerSideProps` type from `next`: ```ts @@ -34,7 +56,12 @@ export const getServerSideProps: GetServerSideProps = async (context) => { } ``` +<<<<<<< HEAD If you want to get inferred typings for your props, you can use `InferGetServerSidePropsType`: +======= +If you want to get inferred typings for your props, you can use `InferGetServerSidePropsType`, like this: + +> > > > > > > 1d3d662c4 (merge conflicts) ```tsx import { InferGetServerSidePropsType } from 'next' @@ -59,19 +86,40 @@ function Page({ data }: InferGetServerSidePropsType) export default Page ``` +<<<<<<< HEAD + ## Technical details ### Only runs on server-side +======= + +### Technical details + +#### Only runs on server-side + +> > > > > > > 1d3d662c4 (merge conflicts) + `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. + <<<<<<< HEAD - When you request this page on client-side page transitions through `next/link` ([documentation](/docs/api-reference/next/link.md)) or `next/router` ([documentation](/docs/api-reference/next/router.md)), Next.js sends an `API` request to the server, which runs `getServerSideProps`. It’ll return `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. You can use [this tool](https://next-code-elimination.vercel.app/) to verify what Next.js eliminates from the client-side bundle. ### Only allowed in a page +======= + +- When you request this page on client-side page transitions through `next/link` ([documentation](/docs/api-reference/next/link.md)) or `next/router` ([documentation](/docs/api-reference/next/router.md)), Next.js sends an API request to the server, which runs `getServerSideProps`. It’ll return 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. + +You can use [this tool](https://next-code-elimination.vercel.app/) to verify what Next.js eliminates from the client-side bundle. + +#### Only allowed in a page + +> > > > > > > 1d3d662c4 (merge conflicts) + `getServerSideProps` can only be exported from a **page**. You can’t export it from non-page files. Also, you must use `export async function getServerSideProps() {}` — it will **not** work if you add `getServerSideProps` as a property of the page component. diff --git a/docs/basic-features/data-fetching/getStaticPaths.md b/docs/basic-features/data-fetching/getStaticPaths.md index 783c5b11007ff..f3704ad99fcb1 100644 --- a/docs/basic-features/data-fetching/getStaticPaths.md +++ b/docs/basic-features/data-fetching/getStaticPaths.md @@ -2,11 +2,21 @@ description: Fetch data at build time with `getStaticProps` API reference. --- +<<<<<<< HEAD + # `getStaticPaths` If a page has [dynamic routes](/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. -When you export an `async` function called `getStaticPaths` (static generation) from a page that uses dynamic routes, Next.js will statically pre-render all the paths specified by `getStaticPaths`. +# When you export an `async` function called `getStaticPaths` (static generation) from a page that uses dynamic routes, Next.js will statically pre-render all the paths specified by `getStaticPaths`. + +# `getStaticPaths` (Static Generation) + +If a page has [dynamic routes](/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. + +When 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`. + +> > > > > > > 1d3d662c4 (merge conflicts) ```jsx export async function getStaticPaths() { @@ -19,12 +29,19 @@ export async function getStaticPaths() { } ``` +<<<<<<< HEAD The [`getStaticPaths` API reference](/docs/api-reference/data-fetching/getStaticPaths.md) covers all parameters and props that can be used with `getStaticPaths`. +======= +The [`getStaticPaths` API reference](/docs/api-reference/getstaticpaths.md) covers all parameters and props that can be used with `getStaticPaths`. + +> > > > > > > 1d3d662c4 (merge conflicts) ## When should I use `getStaticPaths`? You should use `getStaticPaths` if you’re statically pre-rendering pages that use dynamic routes. +<<<<<<< HEAD + ## TypeScript: Use `GetStaticPaths` For TypeScript, you can use the `GetStaticPaths` type from `next`: @@ -37,13 +54,22 @@ export const getStaticPaths: GetStaticPaths = async () => { } ``` +======= + +> > > > > > > 1d3d662c4 (merge conflicts) + ## Technical details ### Use together with [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) When you use `getStaticProps` on a page with dynamic route parameters, you **must** use `getStaticPaths`. +<<<<<<< HEAD Note that you **cannot** use `getStaticPaths` with [`getServerSideProps`](/docs/basic-features/data-fetching/getServerSideProps.md). +======= +Note that you **cannot** use `getStaticPaths` with [`getServerSideProps`](/docs/data-fetching/getServerSideProps.md). + +> > > > > > > 1d3d662c4 (merge conflicts) ### Only runs at build time on server-side diff --git a/docs/basic-features/data-fetching/getStaticProps.md b/docs/basic-features/data-fetching/getStaticProps.md index b82664cc74912..fcb20a867e73d 100644 --- a/docs/basic-features/data-fetching/getStaticProps.md +++ b/docs/basic-features/data-fetching/getStaticProps.md @@ -2,9 +2,17 @@ description: Fetch data at build time with `getStaticProps` (Static Generation) API reference. --- +<<<<<<< HEAD + # `getStaticProps` -If you export an `async` function called `getStaticProps` (static generation) from a page, Next.js will pre-render this page at build time using the props returned by `getStaticProps`. +# If you export an `async` function called `getStaticProps` (static generation) from a page, Next.js will pre-render this page at build time using the props returned by `getStaticProps`. + +# `getStaticProps` (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`. + +> > > > > > > 1d3d662c4 (merge conflicts) ```jsx export async function getStaticProps(context) { @@ -21,6 +29,7 @@ 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 a headless CMS. - The data can be publicly cached (not user-specific). + <<<<<<< HEAD - 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. ## TypeScript: Use `GetStaticProps` @@ -63,6 +72,11 @@ function Blog({ posts }: InferGetStaticPropsType) { export default Blog ``` +======= + +- 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. + > > > > > > > 1d3d662c4 (merge conflicts) + ## Using `getStaticProps` to fetch data from a CMS The following example shows how you can fetch a list of blog posts from a CMS. @@ -100,17 +114,31 @@ export async function getStaticProps() { export default Blog ``` +<<<<<<< HEAD The [`getStaticProps` API reference](/docs/api-reference/data-fetching/getStaticProps.md) covers all parameters and props that can be used with `getStaticProps`. +======= +The [`getStaticProps` API reference](/docs/api-reference/getStaticProps.md) covers all parameters and props that can be used with `getStaticProps`. + +> > > > > > > 1d3d662c4 (merge conflicts) ## Technical details ### Only runs at build time +<<<<<<< HEAD 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. +# 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. + +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. + +> > > > > > > 1d3d662c4 (merge conflicts) You should not fetch an **API route** from `getStaticProps` — instead, you can write the server-side code directly in `getStaticProps`. @@ -118,7 +146,12 @@ You can use the [next-code-elimination tool](https://next-code-elimination.verce ### Statically Generates both `HTML` and `JSON` +<<<<<<< HEAD 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`. +======= +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`. + +> > > > > > > 1d3d662c4 (merge conflicts) This `JSON` file will be used in client-side routing through [`next/link`](/docs/api-reference/next/link.md) or [`next/router`](/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. diff --git a/docs/manifest.json b/docs/manifest.json index 7acf3474f65e4..592aaf46d0090 100644 --- a/docs/manifest.json +++ b/docs/manifest.json @@ -47,10 +47,6 @@ "title": "Built-in CSS Support", "path": "/docs/basic-features/built-in-css-support.md" }, - { - "title": "Layouts", - "path": "/docs/basic-features/layouts.md" - }, { "title": "Image Optimization", "path": "/docs/basic-features/image-optimization.md" @@ -84,7 +80,7 @@ "path": "/docs/basic-features/supported-browsers-features.md" }, { - "title": "Handling Script", + "title": "Handling Scripts", "path": "/docs/basic-features/script.md" } ] @@ -147,10 +143,6 @@ "title": "Authentication", "path": "/docs/authentication.md" }, - { - "title": "Testing", - "path": "/docs/testing.md" - }, { "title": "Advanced Features", "routes": [ @@ -422,10 +414,6 @@ "title": "Disabling ETag Generation", "path": "/docs/api-reference/next.config.js/disabling-etag-generation.md" }, - { - "title": "Disabling HTTP Keep-Alive", - "path": "/docs/api-reference/next.config.js/disabling-http-keep-alive.md" - }, { "title": "Setting a custom build directory", "path": "/docs/api-reference/next.config.js/setting-a-custom-build-directory.md" From 4c48348ecc9915c512836226a9ceddea02421bb8 Mon Sep 17 00:00:00 2001 From: molebox Date: Fri, 12 Nov 2021 12:07:12 +0100 Subject: [PATCH 13/70] merge conflicts --- docs/manifest.json | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/docs/manifest.json b/docs/manifest.json index 592aaf46d0090..3e05c28130a61 100644 --- a/docs/manifest.json +++ b/docs/manifest.json @@ -47,6 +47,10 @@ "title": "Built-in CSS Support", "path": "/docs/basic-features/built-in-css-support.md" }, + { + "title": "Layouts", + "path": "/docs/basic-features/layouts.md" + }, { "title": "Image Optimization", "path": "/docs/basic-features/image-optimization.md" @@ -143,6 +147,10 @@ "title": "Authentication", "path": "/docs/authentication.md" }, + { + "title": "Testing", + "path": "/docs/testing.md" + }, { "title": "Advanced Features", "routes": [ @@ -414,6 +422,10 @@ "title": "Disabling ETag Generation", "path": "/docs/api-reference/next.config.js/disabling-etag-generation.md" }, + { + "title": "Disabling HTTP Keep-Alive", + "path": "/docs/api-reference/next.config.js/disabling-http-keep-alive.md" + }, { "title": "Setting a custom build directory", "path": "/docs/api-reference/next.config.js/setting-a-custom-build-directory.md" From 268d9729b74af24c60e1c92347c7bc6eecb7ea12 Mon Sep 17 00:00:00 2001 From: molebox Date: Fri, 12 Nov 2021 16:24:56 +0100 Subject: [PATCH 14/70] Removed duplicate doc --- .../data-fetching/data-fetching.md | 165 ------------------ 1 file changed, 165 deletions(-) delete mode 100644 docs/basic-features/data-fetching/data-fetching.md diff --git a/docs/basic-features/data-fetching/data-fetching.md b/docs/basic-features/data-fetching/data-fetching.md deleted file mode 100644 index cf4be5edca29d..0000000000000 --- a/docs/basic-features/data-fetching/data-fetching.md +++ /dev/null @@ -1,165 +0,0 @@ ---- -description: 'Data fetching in Next.js allows you to render your content in different ways, depending on your applications use case. These include pre-rendering with server-side rendering or static-site generation, and incremental static regeneration. Learn how to manage your application data in Next.js.' ---- - -# Data Fetching - -
- Examples - -
- -The [Pages documentation](/docs/basic-features/pages.md) explained that Next.js has two forms of pre-rendering: **Static Generation** and **Server-side Rendering**. In the sections below, you will learn about data fetching strategies for each case. - -It is recommended that you [read through the Pages documentation](/docs/basic-features/pages.md) first if you have not already done so. - -The three unique Next.js functions you can use to fetch data for pre-rendering are: - -- [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) (Static Generation): Fetch data at **build time**. -- [`getStaticPaths`](/docs/basic-features/data-fetching/getStaticPaths.md) (Static Generation): Specify [dynamic routes](/docs/routing/dynamic-routes.md) to pre-render pages based on data. -- [`getServerSideProps`](/docs/basic-features/data-fetching/getServerSideProps.md) (Server-side Rendering): Fetch data on **each request**. - -## Incremental Static Regeneration - -
- Examples - -
- -
- Version History - -| Version | Changes | -| -------- | ---------------- | -| `v9.5.0` | Base Path added. | - -
- -Next.js allows you to create or update static pages _after_ you’ve built your site. Incremental Static Regeneration (ISR) enables you to use static-generation on a per-page basis, **without needing to rebuild the entire site**. With ISR, you can retain the benefits of static while scaling to millions of pages. - -The following example shows how to use the `revalidate` property: - -```jsx -function Blog({ posts }) { - return ( -
    - {posts.map((post) => ( -
  • {post.title}
  • - ))} -
- ) -} - -// This function gets called at build time on server-side. -// It may be called again, on a serverless function, if -// revalidation is enabled and a new request comes in -export async function getStaticProps() { - const res = await fetch('https://.../posts') - const posts = await res.json() - - return { - props: { - posts, - }, - // Next.js will attempt to re-generate the page: - // - When a request comes in - // - At most once every 10 seconds - revalidate: 10, // In seconds - } -} - -// This function gets called at build time on server-side. -// It may be called again, on a serverless function, if -// the path has not been generated. -export async function getStaticPaths() { - 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) => ({ - params: { id: post.id }, - })) - - // We'll pre-render only these paths at build time. - // { fallback: blocking } will server-render pages - // on-demand if the path doesn't exist. - return { paths, fallback: 'blocking' } -} - -export default Blog -``` - -When a request is made to a page that was pre-rendered at build time, it will initially show the cached page. - -- Any requests to the page after the initial request and before 10 seconds are also cached and instantaneous. -- After the 10-second window, the next request will still show the cached (stale) page -- Next.js triggers a regeneration of the page in the background. -- Once the page has been successfully generated, Next.js will invalidate the cache and show the updated product page. If the background regeneration fails, the old page remains unaltered. - -When a request is made to a path that hasn’t been generated, Next.js will server-render the page on the first request. Future requests will serve the static file from the cache. - -To learn how to persist the cache globally and handle rollbacks, learn more about [Incremental Static Regeneration](https://vercel.com/docs/next.js/incremental-static-regeneration). - -## SWR - -The team behind Next.js has created a React hook for data fetching called [**SWR**](https://swr.vercel.app/). 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 you can use it like so: - -```jsx -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.vercel.app/). - -## Learn more - -We recommend you to read the following sections next: - - - - - - From 7eebcd7a91c5bb80ae84be9b28ce1442ceb4cc3b Mon Sep 17 00:00:00 2001 From: molebox Date: Fri, 12 Nov 2021 17:07:31 +0100 Subject: [PATCH 15/70] Silly merge left overs --- .../data-fetching/getInitialProps.md | 31 ++-------- .../data-fetching/getServerSideProps.md | 42 +++++-------- .../data-fetching/getStaticPaths.md | 45 +------------- .../data-fetching/getStaticProps.md | 47 +++++---------- .../data-fetching/getServerSideProps.md | 60 ++----------------- .../data-fetching/getStaticPaths.md | 30 +--------- .../data-fetching/getStaticProps.md | 39 +++--------- 7 files changed, 51 insertions(+), 243 deletions(-) diff --git a/docs/api-reference/data-fetching/getInitialProps.md b/docs/api-reference/data-fetching/getInitialProps.md index e0b10f8d01765..10e1659258a07 100644 --- a/docs/api-reference/data-fetching/getInitialProps.md +++ b/docs/api-reference/data-fetching/getInitialProps.md @@ -4,20 +4,13 @@ description: Enable Server-Side Rendering in a page and do initial data populati # getInitialProps -> **Recommended: [`getStaticProps`](/docs/basic-features/data-fetching.md#getstaticprops-static-generation) or [`getServerSideProps`](/docs/basic-features/data-fetching.md#getserversideprops-server-side-rendering)**. -> -> If you're using Next.js 9.3 or newer, we recommend that you use `getStaticProps` or `getServerSideProps` instead of `getInitialProps`. -> -> <<<<<<< HEAD -> These new data fetching methods allow you to have a granular choice between static generation and server-side rendering. Learn more on the documentation for [Pages](/docs/basic-features/pages.md) and [Data Fetching](/docs/basic-features/data-fetching/index.md). -> ======= -> These new data fetching methods allow you to have a granular choice between static generation and server-side rendering. Learn more on the documentation for [Pages](/docs/basic-features/pages.md) and [Data Fetching](/docs/basic-features/data-fetching/data-fetching.md). -> -> > > > > > > 1d3d662c4 (merge conflicts) +**Recommended: [`getStaticProps`](/docs/basic-features/data-fetching.md#getstaticprops-static-generation) or [`getServerSideProps`](/docs/basic-features/data-fetching.md#getserversideprops-server-side-rendering)**. + +These new data fetching methods allow you to have a granular choice between static generation and server-side rendering. Learn more on the documentation for [Pages](/docs/basic-features/pages.md) and [Data Fetching](/docs/basic-features/data-fetching/index.md). `getInitialProps` enables [server-side rendering](/docs/basic-features/pages.md#server-side-rendering) in a page and allows you to do **initial data population**, it means sending the [page](/docs/basic-features/pages.md) with the data already populated from the server. This is especially useful for [SEO](https://en.wikipedia.org/wiki/Search_engine_optimization). -> `getInitialProps` will disable [Automatic Static Optimization](/docs/advanced-features/automatic-static-optimization.md). +`getInitialProps` will disable [Automatic Static Optimization](/docs/advanced-features/automatic-static-optimization.md). `getInitialProps` is an [`async`](https://vercel.com/blog/async-and-await) function that can be added to any page as a [`static method`](https://javascript.info/static-properties-methods). Take a look at the following example: @@ -128,22 +121,8 @@ export default class Page extends React.Component { For more information on what to do next, we recommend the following sections: - - - - diff --git a/docs/api-reference/data-fetching/getServerSideProps.md b/docs/api-reference/data-fetching/getServerSideProps.md index dd69927eed9b6..cd69c6d2fc119 100644 --- a/docs/api-reference/data-fetching/getServerSideProps.md +++ b/docs/api-reference/data-fetching/getServerSideProps.md @@ -2,16 +2,8 @@ description: Fetch data on each request with `getServerSideProps`. Learn more about this API for data fetching in Next.js. --- -<<<<<<< HEAD - # `getServerSideProps` -======= - -# `getServerSideProps` (Server-side Rendering) - -> > > > > > > 1d3d662c4 (merge conflicts) -
Version History @@ -22,12 +14,7 @@ description: Fetch data on each request with `getServerSideProps`. Learn more ab
-<<<<<<< HEAD When exporting an `async` function called `getServerSideProps` (server-side rendering) from a page, Next.js will pre-render this page on each request using the data returned by `getServerSideProps`. -======= -When exporting an `async` function called `getServerSideProps` from a page, Next.js will pre-render this page on each request using the data returned by `getServerSideProps`. - -> > > > > > > 1d3d662c4 (merge conflicts) ```js export async function getServerSideProps(context) { @@ -37,25 +24,13 @@ export async function getServerSideProps(context) { } ``` -You can import modules in top-level scope for use in `getServerSideProps`. -Imports used will [**not be bundled for the client-side**](#write-server-side-code-directly). This means you can write **server-side code directly in `getServerSideProps`**, including reading from the filesystem or a database. +You can import modules in top-level scope for use in `getServerSideProps`. Imports used will **not be bundled for the client-side**. This means you can write **server-side code directly in `getServerSideProps`**, including reading from the filesystem or a database. -<<<<<<< HEAD You should not use the [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) `API` to call an [API route](/docs/api-routes/introduction.md) in `getServerSideProps`. -Instead, directly import the logic used inside your `API` route. -You may need to slightly refactor your code for this approach. - -# The `fetch()` `API` _can_ be used to fetch external data, such as from a Content Management System (CMS) or `API`. +Instead, directly import the logic used inside your `API` route. You may need to slightly refactor your code for this approach. -You should not use the [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) API to call an [API route](/docs/api-routes/introduction.md) in `getServerSideProps`. - -Instead, directly import the logic used inside your API route. -You may need to slightly refactor your code for this approach. - -The `fetch()` API _can_ be used to fetch external data, such as from a Content Management System (CMS) or API. - -> > > > > > > 1d3d662c4 (merge conflicts) +> **Note:** The `fetch()` `API` _can_ be used to fetch external data, such as from a Content Management System (CMS) or `API`. ## Context parameter @@ -132,3 +107,14 @@ export async function getServerSideProps(context) { } } ``` + +## Related + +For more information on what to do next, we recommend the following sections: + + diff --git a/docs/api-reference/data-fetching/getStaticPaths.md b/docs/api-reference/data-fetching/getStaticPaths.md index 058b4d7b0af63..b7e0d2aa0d357 100644 --- a/docs/api-reference/data-fetching/getStaticPaths.md +++ b/docs/api-reference/data-fetching/getStaticPaths.md @@ -2,16 +2,8 @@ description: Fetch data at build time with `getStaticProps`. --- -<<<<<<< HEAD - # `getStaticPaths` -======= - -# `getStaticPaths` (Static Generation) - -> > > > > > > 1d3d662c4 (merge conflicts) -
Version History @@ -22,13 +14,8 @@ description: Fetch data at build time with `getStaticProps`.
-<<<<<<< HEAD -When exporting an `async` function called `getStaticPaths` (static generation) from a page that uses dynamic routes, Next.js will statically pre-render all the paths specified by `getStaticPaths`. -======= When exporting an `async` function called `getStaticPaths` from a page that uses dynamic routes, Next.js will statically pre-render all the paths specified by `getStaticPaths`. -> > > > > > > 1d3d662c4 (merge conflicts) - ```jsx export async function getStaticPaths() { return { @@ -72,7 +59,7 @@ If `fallback` is `false`, then any paths not returned by `getStaticPaths` will r It is 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 will need to run the build again. -The following example 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`](/docs/api-reference/getStaticProps.md). +The following example 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`](/docs/api-reference/data-fetching/getStaticProps.md). ```jsx // pages/posts/[id].js @@ -128,7 +115,7 @@ If `fallback` is `true`, then the behavior of `getStaticProps` changes in the fo - When complete, 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: true` is not supported when using [`next export`](/docs/advanced-features/static-html-export.md). +> **Note:** `fallback: true` is not supported when using [`next export`](/docs/advanced-features/static-html-export.md). #### When is `fallback: true` useful? @@ -140,13 +127,8 @@ Shortly after, `getStaticProps` finishes and the page will be rendered with the This ensures that users always have a fast experience while preserving fast builds and the benefits of Static Generation. -<<<<<<< HEAD -`fallback: true` will not _update_ generated pages, for that take a look at [Incremental Static Regeneration](/docs/basic-features/data-fetching/data-fetching#incremental-static-regeneration). -======= `fallback: true` will not _update_ generated pages, for that take a look at [Incremental Static Regeneration](/docs/basic-features/data-fetching/index#incremental-static-regeneration). -> > > > > > > 1d3d662c4 (merge conflicts) - ### `fallback: 'blocking'` If `fallback` is `'blocking'`, new paths not returned by `getStaticPaths` will wait for the `HTML` to be generated, identical to SSR (hence why _blocking_), and then be cached for future requests so it only happens once per path. @@ -158,14 +140,9 @@ If `fallback` is `'blocking'`, new paths not returned by `getStaticPaths` will w - When complete, the browser receives the `HTML` for the generated path. From the user’s perspective, it will transition from "the browser is requesting the page" to "the full page is loaded". There is no flash of loading/fallback state. - 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. -<<<<<<< HEAD -`fallback: 'blocking'` will not _update_ generated pages by default. To update generated pages, use [Incremental Static Regeneration](/docs/basic-features/data-fetching/data-fetching#incremental-static-regeneration) in conjunction with `fallback: 'blocking'`. -======= `fallback: 'blocking'` will not _update_ generated pages by default. To update generated pages, use [Incremental Static Regeneration](/docs/basic-features/data-fetching/index#incremental-static-regeneration) in conjunction with `fallback: 'blocking'`. -> > > > > > > 1d3d662c4 (merge conflicts) - -> `fallback: 'blocking'` is not supported when using [`next export`](/docs/advanced-features/static-html-export.md). +> **Note:** `fallback: 'blocking'` is not supported when using [`next export`](/docs/advanced-features/static-html-export.md). ### Fallback pages @@ -221,19 +198,3 @@ export async function getStaticProps({ params }) { export default Post ``` - -# <<<<<<< HEAD - -## TypeScript: Use `GetStaticPaths` - -For TypeScript, you can use the `GetStaticPaths` type from `next`: - -```ts -import { GetStaticPaths } from 'next' - -export const getStaticPaths: GetStaticPaths = async () => { - // ... -} -``` - -> > > > > > > 1d3d662c4 (merge conflicts) diff --git a/docs/api-reference/data-fetching/getStaticProps.md b/docs/api-reference/data-fetching/getStaticProps.md index 4fbd8c434dbe9..87387bc8eaa26 100644 --- a/docs/api-reference/data-fetching/getStaticProps.md +++ b/docs/api-reference/data-fetching/getStaticProps.md @@ -2,16 +2,8 @@ description: Fetch data at build time with `getStaticProps`. --- -<<<<<<< HEAD - # `getStaticProps` -======= - -# `getStaticProps` (Static Generation) - -> > > > > > > 1d3d662c4 (merge conflicts) -
Version History @@ -23,13 +15,8 @@ description: Fetch data at build time with `getStaticProps`.
-<<<<<<< HEAD -Exporting an `async` function called `getStaticProps` (static generation) will pre-render a page at build time using the props returned from the function: -======= Exporting an `async` function called `getStaticProps` will pre-render a page at build time using the props returned from the function: -> > > > > > > 1d3d662c4 (merge conflicts) - ```jsx export async function getStaticProps(context) { return { @@ -39,24 +26,13 @@ export async function getStaticProps(context) { ``` You can import modules in top-level scope for use in `getStaticProps`. -Imports used will [**not be bundled for the client-side**](#write-server-side-code-directly). This means you can write **server-side code directly in `getStaticProps`**, including reading from the filesystem or a database. +Imports used will **not be bundled for the client-side**. This means you can write **server-side code directly in `getStaticProps`**, including reading from the filesystem or a database. -<<<<<<< HEAD You should not use the [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) `API` to call an [`API` route](/docs/api-routes/introduction.md) in `getStaticProps`. -Instead, directly import the logic used inside your `API` route. -You may need to slightly refactor your code for this approach. - -# The `fetch()` `API` _can_ be used to fetch external data, such as from a Content Management System (CMS) or `API`. - -You should not use the [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) API to call an [API route](/docs/api-routes/introduction.md) in `getStaticProps`. +Instead, directly import the logic used inside your `API` route. You may need to slightly refactor your code for this approach. -Instead, directly import the logic used inside your API route. -You may need to slightly refactor your code for this approach. - -The `fetch()` API _can_ be used to fetch external data, such as from a Content Management System (CMS) or API. - -> > > > > > > 1d3d662c4 (merge conflicts) +The `fetch()` `API` _can_ be used to fetch external data, such as from a Content Management System (CMS) or `API`. ## Context parameter @@ -109,7 +85,7 @@ export async function getStaticProps() { } ``` -More information is covered in [Incremental Static Regeneration](/docs/basic-features/data-fetching/data-fetching#incremental-static-regeneration) +More information is covered in [Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration) ### `notFound` @@ -160,8 +136,6 @@ export async function getStaticProps(context) { Redirecting at build-time is currently not allowed and if the redirects are known at build-time they should be added in [`next.config.js`](/docs/api-reference/next.config.js/redirects.md). -# <<<<<<< HEAD - ## TypeScript: Use `GetStaticProps` You can use the `GetStaticProps` type from `next` to type the function: @@ -202,8 +176,6 @@ function Blog({ posts }: InferGetStaticPropsType) { export default Blog ``` -> > > > > > > 1d3d662c4 (merge conflicts) - ## Reading files: Use `process.cwd()` Files can be read directly from the filesystem in `getStaticProps`. @@ -262,3 +234,14 @@ export async function getStaticProps() { export default Blog ``` + +## Related + +For more information on what to do next, we recommend the following sections: + + diff --git a/docs/basic-features/data-fetching/getServerSideProps.md b/docs/basic-features/data-fetching/getServerSideProps.md index 6f6dfccbd81b2..ebe5f65901913 100644 --- a/docs/basic-features/data-fetching/getServerSideProps.md +++ b/docs/basic-features/data-fetching/getServerSideProps.md @@ -2,17 +2,9 @@ description: Fetch data at build time with `getStaticProps` API reference. --- -<<<<<<< HEAD - # `getServerSideProps` -# If you export an `async` function called `getServerSideProps` (server-side rendering) from a page, Next.js will pre-render this page on each request using the data returned by `getServerSideProps`. - -# `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`. - -> > > > > > > 1d3d662c4 (merge conflicts) +If you export an `async` function called `getServerSideProps` (server-side rendering) 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) { @@ -22,7 +14,6 @@ export async function getServerSideProps(context) { } ``` -<<<<<<< HEAD The [`getServerSideProps` API reference](/docs/api-reference/data-fetching/getServerSideProps.md) covers all parameters and props that can be used with `getServerSideProps`. ## When should I use `getServerSideProps`? @@ -31,21 +22,8 @@ You should use `getServerSideProps` only if you need to pre-render a page whose If you do not need to pre-render the data, then you should consider fetching data on the [client side](#fetching-data-on-the-client-side). -## TypeScript: Use `GetServerSideProps` - -======= -The [`getServerSideProps` API reference](/docs/api-reference/getServerSideProps.md) covers all parameters and props that can be used with `getServerSideProps`. - -### When should I use `getServerSideProps`? - -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`](/docs/data-fetching/getstaticprops.md) because the server must compute the result on every request, and the result cannot be cached by a CDN without extra configuration. - -If you do not need to pre-render the data, then you should consider fetching data on the [client side](#fetching-data-on-the-client-side). - ### TypeScript: Use `GetServerSideProps` -> > > > > > > 1d3d662c4 (merge conflicts) - For TypeScript, you can use the `GetServerSideProps` type from `next`: ```ts @@ -56,12 +34,7 @@ export const getServerSideProps: GetServerSideProps = async (context) => { } ``` -<<<<<<< HEAD If you want to get inferred typings for your props, you can use `InferGetServerSidePropsType`: -======= -If you want to get inferred typings for your props, you can use `InferGetServerSidePropsType`, like this: - -> > > > > > > 1d3d662c4 (merge conflicts) ```tsx import { InferGetServerSidePropsType } from 'next' @@ -86,39 +59,16 @@ function Page({ data }: InferGetServerSidePropsType) export default Page ``` -<<<<<<< HEAD - -## Technical details - -### Only runs on server-side - -======= - ### Technical details #### Only runs on server-side -> > > > > > > 1d3d662c4 (merge conflicts) - `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. - <<<<<<< HEAD -- When you request this page on client-side page transitions through `next/link` ([documentation](/docs/api-reference/next/link.md)) or `next/router` ([documentation](/docs/api-reference/next/router.md)), Next.js sends an `API` request to the server, which runs `getServerSideProps`. It’ll return `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. - -You can use [this tool](https://next-code-elimination.vercel.app/) to verify what Next.js eliminates from the client-side bundle. - -### Only allowed in a page - -======= - -- When you request this page on client-side page transitions through `next/link` ([documentation](/docs/api-reference/next/link.md)) or `next/router` ([documentation](/docs/api-reference/next/router.md)), Next.js sends an API request to the server, which runs `getServerSideProps`. It’ll return 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. - -You can use [this tool](https://next-code-elimination.vercel.app/) to verify what Next.js eliminates from the client-side bundle. - -#### Only allowed in a page +- 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`](/docs/api-reference/next/link.md)) or ([`next/router`](/docs/api-reference/next/router.md)), Next.js sends an API request to the server, which runs `getServerSideProps`. It’ll return 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 -> > > > > > > 1d3d662c4 (merge conflicts) +You can use the [next-code-elimination tool](https://next-code-elimination.vercel.app/) to verify what Next.js eliminates from the client-side bundle. `getServerSideProps` can only be exported from a **page**. You can’t export it from non-page files. @@ -126,7 +76,7 @@ Also, you must use `export async function getServerSideProps() {}` — it will * ## 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. An example of this is user-specific 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. diff --git a/docs/basic-features/data-fetching/getStaticPaths.md b/docs/basic-features/data-fetching/getStaticPaths.md index f3704ad99fcb1..12db221725c90 100644 --- a/docs/basic-features/data-fetching/getStaticPaths.md +++ b/docs/basic-features/data-fetching/getStaticPaths.md @@ -2,21 +2,11 @@ description: Fetch data at build time with `getStaticProps` API reference. --- -<<<<<<< HEAD - # `getStaticPaths` -If a page has [dynamic routes](/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. - -# When you export an `async` function called `getStaticPaths` (static generation) from a page that uses dynamic routes, Next.js will statically pre-render all the paths specified by `getStaticPaths`. - -# `getStaticPaths` (Static Generation) - -If a page has [dynamic routes](/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. - -When 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`. +If a page has [dynamic routes](/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. -> > > > > > > 1d3d662c4 (merge conflicts) +When you export an `async` function called `getStaticPaths` (static generation) from a page that uses dynamic routes, Next.js will statically pre-render all the paths specified by `getStaticPaths`. ```jsx export async function getStaticPaths() { @@ -29,19 +19,12 @@ export async function getStaticPaths() { } ``` -<<<<<<< HEAD The [`getStaticPaths` API reference](/docs/api-reference/data-fetching/getStaticPaths.md) covers all parameters and props that can be used with `getStaticPaths`. -======= -The [`getStaticPaths` API reference](/docs/api-reference/getstaticpaths.md) covers all parameters and props that can be used with `getStaticPaths`. - -> > > > > > > 1d3d662c4 (merge conflicts) ## When should I use `getStaticPaths`? You should use `getStaticPaths` if you’re statically pre-rendering pages that use dynamic routes. -<<<<<<< HEAD - ## TypeScript: Use `GetStaticPaths` For TypeScript, you can use the `GetStaticPaths` type from `next`: @@ -54,22 +37,13 @@ export const getStaticPaths: GetStaticPaths = async () => { } ``` -======= - -> > > > > > > 1d3d662c4 (merge conflicts) - ## Technical details ### Use together with [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) When you use `getStaticProps` on a page with dynamic route parameters, you **must** use `getStaticPaths`. -<<<<<<< HEAD Note that you **cannot** use `getStaticPaths` with [`getServerSideProps`](/docs/basic-features/data-fetching/getServerSideProps.md). -======= -Note that you **cannot** use `getStaticPaths` with [`getServerSideProps`](/docs/data-fetching/getServerSideProps.md). - -> > > > > > > 1d3d662c4 (merge conflicts) ### Only runs at build time on server-side diff --git a/docs/basic-features/data-fetching/getStaticProps.md b/docs/basic-features/data-fetching/getStaticProps.md index fcb20a867e73d..6eee234cb16b9 100644 --- a/docs/basic-features/data-fetching/getStaticProps.md +++ b/docs/basic-features/data-fetching/getStaticProps.md @@ -2,17 +2,9 @@ description: Fetch data at build time with `getStaticProps` (Static Generation) API reference. --- -<<<<<<< HEAD - # `getStaticProps` -# If you export an `async` function called `getStaticProps` (static generation) from a page, Next.js will pre-render this page at build time using the props returned by `getStaticProps`. - -# `getStaticProps` (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`. - -> > > > > > > 1d3d662c4 (merge conflicts) +If you export an `async` function called `getStaticProps` (static generation) from a page, Next.js will pre-render this page at build time using the props returned by `getStaticProps`. ```jsx export async function getStaticProps(context) { @@ -29,7 +21,6 @@ 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 a headless CMS. - The data can be publicly cached (not user-specific). - <<<<<<< HEAD - 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. ## TypeScript: Use `GetStaticProps` @@ -72,10 +63,7 @@ function Blog({ posts }: InferGetStaticPropsType) { export default Blog ``` -======= - -- 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. - > > > > > > > 1d3d662c4 (merge conflicts) +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. ## Using `getStaticProps` to fetch data from a CMS @@ -114,23 +102,17 @@ export async function getStaticProps() { export default Blog ``` -<<<<<<< HEAD The [`getStaticProps` API reference](/docs/api-reference/data-fetching/getStaticProps.md) covers all parameters and props that can be used with `getStaticProps`. -======= -The [`getStaticProps` API reference](/docs/api-reference/getStaticProps.md) covers all parameters and props that can be used with `getStaticProps`. - -> > > > > > > 1d3d662c4 (merge conflicts) ## Technical details ### Only runs at build time -<<<<<<< HEAD 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. +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. 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. @@ -138,24 +120,17 @@ Because `getStaticProps` runs at build time, it does **not** receive data that 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. -> > > > > > > 1d3d662c4 (merge conflicts) - You should not fetch an **API route** from `getStaticProps` — instead, you can write the server-side code directly in `getStaticProps`. You can use the [next-code-elimination tool](https://next-code-elimination.vercel.app/) to verify what Next.js eliminates from the client-side bundle. -### Statically Generates both `HTML` and `JSON` - -<<<<<<< HEAD -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`. -======= -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`. +### Statically Generates both HTML and JSON -> > > > > > > 1d3d662c4 (merge conflicts) +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`](/docs/api-reference/next/link.md) or [`next/router`](/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`](/docs/api-reference/next/link.md) or [`next/router`](/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. -When using Incremental Static Generation `getStaticProps` will be executed out of band to generate the `JSON` needed for client-side navigation. You may see this in the form of multiple requests being made for the same page, however, this is intended and has no impact on end-user performance +When using Incremental Static Generation `getStaticProps` will be executed out of band to generate the JSON needed for client-side navigation. You may see this in the form of multiple requests being made for the same page, however, this is intended and has no impact on end-user performance ### Only allowed in a page From cea5cea88e8e439fd2a3cdf9e829e027a91eb52a Mon Sep 17 00:00:00 2001 From: Rich Haines Date: Tue, 16 Nov 2021 09:53:41 +0100 Subject: [PATCH 16/70] Update docs/api-reference/data-fetching/getInitialProps.md Co-authored-by: Lee Robinson --- docs/api-reference/data-fetching/getInitialProps.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/docs/api-reference/data-fetching/getInitialProps.md b/docs/api-reference/data-fetching/getInitialProps.md index 10e1659258a07..abf8f39646640 100644 --- a/docs/api-reference/data-fetching/getInitialProps.md +++ b/docs/api-reference/data-fetching/getInitialProps.md @@ -4,9 +4,7 @@ description: Enable Server-Side Rendering in a page and do initial data populati # getInitialProps -**Recommended: [`getStaticProps`](/docs/basic-features/data-fetching.md#getstaticprops-static-generation) or [`getServerSideProps`](/docs/basic-features/data-fetching.md#getserversideprops-server-side-rendering)**. - -These new data fetching methods allow you to have a granular choice between static generation and server-side rendering. Learn more on the documentation for [Pages](/docs/basic-features/pages.md) and [Data Fetching](/docs/basic-features/data-fetching/index.md). +**Recommended: [`getStaticProps`](/docs/basic-features/data-fetching.md#getstaticprops-static-generation) or [`getServerSideProps`](/docs/basic-features/data-fetching.md#getserversideprops-server-side-rendering)** instead of `getInitialProps`. These new data fetching methods allow you to have a granular choice between static generation and server-side rendering. `getInitialProps` enables [server-side rendering](/docs/basic-features/pages.md#server-side-rendering) in a page and allows you to do **initial data population**, it means sending the [page](/docs/basic-features/pages.md) with the data already populated from the server. This is especially useful for [SEO](https://en.wikipedia.org/wiki/Search_engine_optimization). From a01bcf663141608ed46055e2cc48fff7feac0c8a Mon Sep 17 00:00:00 2001 From: molebox Date: Tue, 16 Nov 2021 12:36:03 +0100 Subject: [PATCH 17/70] Feedback changes, fleshout swr page, changed name, fixed links --- .../data-fetching/getServerSideProps.md | 4 +- .../data-fetching/getStaticPaths.md | 14 ++-- .../data-fetching/client-side.md | 68 +++++++++++++++++++ .../data-fetching/getStaticProps.md | 6 +- docs/basic-features/data-fetching/index.md | 2 +- docs/basic-features/data-fetching/swr.md | 21 ------ docs/manifest.json | 4 +- 7 files changed, 81 insertions(+), 38 deletions(-) create mode 100644 docs/basic-features/data-fetching/client-side.md delete mode 100644 docs/basic-features/data-fetching/swr.md diff --git a/docs/api-reference/data-fetching/getServerSideProps.md b/docs/api-reference/data-fetching/getServerSideProps.md index cd69c6d2fc119..d5799591f630c 100644 --- a/docs/api-reference/data-fetching/getServerSideProps.md +++ b/docs/api-reference/data-fetching/getServerSideProps.md @@ -14,7 +14,7 @@ description: Fetch data on each request with `getServerSideProps`. Learn more ab
-When exporting an `async` function called `getServerSideProps` (server-side rendering) from a page, Next.js will pre-render this page on each request using the data returned by `getServerSideProps`. +When exporting an `async` function called `getServerSideProps` (server-side rendering) from a page, Next.js will pre-render this page on each request using the data returned by `getServerSideProps`. This is useful if you want to fetch data that changes often, and have the page update to show the most current data. ```js export async function getServerSideProps(context) { @@ -30,8 +30,6 @@ You should not use the [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/ Instead, directly import the logic used inside your `API` route. You may need to slightly refactor your code for this approach. -> **Note:** The `fetch()` `API` _can_ be used to fetch external data, such as from a Content Management System (CMS) or `API`. - ## Context parameter The `context` parameter is an object containing the following keys: diff --git a/docs/api-reference/data-fetching/getStaticPaths.md b/docs/api-reference/data-fetching/getStaticPaths.md index b7e0d2aa0d357..a5f4c72f536e4 100644 --- a/docs/api-reference/data-fetching/getStaticPaths.md +++ b/docs/api-reference/data-fetching/getStaticPaths.md @@ -1,5 +1,5 @@ --- -description: Fetch data at build time with `getStaticProps`. +description: Fetch data and generate static pages with `getStaticProps`. --- # `getStaticPaths` @@ -7,14 +7,14 @@ description: Fetch data at build time with `getStaticProps`.
Version History -| Version | Changes | -| -------- | ----------------------------------------------------------------------------------------------------------------- | -| `v9.5.0` | Stable [Incremental Static Regeneration](https://nextjs.org/blog/next-9-5#stable-incremental-static-regeneration) | -| `v9.3.0` | `getStaticPaths` introduced. | +| Version | Changes | +| -------- | ------------------------------------------------------------------------------------------------------------ | +| `v9.5.0` | Stable [Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration) | +| `v9.3.0` | `getStaticPaths` introduced. |
-When exporting an `async` function called `getStaticPaths` from a page that uses dynamic routes, Next.js will statically pre-render all the paths specified by `getStaticPaths`. +When exporting an `async` function called `getStaticPaths` from a page that uses [dynamic routes](/docs/routing/dynamic-routes), Next.js will statically pre-render all the paths specified by `getStaticPaths`. ```jsx export async function getStaticPaths() { @@ -127,7 +127,7 @@ Shortly after, `getStaticProps` finishes and the page will be rendered with the This ensures that users always have a fast experience while preserving fast builds and the benefits of Static Generation. -`fallback: true` will not _update_ generated pages, for that take a look at [Incremental Static Regeneration](/docs/basic-features/data-fetching/index#incremental-static-regeneration). +`fallback: true` will not _update_ generated pages, for that take a look at [Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration). ### `fallback: 'blocking'` diff --git a/docs/basic-features/data-fetching/client-side.md b/docs/basic-features/data-fetching/client-side.md new file mode 100644 index 0000000000000..372b6f6c9d904 --- /dev/null +++ b/docs/basic-features/data-fetching/client-side.md @@ -0,0 +1,68 @@ +--- +description: 'Learn how to use SWR, a data fetching React hook that handles caching, revalidation, focus tracking, refetching on interval and more.' +--- + +# Client-side data fetching + +Client-side data fetching is useful when your page doesn't require SEO indexing, when you don't need to pre-render your data, or when your pages content needs to update frequently. Unlike the server-side rendering APIs, you can use client side data fetching at the component level. + +If done at the page level, the data is fetched at runtime, and the contents of the page updated as the data changes. When used at the component level, the data is fetched at the time of the component mount, and the contents of the component are updated as the data changes. + +It's important to note that using client-side data fetching can affect the performance of your application and the load speed of your pages. This is because the data fetching is done at the time of the component or pages mount, and the data is not cached. + +## Client-side data fetching with useEffect + +The following example shows how you can fetch data on the client side using the useEffect hook. + +```jsx +function Profile() { + const [data, setData] = useState(null) + const [isLoading, setLoading] = useState(false) + + useEffect(() => { + setLoading(true) + fetch('api/profile-data') + .then((res) => res.json()) + .then((data) => { + setData(data) + setLoading(false) + }) + }, []) + + if (isLoading) return

Loading...

+ if (!profileData) return

No profile data

+ + return ( +
+

{data.name}

+

{data.bio}

+
+ ) +} +``` + +# Client-side data fetching with SWR + +The team behind Next.js has created a React hook for data fetching called [**SWR**](https://swr.vercel.app/). It is **highly recommend** if you are fetching data on the client side. It handles caching, revalidation, focus tracking, refetching on interval, and more. + +Using the same example as above, we can now use SWR to fetch the profile data. SWR will automatically cache the data for us, and will revalidate the data if it is stale. + +For more information on using SWR, check out the [SWR docs](https://swr.vercel.app/docs). + +```jsx +import useSWR from 'swr' + +function Profile() { + const { data, error } = useSWR('/api/profile-data', fetch) + + if (error) return
Failed to load
+ if (!data) return
Loading...
+ + return ( +
+

{data.name}

+

{data.bio}

+
+ ) +} +``` diff --git a/docs/basic-features/data-fetching/getStaticProps.md b/docs/basic-features/data-fetching/getStaticProps.md index 6eee234cb16b9..4b5af5838f0ab 100644 --- a/docs/basic-features/data-fetching/getStaticProps.md +++ b/docs/basic-features/data-fetching/getStaticProps.md @@ -1,5 +1,5 @@ --- -description: Fetch data at build time with `getStaticProps` (Static Generation) API reference. +description: Fetch data and generate static pages with `getStaticProps`. Learn more about this API for data fetching in Next.js. --- # `getStaticProps` @@ -108,14 +108,12 @@ The [`getStaticProps` API reference](/docs/api-reference/data-fetching/getStatic ### 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. -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. diff --git a/docs/basic-features/data-fetching/index.md b/docs/basic-features/data-fetching/index.md index a1906a96d5a1a..ef169922967f6 100644 --- a/docs/basic-features/data-fetching/index.md +++ b/docs/basic-features/data-fetching/index.md @@ -29,7 +29,7 @@ description: 'Data fetching in Next.js allows you to render your content in diff Data fetching in Next.js allows you to render your content in different ways, depending on your applications use case. These include pre-rendering with **Server-side Rendering** or **Static Generation**, and updating or creating content at runtime with **Incremental Static Regeneration**.
- + CSR: Client-side rendering Learn more about client side rendering in Next.js with SWR. diff --git a/docs/basic-features/data-fetching/swr.md b/docs/basic-features/data-fetching/swr.md deleted file mode 100644 index 750fe10c8e8ef..0000000000000 --- a/docs/basic-features/data-fetching/swr.md +++ /dev/null @@ -1,21 +0,0 @@ ---- -description: 'Learn how to use SWR, a data fetching React hook that handles caching, revalidation, focus tracking, refetching on interval and more.' ---- - -# SWR - -The team behind Next.js has created a React hook for data fetching called [**SWR**](https://swr.vercel.app/). It is highly recommend if you are fetching data on the client side. It handles caching, revalidation, focus tracking, refetching on interval, and more. - -```jsx -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.vercel.app/). diff --git a/docs/manifest.json b/docs/manifest.json index 3e05c28130a61..70d7eb91d0e50 100644 --- a/docs/manifest.json +++ b/docs/manifest.json @@ -38,8 +38,8 @@ "path": "/docs/basic-features/data-fetching/incremental-static-regeneration.md" }, { - "title": "SWR", - "path": "/docs/basic-features/data-fetching/swr.md" + "title": "Client side", + "path": "/docs/basic-features/data-fetching/client-side.md" } ] }, From 3034fc38e7fdd66728c7c862ff65a18a2ec8ef74 Mon Sep 17 00:00:00 2001 From: molebox Date: Thu, 18 Nov 2021 12:04:02 +0100 Subject: [PATCH 18/70] Added ISR not on build time. Clean up --- docs/api-reference/data-fetching/getServerSideProps.md | 2 +- docs/api-reference/data-fetching/getStaticPaths.md | 10 +++++----- docs/basic-features/data-fetching/getStaticProps.md | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/docs/api-reference/data-fetching/getServerSideProps.md b/docs/api-reference/data-fetching/getServerSideProps.md index d5799591f630c..64fa249e110c3 100644 --- a/docs/api-reference/data-fetching/getServerSideProps.md +++ b/docs/api-reference/data-fetching/getServerSideProps.md @@ -51,7 +51,7 @@ The `getServerSideProps` function should return an object with the following **o ### `props` -The `props` object is a key value pair, where each value is received by the page component. It should be a [serializable object](https://en.wikipedia.org/wiki/Serialization) +The `props` object is a key value pair, where each value is received by the page component. It should be a [serializable object](https://en.wikipedia.org/wiki/Serialization). ```jsx export async function getServerSideProps(context) { diff --git a/docs/api-reference/data-fetching/getStaticPaths.md b/docs/api-reference/data-fetching/getStaticPaths.md index a5f4c72f536e4..51e2dcd541822 100644 --- a/docs/api-reference/data-fetching/getStaticPaths.md +++ b/docs/api-reference/data-fetching/getStaticPaths.md @@ -7,14 +7,14 @@ description: Fetch data and generate static pages with `getStaticProps`.
Version History -| Version | Changes | -| -------- | ------------------------------------------------------------------------------------------------------------ | -| `v9.5.0` | Stable [Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration) | -| `v9.3.0` | `getStaticPaths` introduced. | +| Version | Changes | +| -------- | --------------------------------------------------------------------------------------------------------------- | +| `v9.5.0` | Stable [Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration.md) | +| `v9.3.0` | `getStaticPaths` introduced. |
-When exporting an `async` function called `getStaticPaths` from a page that uses [dynamic routes](/docs/routing/dynamic-routes), Next.js will statically pre-render all the paths specified by `getStaticPaths`. +When exporting an `async` function called `getStaticPaths` from a page that uses [dynamic routes](/docs/routing/dynamic-routes.md), Next.js will statically pre-render all the paths specified by `getStaticPaths`. ```jsx export async function getStaticPaths() { diff --git a/docs/basic-features/data-fetching/getStaticProps.md b/docs/basic-features/data-fetching/getStaticProps.md index 4b5af5838f0ab..eea5d993714c2 100644 --- a/docs/basic-features/data-fetching/getStaticProps.md +++ b/docs/basic-features/data-fetching/getStaticProps.md @@ -108,7 +108,7 @@ The [`getStaticProps` API reference](/docs/api-reference/data-fetching/getStatic ### 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`. When combined with [Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration.md) however, it will run in the background while the stale page is being revalidated, and the fresh page served to the browser. ### Write server-side code directly From 2511cdfac159a05a07a94b47e45e104232d54d4d Mon Sep 17 00:00:00 2001 From: molebox Date: Mon, 22 Nov 2021 14:46:47 +0100 Subject: [PATCH 19/70] Moved some information to gsp --- docs/api-reference/data-fetching/getServerSideProps.md | 4 ---- docs/basic-features/data-fetching/getServerSideProps.md | 6 ++++++ docs/basic-features/data-fetching/getStaticPaths.md | 8 +++++++- docs/basic-features/data-fetching/getStaticProps.md | 8 ++++---- 4 files changed, 17 insertions(+), 9 deletions(-) diff --git a/docs/api-reference/data-fetching/getServerSideProps.md b/docs/api-reference/data-fetching/getServerSideProps.md index 64fa249e110c3..cc70a93d8c915 100644 --- a/docs/api-reference/data-fetching/getServerSideProps.md +++ b/docs/api-reference/data-fetching/getServerSideProps.md @@ -26,10 +26,6 @@ export async function getServerSideProps(context) { You can import modules in top-level scope for use in `getServerSideProps`. Imports used will **not be bundled for the client-side**. This means you can write **server-side code directly in `getServerSideProps`**, including reading from the filesystem or a database. -You should not use the [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) `API` to call an [API route](/docs/api-routes/introduction.md) in `getServerSideProps`. - -Instead, directly import the logic used inside your `API` route. You may need to slightly refactor your code for this approach. - ## Context parameter The `context` parameter is an object containing the following keys: diff --git a/docs/basic-features/data-fetching/getServerSideProps.md b/docs/basic-features/data-fetching/getServerSideProps.md index ebe5f65901913..da55726c52738 100644 --- a/docs/basic-features/data-fetching/getServerSideProps.md +++ b/docs/basic-features/data-fetching/getServerSideProps.md @@ -22,6 +22,12 @@ You should use `getServerSideProps` only if you need to pre-render a page whose If you do not need to pre-render the data, then you should consider fetching data on the [client side](#fetching-data-on-the-client-side). +### `getServerSideProps` or API Routes? + +It can be tempting to reach for an [API Route](/docs/api-routes/introduction.md) when you want to fetch data from the server, then call that API route from `getServerSideProps`. This is an unnecessary and inefficient approach, as it will cause an extra request to be made due to both `getServerSideProps` and API Routes running on the server. + +Instead, directly import the logic used inside your API Route into `getServerSideProps`. This could mean calling a CMS, database, or other API directly from inside `getServerSideProps`. + ### TypeScript: Use `GetServerSideProps` For TypeScript, you can use the `GetServerSideProps` type from `next`: diff --git a/docs/basic-features/data-fetching/getStaticPaths.md b/docs/basic-features/data-fetching/getStaticPaths.md index 12db221725c90..614fb039023e9 100644 --- a/docs/basic-features/data-fetching/getStaticPaths.md +++ b/docs/basic-features/data-fetching/getStaticPaths.md @@ -23,7 +23,13 @@ The [`getStaticPaths` API reference](/docs/api-reference/data-fetching/getStatic ## 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 and: + +- The data comes from a headless CMS +- The data comes from a database +- The data comes from the filesystem +- 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 ## TypeScript: Use `GetStaticPaths` diff --git a/docs/basic-features/data-fetching/getStaticProps.md b/docs/basic-features/data-fetching/getStaticProps.md index eea5d993714c2..a416fec66619f 100644 --- a/docs/basic-features/data-fetching/getStaticProps.md +++ b/docs/basic-features/data-fetching/getStaticProps.md @@ -18,10 +18,10 @@ export async function getStaticProps(context) { 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 a 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. +- The data required to render the page is available at build time ahead of a user’s request +- The data comes from a 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 ## TypeScript: Use `GetStaticProps` From a35b3c013cab2c2b3581af68089d8fd9302a26ff Mon Sep 17 00:00:00 2001 From: Rich Haines Date: Tue, 30 Nov 2021 09:50:23 +0100 Subject: [PATCH 20/70] Update docs/api-reference/data-fetching/getServerSideProps.md Co-authored-by: Lee Robinson --- docs/api-reference/data-fetching/getServerSideProps.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api-reference/data-fetching/getServerSideProps.md b/docs/api-reference/data-fetching/getServerSideProps.md index cc70a93d8c915..efa15fdb489e6 100644 --- a/docs/api-reference/data-fetching/getServerSideProps.md +++ b/docs/api-reference/data-fetching/getServerSideProps.md @@ -24,7 +24,7 @@ export async function getServerSideProps(context) { } ``` -You can import modules in top-level scope for use in `getServerSideProps`. Imports used will **not be bundled for the client-side**. This means you can write **server-side code directly in `getServerSideProps`**, including reading from the filesystem or a database. +You can import modules in top-level scope for use in `getServerSideProps`. Imports used will **not be bundled for the client-side**. This means you can write **server-side code directly in `getServerSideProps`**, including fetching data from your database. ## Context parameter From 2d7ce6393b79963094c1e3f5819e3091b9b0d5ac Mon Sep 17 00:00:00 2001 From: Rich Haines Date: Tue, 30 Nov 2021 09:51:37 +0100 Subject: [PATCH 21/70] Update docs/api-reference/data-fetching/getServerSideProps.md Co-authored-by: Lee Robinson --- docs/api-reference/data-fetching/getServerSideProps.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api-reference/data-fetching/getServerSideProps.md b/docs/api-reference/data-fetching/getServerSideProps.md index efa15fdb489e6..1ae0f554566fd 100644 --- a/docs/api-reference/data-fetching/getServerSideProps.md +++ b/docs/api-reference/data-fetching/getServerSideProps.md @@ -47,7 +47,7 @@ The `getServerSideProps` function should return an object with the following **o ### `props` -The `props` object is a key value pair, where each value is received by the page component. It should be a [serializable object](https://en.wikipedia.org/wiki/Serialization). +The `props` object is a key-value pair, where each value is forwarded to the page component. It should be a [serializable object](https://en.wikipedia.org/wiki/Serialization). ```jsx export async function getServerSideProps(context) { From 3ef05098950c74488bb375d428c1fe5ee78dc2c2 Mon Sep 17 00:00:00 2001 From: Rich Haines Date: Tue, 30 Nov 2021 09:51:58 +0100 Subject: [PATCH 22/70] Update docs/api-reference/data-fetching/getServerSideProps.md Co-authored-by: Lee Robinson --- docs/api-reference/data-fetching/getServerSideProps.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api-reference/data-fetching/getServerSideProps.md b/docs/api-reference/data-fetching/getServerSideProps.md index 1ae0f554566fd..8aa84d711b102 100644 --- a/docs/api-reference/data-fetching/getServerSideProps.md +++ b/docs/api-reference/data-fetching/getServerSideProps.md @@ -59,7 +59,7 @@ export async function getServerSideProps(context) { ### `notFound` -The `notFound` boolean allows the page to return a 404 status and page. With `notFound: true` the page will return a 404 even if there was a successfully generated page before. This is meant to support use-cases like user generated content getting removed by its author. +The `notFound` boolean allows the page to return a `404` status and [404 Page](/docs/advanced-features/custom-error-page.md#404-page). With `notFound: true`, the page will return a `404` even if there was a successfully generated page before. This is meant to support use-cases like user-generated content getting removed by its author. ```js export async function getServerSideProps(context) { From 2e0ab34dd04cfd56b5bd4bdf5739245217037b45 Mon Sep 17 00:00:00 2001 From: Rich Haines Date: Tue, 30 Nov 2021 09:52:11 +0100 Subject: [PATCH 23/70] Update docs/api-reference/data-fetching/getStaticPaths.md Co-authored-by: Lee Robinson --- docs/api-reference/data-fetching/getStaticPaths.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api-reference/data-fetching/getStaticPaths.md b/docs/api-reference/data-fetching/getStaticPaths.md index 51e2dcd541822..c1811e5be60cc 100644 --- a/docs/api-reference/data-fetching/getStaticPaths.md +++ b/docs/api-reference/data-fetching/getStaticPaths.md @@ -1,5 +1,5 @@ --- -description: Fetch data and generate static pages with `getStaticProps`. +description: Fetch data and generate static pages with `getStaticPaths`. --- # `getStaticPaths` From ce2699ba4700f4cc23bdb05abcac9a029a43641d Mon Sep 17 00:00:00 2001 From: Rich Haines Date: Tue, 30 Nov 2021 09:54:43 +0100 Subject: [PATCH 24/70] Update docs/api-reference/data-fetching/getStaticProps.md Co-authored-by: Lee Robinson --- docs/api-reference/data-fetching/getStaticProps.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api-reference/data-fetching/getStaticProps.md b/docs/api-reference/data-fetching/getStaticProps.md index 87387bc8eaa26..cd09cdded8197 100644 --- a/docs/api-reference/data-fetching/getStaticProps.md +++ b/docs/api-reference/data-fetching/getStaticProps.md @@ -51,7 +51,7 @@ The `getStaticProps` function should return an object with the following **optio ### `props` -The `props` object is a key value pair, where each value is received by the page component. It should be a [serializable object](https://en.wikipedia.org/wiki/Serialization) +The `props` object is a key-value pair, where each value is received by the page component. It should be a [serializable object](https://en.wikipedia.org/wiki/Serialization) ```jsx export async function getStaticProps(context) { From 82033609adf82f20caaa0d59fa5c3ededbe75007 Mon Sep 17 00:00:00 2001 From: Rich Haines Date: Tue, 30 Nov 2021 09:54:56 +0100 Subject: [PATCH 25/70] Update docs/api-reference/data-fetching/getStaticPaths.md Co-authored-by: Lee Robinson --- docs/api-reference/data-fetching/getStaticPaths.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api-reference/data-fetching/getStaticPaths.md b/docs/api-reference/data-fetching/getStaticPaths.md index c1811e5be60cc..3b3e5518f25a2 100644 --- a/docs/api-reference/data-fetching/getStaticPaths.md +++ b/docs/api-reference/data-fetching/getStaticPaths.md @@ -14,7 +14,7 @@ description: Fetch data and generate static pages with `getStaticPaths`. -When exporting an `async` function called `getStaticPaths` from a page that uses [dynamic routes](/docs/routing/dynamic-routes.md), Next.js will statically pre-render all the paths specified by `getStaticPaths`. +When exporting an `async` function called `getStaticPaths` from a page that uses [Dynamic Routes](/docs/routing/dynamic-routes.md), Next.js will statically pre-render all the paths specified by `getStaticPaths`. ```jsx export async function getStaticPaths() { From 5b48c169f772ebe37146418c892162151493ff62 Mon Sep 17 00:00:00 2001 From: Rich Haines Date: Tue, 30 Nov 2021 09:55:06 +0100 Subject: [PATCH 26/70] Update docs/api-reference/data-fetching/getStaticPaths.md Co-authored-by: Lee Robinson --- docs/api-reference/data-fetching/getStaticPaths.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api-reference/data-fetching/getStaticPaths.md b/docs/api-reference/data-fetching/getStaticPaths.md index 3b3e5518f25a2..95f77eb9edd5a 100644 --- a/docs/api-reference/data-fetching/getStaticPaths.md +++ b/docs/api-reference/data-fetching/getStaticPaths.md @@ -33,7 +33,7 @@ The `getStaticPaths` function should return an object with the following **requi ### `paths` -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`: +The `paths` key determines which paths will be pre-rendered. For example, suppose that you have a page that uses [Dynamic Routes](/docs/routing/dynamic-routes.md) named `pages/posts/[id].js`. If you export `getStaticPaths` from this page and return the following for `paths`: ```js return { From 2ef91741948dde03fb40b9ed820793591b965610 Mon Sep 17 00:00:00 2001 From: Rich Haines Date: Tue, 30 Nov 2021 09:55:23 +0100 Subject: [PATCH 27/70] Update docs/api-reference/data-fetching/getStaticPaths.md Co-authored-by: Lee Robinson --- docs/api-reference/data-fetching/getStaticPaths.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api-reference/data-fetching/getStaticPaths.md b/docs/api-reference/data-fetching/getStaticPaths.md index 95f77eb9edd5a..14dd6832330b5 100644 --- a/docs/api-reference/data-fetching/getStaticPaths.md +++ b/docs/api-reference/data-fetching/getStaticPaths.md @@ -45,7 +45,7 @@ return { } ``` -Then Next.js will statically generate `posts/1` and `posts/2` at build time using the page component in `pages/posts/[id].js`. +Then, Next.js will statically generate `/posts/1` and `/posts/2` during `next build` 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: From 77f2e744fe817e53f33e8ca9163d294e8ebf8577 Mon Sep 17 00:00:00 2001 From: Rich Haines Date: Tue, 30 Nov 2021 09:55:34 +0100 Subject: [PATCH 28/70] Update docs/api-reference/data-fetching/getStaticProps.md Co-authored-by: Lee Robinson --- docs/api-reference/data-fetching/getStaticProps.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api-reference/data-fetching/getStaticProps.md b/docs/api-reference/data-fetching/getStaticProps.md index cd09cdded8197..c53d338fcb98e 100644 --- a/docs/api-reference/data-fetching/getStaticProps.md +++ b/docs/api-reference/data-fetching/getStaticProps.md @@ -63,7 +63,7 @@ export async function getStaticProps(context) { ### `revalidate` -The `revalidate` property is the amount in seconds after which a page re-generation can occur (defaults to: `false` or no revalidating). +The `revalidate` property is the amount in seconds after which a page re-generation can occur (defaults to `false` or no revalidation). ```js // This function gets called at build time on server-side. From b0adf8d7620a072d48be79b3ea173a39458f990f Mon Sep 17 00:00:00 2001 From: Rich Haines Date: Tue, 30 Nov 2021 09:55:50 +0100 Subject: [PATCH 29/70] Update docs/api-reference/data-fetching/getStaticPaths.md Co-authored-by: Lee Robinson --- docs/api-reference/data-fetching/getStaticPaths.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api-reference/data-fetching/getStaticPaths.md b/docs/api-reference/data-fetching/getStaticPaths.md index 14dd6832330b5..3bf3c5c637fea 100644 --- a/docs/api-reference/data-fetching/getStaticPaths.md +++ b/docs/api-reference/data-fetching/getStaticPaths.md @@ -47,7 +47,7 @@ return { Then, Next.js will statically generate `/posts/1` and `/posts/2` during `next build` 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: +The value for each `params` object 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`. From d24d1a73b4470fbfe59ffeae4fbedea6e06fc486 Mon Sep 17 00:00:00 2001 From: Rich Haines Date: Tue, 30 Nov 2021 09:56:11 +0100 Subject: [PATCH 30/70] Update docs/api-reference/data-fetching/getStaticPaths.md Co-authored-by: Lee Robinson --- docs/api-reference/data-fetching/getStaticPaths.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api-reference/data-fetching/getStaticPaths.md b/docs/api-reference/data-fetching/getStaticPaths.md index 3bf3c5c637fea..642f2fbf7174a 100644 --- a/docs/api-reference/data-fetching/getStaticPaths.md +++ b/docs/api-reference/data-fetching/getStaticPaths.md @@ -50,7 +50,7 @@ Then, Next.js will statically generate `/posts/1` and `/posts/2` during `next bu The value for each `params` object 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`. +- If the page name uses [catch-all routes](/docs/routing/dynamic-routes.md#catch-all-routes) like `pages/[...slug]`, then `params` should contain `slug` (which is an array). If this array is `['hello', 'world']`, then Next.js will statically generate the page at `/hello/world`. - If the page uses an optional catch-all route, supply `null`, `[]`, `undefined` or `false` to render the root-most route. For example, if you supply `slug: false` for `pages/[[...slug]]`, Next.js will statically generate the page `/`. ### `fallback: false` From b5c77cdb6118ca53161b6591a9f4bbe18f7a8470 Mon Sep 17 00:00:00 2001 From: Rich Haines Date: Tue, 30 Nov 2021 09:56:23 +0100 Subject: [PATCH 31/70] Update docs/api-reference/data-fetching/getStaticPaths.md Co-authored-by: Lee Robinson --- docs/api-reference/data-fetching/getStaticPaths.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api-reference/data-fetching/getStaticPaths.md b/docs/api-reference/data-fetching/getStaticPaths.md index 642f2fbf7174a..d021110647b8b 100644 --- a/docs/api-reference/data-fetching/getStaticPaths.md +++ b/docs/api-reference/data-fetching/getStaticPaths.md @@ -51,7 +51,7 @@ The value for each `params` object must match the parameters used in the page na - If the page name is `pages/posts/[postId]/[commentId]`, then `params` should contain `postId` and `commentId`. - If the page name uses [catch-all routes](/docs/routing/dynamic-routes.md#catch-all-routes) like `pages/[...slug]`, then `params` should contain `slug` (which is an array). If this array is `['hello', 'world']`, then Next.js will statically generate the page at `/hello/world`. -- If the page uses an optional catch-all route, supply `null`, `[]`, `undefined` or `false` to render the root-most route. For example, if you supply `slug: false` for `pages/[[...slug]]`, Next.js will statically generate the page `/`. +- If the page uses an [optional catch-all route](/docs/routing/dynamic-routes.md#optional-catch-all-routes), use `null`, `[]`, `undefined` or `false` to render the root-most route. For example, if you supply `slug: false` for `pages/[[...slug]]`, Next.js will statically generate the page `/`. ### `fallback: false` From e23b1aecbe44574bf4baf34b4b184d2a03af1163 Mon Sep 17 00:00:00 2001 From: Rich Haines Date: Tue, 30 Nov 2021 09:56:45 +0100 Subject: [PATCH 32/70] Update docs/api-reference/data-fetching/getStaticPaths.md Co-authored-by: Lee Robinson --- docs/api-reference/data-fetching/getStaticPaths.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api-reference/data-fetching/getStaticPaths.md b/docs/api-reference/data-fetching/getStaticPaths.md index d021110647b8b..484a898ae6d0b 100644 --- a/docs/api-reference/data-fetching/getStaticPaths.md +++ b/docs/api-reference/data-fetching/getStaticPaths.md @@ -55,7 +55,7 @@ The value for each `params` object must match the parameters used in the page na ### `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. +If `fallback` is `false`, then any paths not returned by `getStaticPaths` will result in a **404 page**. This is useful if you have a small number of paths to pre-render and want to statically generate them all during `next build`. It is 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 will need to run the build again. From b191d3f66e0342d62171a1a42145f3a490490de7 Mon Sep 17 00:00:00 2001 From: Rich Haines Date: Tue, 30 Nov 2021 09:56:54 +0100 Subject: [PATCH 33/70] Update docs/api-reference/data-fetching/getStaticProps.md Co-authored-by: Lee Robinson --- docs/api-reference/data-fetching/getStaticProps.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api-reference/data-fetching/getStaticProps.md b/docs/api-reference/data-fetching/getStaticProps.md index c53d338fcb98e..a93068cd27547 100644 --- a/docs/api-reference/data-fetching/getStaticProps.md +++ b/docs/api-reference/data-fetching/getStaticProps.md @@ -89,7 +89,7 @@ More information is covered in [Incremental Static Regeneration](/docs/basic-fea ### `notFound` -The `notFound` boolean allows the page to return a 404 status and page. With `notFound: true` the page will return a 404 even if there was a successfully generated page before. This is meant to support use-cases like user generated content getting removed by its author. +The `notFound` boolean allows the page to return a `404` status and [404 Page](/docs/advanced-features/custom-error-page.md#404-page). With `notFound: true`, the page will return a `404` even if there was a successfully generated page before. This is meant to support use-cases like user-generated content getting removed by its author. ```js export async function getStaticProps(context) { From de68ebed157013f303fc83c08dcef000a1830237 Mon Sep 17 00:00:00 2001 From: Rich Haines Date: Tue, 30 Nov 2021 09:57:22 +0100 Subject: [PATCH 34/70] Update docs/api-reference/data-fetching/getStaticProps.md Co-authored-by: Lee Robinson --- docs/api-reference/data-fetching/getStaticProps.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api-reference/data-fetching/getStaticProps.md b/docs/api-reference/data-fetching/getStaticProps.md index a93068cd27547..9639421c719c0 100644 --- a/docs/api-reference/data-fetching/getStaticProps.md +++ b/docs/api-reference/data-fetching/getStaticProps.md @@ -26,7 +26,7 @@ export async function getStaticProps(context) { ``` You can import modules in top-level scope for use in `getStaticProps`. -Imports used will **not be bundled for the client-side**. This means you can write **server-side code directly in `getStaticProps`**, including reading from the filesystem or a database. +Imports used will **not be bundled for the client-side**. This means you can write **server-side code directly in `getStaticProps`**, including fetching data from your database. You should not use the [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) `API` to call an [`API` route](/docs/api-routes/introduction.md) in `getStaticProps`. From cebe6ec07bd310389c2315432101e882343f1432 Mon Sep 17 00:00:00 2001 From: molebox Date: Thu, 16 Dec 2021 11:07:28 +0100 Subject: [PATCH 35/70] Conflicts part 2 --- .../data-fetching/getServerSideProps.md | 2 +- .../data-fetching/getStaticPaths.md | 4 +- .../data-fetching/getStaticProps.md | 57 ++++--------------- .../data-fetching/getServerSideProps.md | 6 +- .../data-fetching/getStaticPaths.md | 6 +- .../data-fetching/getStaticProps.md | 2 - 6 files changed, 19 insertions(+), 58 deletions(-) diff --git a/docs/api-reference/data-fetching/getServerSideProps.md b/docs/api-reference/data-fetching/getServerSideProps.md index 8aa84d711b102..f4c118342a00f 100644 --- a/docs/api-reference/data-fetching/getServerSideProps.md +++ b/docs/api-reference/data-fetching/getServerSideProps.md @@ -1,5 +1,5 @@ --- -description: Fetch data on each request with `getServerSideProps`. Learn more about this API for data fetching in Next.js. +description: API reference for `getServerSideProps`. Learn how to fetch data on each request with Next.js. --- # `getServerSideProps` diff --git a/docs/api-reference/data-fetching/getStaticPaths.md b/docs/api-reference/data-fetching/getStaticPaths.md index 484a898ae6d0b..cdec668849b12 100644 --- a/docs/api-reference/data-fetching/getStaticPaths.md +++ b/docs/api-reference/data-fetching/getStaticPaths.md @@ -1,5 +1,5 @@ --- -description: Fetch data and generate static pages with `getStaticPaths`. +description: API reference for `getStaticPaths`. Learn how to fetch data and generate static pages with `getStaticPaths`. --- # `getStaticPaths` @@ -57,7 +57,7 @@ The value for each `params` object must match the parameters used in the page na If `fallback` is `false`, then any paths not returned by `getStaticPaths` will result in a **404 page**. This is useful if you have a small number of paths to pre-render and want to statically generate them all during `next build`. -It is 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 will need to run the build again. +When `next build` is run, Next.js will check if `getStaticPaths` returned `fallback: false`, it will then build **only** the paths returned by `getStaticPaths`. This option is useful if you have a small number of paths to create, or new page data is not added often. If you find that you need to add more paths, and you have `fallback: false`, you will need to run `next build` again so that the new paths can be generated. The following example 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`](/docs/api-reference/data-fetching/getStaticProps.md). diff --git a/docs/api-reference/data-fetching/getStaticProps.md b/docs/api-reference/data-fetching/getStaticProps.md index 9639421c719c0..80b65b5a7ac28 100644 --- a/docs/api-reference/data-fetching/getStaticProps.md +++ b/docs/api-reference/data-fetching/getStaticProps.md @@ -1,5 +1,5 @@ --- -description: Fetch data at build time with `getStaticProps`. +description: API reference for `getStaticProps`. Learn how to use `getStaticProps` to generate static pages with Next.js. --- # `getStaticProps` @@ -28,11 +28,11 @@ export async function getStaticProps(context) { You can import modules in top-level scope for use in `getStaticProps`. Imports used will **not be bundled for the client-side**. This means you can write **server-side code directly in `getStaticProps`**, including fetching data from your database. -You should not use the [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) `API` to call an [`API` route](/docs/api-routes/introduction.md) in `getStaticProps`. +If you are calling an external `API`, or fetching data from a database or Content Management System (CMS) in an `API` route, you can move that logic to `getStaticProps`, as both `API` routes and `getStaticProps` run on the server. -Instead, directly import the logic used inside your `API` route. You may need to slightly refactor your code for this approach. +Calling an `API` route from within `getStaticProps` can result in an additional call, reducing performance. -The `fetch()` `API` _can_ be used to fetch external data, such as from a Content Management System (CMS) or `API`. +Alternatively, if you are **not** using `API` routes to fetch data, then the [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) `API` _can_ be used directly in `getStaticProps` to fetch data. ## Context parameter @@ -85,7 +85,7 @@ export async function getStaticProps() { } ``` -More information is covered in [Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration) +Learn more about [Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration) ### `notFound` @@ -112,7 +112,9 @@ export async function getStaticProps(context) { ### `redirect` -The `redirect` object allows redirecting to internal or external resources. It should match the shape of `{ destination: string, permanent: boolean }`. In some rare cases, you might need to assign a custom status code for older `HTTP` Clients to properly redirect. In these cases, you can use the `statusCode` property instead of the `permanent` property, but not both. You can also set `basePath: false` similar to redirects in `next.config.js`. +The `redirect` object allows redirecting to internal or external resources. It should match the shape of `{ destination: string, permanent: boolean }`. + +In some rare cases, you might need to assign a custom status code for older `HTTP` clients to properly redirect. In these cases, you can use the `statusCode` property instead of the `permanent` property, **but not both**. You can also set `basePath: false` similar to redirects in `next.config.js`. ```js export async function getStaticProps(context) { @@ -124,6 +126,7 @@ export async function getStaticProps(context) { redirect: { destination: '/', permanent: false, + // statusCode: 301 }, } } @@ -134,47 +137,7 @@ export async function getStaticProps(context) { } ``` -Redirecting at build-time is currently not allowed and if the redirects are known at build-time they should be added in [`next.config.js`](/docs/api-reference/next.config.js/redirects.md). - -## TypeScript: Use `GetStaticProps` - -You can use the `GetStaticProps` type from `next` to type the function: - -```ts -import { GetStaticProps } from 'next' - -export const getStaticProps: GetStaticProps = async (context) => { - // ... -} -``` - -If you want to get inferred typings for your props, you can use `InferGetStaticPropsType`: - -```tsx -import { InferGetStaticPropsType } from 'next' - -type Post = { - author: string - content: string -} - -export const getStaticProps = async () => { - const res = await fetch('https://.../posts') - const posts: Post[] = await res.json() - - return { - props: { - posts, - }, - } -} - -function Blog({ posts }: InferGetStaticPropsType) { - // will resolve posts to type Post[] -} - -export default Blog -``` +If the redirects are known at build-time, they should be added in [`next.config.js`](/docs/api-reference/next.config.js/redirects.md) instead. ## Reading files: Use `process.cwd()` diff --git a/docs/basic-features/data-fetching/getServerSideProps.md b/docs/basic-features/data-fetching/getServerSideProps.md index da55726c52738..d255838475dab 100644 --- a/docs/basic-features/data-fetching/getServerSideProps.md +++ b/docs/basic-features/data-fetching/getServerSideProps.md @@ -1,5 +1,5 @@ --- -description: Fetch data at build time with `getStaticProps` API reference. +description: Fetch data on each request with `getServerSideProps`. --- # `getServerSideProps` @@ -18,7 +18,7 @@ The [`getServerSideProps` API reference](/docs/api-reference/data-fetching/getSe ## When should I use `getServerSideProps`? -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`](/docs/basic-features/data-fetching/getStaticProps.md) because the server must compute the result on every request, and the result cannot be cached by a CDN without extra configuration. +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)](/learn/seo/web-performance) will be slower than [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) because the server must compute the result on every request, and the result can only be cached by a CDN using `cache-control` headers (which could require extra configuration). If you do not need to pre-render the data, then you should consider fetching data on the [client side](#fetching-data-on-the-client-side). @@ -82,7 +82,7 @@ Also, you must use `export async function getServerSideProps() {}` — it will * ## 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: +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](/docs/basic-features/client-side.md). An example of this is user-specific 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. diff --git a/docs/basic-features/data-fetching/getStaticPaths.md b/docs/basic-features/data-fetching/getStaticPaths.md index 614fb039023e9..9f779e6dfea7e 100644 --- a/docs/basic-features/data-fetching/getStaticPaths.md +++ b/docs/basic-features/data-fetching/getStaticPaths.md @@ -1,10 +1,10 @@ --- -description: Fetch data at build time with `getStaticProps` API reference. +description: Fetch data and generate static pages with `getStaticProps`. Learn more about this API for data fetching in Next.js. --- # `getStaticPaths` -If a page has [dynamic routes](/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 a page has [Dynamic Routes](/docs/routing/dynamic-routes.md) and uses `getStaticProps`, it needs to define a list of paths to be statically generated. When you export an `async` function called `getStaticPaths` (static generation) from a page that uses dynamic routes, Next.js will statically pre-render all the paths specified by `getStaticPaths`. @@ -53,7 +53,7 @@ Note that you **cannot** use `getStaticPaths` with [`getServerSideProps`](/docs/ ### Only runs at build time on server-side -`getStaticPaths` only runs at build time on server-side. +`getStaticPaths` only runs at build time on server-side. Except when using [Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration.md), it will run at request time. ### Only allowed in a page diff --git a/docs/basic-features/data-fetching/getStaticProps.md b/docs/basic-features/data-fetching/getStaticProps.md index a416fec66619f..b54449db54af9 100644 --- a/docs/basic-features/data-fetching/getStaticProps.md +++ b/docs/basic-features/data-fetching/getStaticProps.md @@ -63,8 +63,6 @@ function Blog({ posts }: InferGetStaticPropsType) { export default Blog ``` -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. - ## Using `getStaticProps` to fetch data from a CMS The following example shows how you can fetch a list of blog posts from a CMS. From 8ef0b0a79d0620c986037435bd6073958c596bd0 Mon Sep 17 00:00:00 2001 From: Rich Haines Date: Tue, 30 Nov 2021 17:19:57 +0100 Subject: [PATCH 36/70] Update docs/basic-features/data-fetching/getStaticPaths.md Co-authored-by: Lee Robinson --- docs/basic-features/data-fetching/getStaticPaths.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/basic-features/data-fetching/getStaticPaths.md b/docs/basic-features/data-fetching/getStaticPaths.md index 9f779e6dfea7e..1248508f55168 100644 --- a/docs/basic-features/data-fetching/getStaticPaths.md +++ b/docs/basic-features/data-fetching/getStaticPaths.md @@ -53,7 +53,7 @@ Note that you **cannot** use `getStaticPaths` with [`getServerSideProps`](/docs/ ### Only runs at build time on server-side -`getStaticPaths` only runs at build time on server-side. Except when using [Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration.md), it will run at request time. +`getStaticPaths` only runs at build time on server-side. If you're using [Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration.md), `getStaticPaths` can also be ran on-demand _in the background_, but still only on the server-side.. ### Only allowed in a page From 2577778408b0d9835a4f1ce02d5ce15adb0c6f7f Mon Sep 17 00:00:00 2001 From: Rich Haines Date: Fri, 10 Dec 2021 09:09:43 +0100 Subject: [PATCH 37/70] Update docs/basic-features/data-fetching/index.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Balázs Orbán --- docs/basic-features/data-fetching/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/basic-features/data-fetching/index.md b/docs/basic-features/data-fetching/index.md index ef169922967f6..c57226365c9a1 100644 --- a/docs/basic-features/data-fetching/index.md +++ b/docs/basic-features/data-fetching/index.md @@ -1,5 +1,5 @@ --- -description: 'Data fetching in Next.js allows you to render your content in different ways, depending on your applications use case. These include pre-rendering with server-side rendering or static-site generation, and incremental static regeneration. Learn how to manage your application data in Next.js.' +description: 'Data fetching in Next.js allows you to render your content in different ways, depending on your application's use case. These include pre-rendering with server-side rendering or static-site generation, and incremental static regeneration. Learn how to manage your application data in Next.js.' --- # Data Fetching Overview From 3d392008384dfddafe7b000cf83b88230cabb876 Mon Sep 17 00:00:00 2001 From: Rich Haines Date: Fri, 10 Dec 2021 09:10:37 +0100 Subject: [PATCH 38/70] Update docs/basic-features/data-fetching/index.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Balázs Orbán --- docs/basic-features/data-fetching/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/basic-features/data-fetching/index.md b/docs/basic-features/data-fetching/index.md index c57226365c9a1..ad5d3e72c7aa5 100644 --- a/docs/basic-features/data-fetching/index.md +++ b/docs/basic-features/data-fetching/index.md @@ -26,7 +26,7 @@ description: 'Data fetching in Next.js allows you to render your content in diff -Data fetching in Next.js allows you to render your content in different ways, depending on your applications use case. These include pre-rendering with **Server-side Rendering** or **Static Generation**, and updating or creating content at runtime with **Incremental Static Regeneration**. +Data fetching in Next.js allows you to render your content in different ways, depending on your application's use case. These include pre-rendering with **Server-side Rendering** or **Static Generation**, and updating or creating content at runtime with **Incremental Static Regeneration**.
From 34f65611b60c5aaa7237989d6b4bfebf7bf18615 Mon Sep 17 00:00:00 2001 From: Rich Haines Date: Fri, 10 Dec 2021 09:11:05 +0100 Subject: [PATCH 39/70] Update docs/api-reference/data-fetching/getInitialProps.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Balázs Orbán --- docs/api-reference/data-fetching/getInitialProps.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api-reference/data-fetching/getInitialProps.md b/docs/api-reference/data-fetching/getInitialProps.md index abf8f39646640..a83593067d252 100644 --- a/docs/api-reference/data-fetching/getInitialProps.md +++ b/docs/api-reference/data-fetching/getInitialProps.md @@ -4,7 +4,7 @@ description: Enable Server-Side Rendering in a page and do initial data populati # getInitialProps -**Recommended: [`getStaticProps`](/docs/basic-features/data-fetching.md#getstaticprops-static-generation) or [`getServerSideProps`](/docs/basic-features/data-fetching.md#getserversideprops-server-side-rendering)** instead of `getInitialProps`. These new data fetching methods allow you to have a granular choice between static generation and server-side rendering. +**Recommended: [`getStaticProps`](/docs/basic-features/data-fetching.md#getstaticprops-static-generation) or [`getServerSideProps`](/docs/basic-features/data-fetching.md#getserversideprops-server-side-rendering)** instead of `getInitialProps`. These data fetching methods allow you to have a granular choice between static generation and server-side rendering. `getInitialProps` enables [server-side rendering](/docs/basic-features/pages.md#server-side-rendering) in a page and allows you to do **initial data population**, it means sending the [page](/docs/basic-features/pages.md) with the data already populated from the server. This is especially useful for [SEO](https://en.wikipedia.org/wiki/Search_engine_optimization). From 38976b936387f5e9500a0d4d8397168a3ba889ef Mon Sep 17 00:00:00 2001 From: Rich Haines Date: Fri, 10 Dec 2021 09:17:07 +0100 Subject: [PATCH 40/70] Update docs/api-reference/data-fetching/getServerSideProps.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Balázs Orbán --- docs/api-reference/data-fetching/getServerSideProps.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api-reference/data-fetching/getServerSideProps.md b/docs/api-reference/data-fetching/getServerSideProps.md index f4c118342a00f..2a09f88039ba0 100644 --- a/docs/api-reference/data-fetching/getServerSideProps.md +++ b/docs/api-reference/data-fetching/getServerSideProps.md @@ -80,7 +80,7 @@ export async function getServerSideProps(context) { ### `redirect` -The `redirect` object to allows redirecting to internal and external resources. It should match the shape of `{ destination: string, permanent: boolean }`. In some rare cases, you might need to assign a custom status code for older `HTTP` Clients to properly redirect. In these cases, you can use the `statusCode` property instead of the `permanent` property, but not both. +The `redirect` object allows redirecting to internal and external resources. It should match the shape of `{ destination: string, permanent: boolean }`. In some rare cases, you might need to assign a custom status code for older `HTTP` clients to properly redirect. In these cases, you can use the `statusCode` property instead of the `permanent` property, but not both. ```js export async function getServerSideProps(context) { From a80eece1f353127313562a72a52ad2aad7fbf408 Mon Sep 17 00:00:00 2001 From: Rich Haines Date: Fri, 10 Dec 2021 09:17:50 +0100 Subject: [PATCH 41/70] Update docs/api-reference/data-fetching/getStaticPaths.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Balázs Orbán --- docs/api-reference/data-fetching/getStaticPaths.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api-reference/data-fetching/getStaticPaths.md b/docs/api-reference/data-fetching/getStaticPaths.md index cdec668849b12..1eb9b9e5b78ab 100644 --- a/docs/api-reference/data-fetching/getStaticPaths.md +++ b/docs/api-reference/data-fetching/getStaticPaths.md @@ -22,7 +22,7 @@ export async function getStaticPaths() { paths: [ { params: { ... } } // See the "paths" section below ], - fallback: true or false // See the "fallback" section below + fallback: true, false or "blocking" // See the "fallback" section below }; } ``` From 2a339c397b07401007d8570600f750ac468fb80a Mon Sep 17 00:00:00 2001 From: Rich Haines Date: Fri, 10 Dec 2021 09:18:27 +0100 Subject: [PATCH 42/70] Update docs/api-reference/data-fetching/getStaticPaths.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Balázs Orbán --- docs/api-reference/data-fetching/getStaticPaths.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api-reference/data-fetching/getStaticPaths.md b/docs/api-reference/data-fetching/getStaticPaths.md index 1eb9b9e5b78ab..949a56300710f 100644 --- a/docs/api-reference/data-fetching/getStaticPaths.md +++ b/docs/api-reference/data-fetching/getStaticPaths.md @@ -119,7 +119,7 @@ If `fallback` is `true`, then the behavior of `getStaticProps` changes in the fo #### When is `fallback: true` useful? -`fallback: true` is useful if your app has a very large number of static pages that depend on data (such as a very large e-commerce site). If you want to pre-render all product pages, the builds would take forever. +`fallback: true` is useful if your app has a very large number of static pages that depend on data (such as a very large e-commerce site). If you want to pre-render all product pages, the builds would take a very long time. Instead, you may statically generate a small subset of pages and use `fallback: true` for the rest. When someone requests a page that is not generated yet, the user will see the page with a loading indicator or skeleton component. From f6bc0e28bd25b56c83cc1a72eda7c6dacc4e02fa Mon Sep 17 00:00:00 2001 From: Rich Haines Date: Fri, 10 Dec 2021 09:19:16 +0100 Subject: [PATCH 43/70] Update docs/api-reference/data-fetching/getServerSideProps.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Balázs Orbán --- docs/api-reference/data-fetching/getServerSideProps.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api-reference/data-fetching/getServerSideProps.md b/docs/api-reference/data-fetching/getServerSideProps.md index 2a09f88039ba0..86e9eb01b2309 100644 --- a/docs/api-reference/data-fetching/getServerSideProps.md +++ b/docs/api-reference/data-fetching/getServerSideProps.md @@ -59,7 +59,7 @@ export async function getServerSideProps(context) { ### `notFound` -The `notFound` boolean allows the page to return a `404` status and [404 Page](/docs/advanced-features/custom-error-page.md#404-page). With `notFound: true`, the page will return a `404` even if there was a successfully generated page before. This is meant to support use-cases like user-generated content getting removed by its author. +The `notFound` boolean allows the page to return a `404` status and [404 Page](/docs/advanced-features/custom-error-page.md#404-page). With `notFound: true`, the page will return a `404` even if there was a successfully generated page before. This is meant to support use cases like user-generated content getting removed by its author. ```js export async function getServerSideProps(context) { From 8fac37d19b351cf3eda051d8e5aaa819ca959010 Mon Sep 17 00:00:00 2001 From: Rich Haines Date: Fri, 10 Dec 2021 09:20:05 +0100 Subject: [PATCH 44/70] Update docs/api-reference/data-fetching/getStaticProps.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Balázs Orbán --- docs/api-reference/data-fetching/getStaticProps.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api-reference/data-fetching/getStaticProps.md b/docs/api-reference/data-fetching/getStaticProps.md index 80b65b5a7ac28..33d1158e3a7bc 100644 --- a/docs/api-reference/data-fetching/getStaticProps.md +++ b/docs/api-reference/data-fetching/getStaticProps.md @@ -89,7 +89,7 @@ Learn more about [Incremental Static Regeneration](/docs/basic-features/data-fet ### `notFound` -The `notFound` boolean allows the page to return a `404` status and [404 Page](/docs/advanced-features/custom-error-page.md#404-page). With `notFound: true`, the page will return a `404` even if there was a successfully generated page before. This is meant to support use-cases like user-generated content getting removed by its author. +The `notFound` boolean allows the page to return a `404` status and [404 Page](/docs/advanced-features/custom-error-page.md#404-page). With `notFound: true`, the page will return a `404` even if there was a successfully generated page before. This is meant to support use cases like user-generated content getting removed by its author. ```js export async function getStaticProps(context) { From c62565cef4aa37f7a09b3e127a9e6bc02b024485 Mon Sep 17 00:00:00 2001 From: Rich Haines Date: Fri, 10 Dec 2021 09:20:43 +0100 Subject: [PATCH 45/70] Update docs/basic-features/data-fetching/client-side.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Balázs Orbán --- docs/basic-features/data-fetching/client-side.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/basic-features/data-fetching/client-side.md b/docs/basic-features/data-fetching/client-side.md index 372b6f6c9d904..41e4e56cf3ee4 100644 --- a/docs/basic-features/data-fetching/client-side.md +++ b/docs/basic-features/data-fetching/client-side.md @@ -1,5 +1,5 @@ --- -description: 'Learn how to use SWR, a data fetching React hook that handles caching, revalidation, focus tracking, refetching on interval and more.' +description: 'Learn how to use SWR, a data fetching React hook library that handles caching, revalidation, focus tracking, refetching on interval and more.' --- # Client-side data fetching From c682442bc73e6fdb2246c401ee1a1625f50c72d6 Mon Sep 17 00:00:00 2001 From: Rich Haines Date: Fri, 10 Dec 2021 09:21:05 +0100 Subject: [PATCH 46/70] Update docs/basic-features/data-fetching/client-side.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Balázs Orbán --- docs/basic-features/data-fetching/client-side.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/basic-features/data-fetching/client-side.md b/docs/basic-features/data-fetching/client-side.md index 41e4e56cf3ee4..3522144187ee2 100644 --- a/docs/basic-features/data-fetching/client-side.md +++ b/docs/basic-features/data-fetching/client-side.md @@ -4,7 +4,7 @@ description: 'Learn how to use SWR, a data fetching React hook library that hand # Client-side data fetching -Client-side data fetching is useful when your page doesn't require SEO indexing, when you don't need to pre-render your data, or when your pages content needs to update frequently. Unlike the server-side rendering APIs, you can use client side data fetching at the component level. +Client-side data fetching is useful when your page doesn't require SEO indexing, when you don't need to pre-render your data, or when the content of your pages needs to update frequently. Unlike the server-side rendering APIs, you can use client-side data fetching at the component level. If done at the page level, the data is fetched at runtime, and the contents of the page updated as the data changes. When used at the component level, the data is fetched at the time of the component mount, and the contents of the component are updated as the data changes. From 0606f5b302775eca65f413ecae538f1ca50cdea3 Mon Sep 17 00:00:00 2001 From: Rich Haines Date: Fri, 10 Dec 2021 09:21:39 +0100 Subject: [PATCH 47/70] Update docs/basic-features/data-fetching/client-side.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Balázs Orbán --- docs/basic-features/data-fetching/client-side.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/basic-features/data-fetching/client-side.md b/docs/basic-features/data-fetching/client-side.md index 3522144187ee2..766e81a1f1268 100644 --- a/docs/basic-features/data-fetching/client-side.md +++ b/docs/basic-features/data-fetching/client-side.md @@ -6,7 +6,7 @@ description: 'Learn how to use SWR, a data fetching React hook library that hand Client-side data fetching is useful when your page doesn't require SEO indexing, when you don't need to pre-render your data, or when the content of your pages needs to update frequently. Unlike the server-side rendering APIs, you can use client-side data fetching at the component level. -If done at the page level, the data is fetched at runtime, and the contents of the page updated as the data changes. When used at the component level, the data is fetched at the time of the component mount, and the contents of the component are updated as the data changes. +If done at the page level, the data is fetched at runtime, and the content of the page is updated as the data changes. When used at the component level, the data is fetched at the time of the component mount, and the content of the component is updated as the data changes. It's important to note that using client-side data fetching can affect the performance of your application and the load speed of your pages. This is because the data fetching is done at the time of the component or pages mount, and the data is not cached. From cfe9d96e7a357127378c61001c31910aae89c564 Mon Sep 17 00:00:00 2001 From: Rich Haines Date: Fri, 10 Dec 2021 09:22:01 +0100 Subject: [PATCH 48/70] Update docs/basic-features/data-fetching/client-side.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Balázs Orbán --- docs/basic-features/data-fetching/client-side.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/basic-features/data-fetching/client-side.md b/docs/basic-features/data-fetching/client-side.md index 766e81a1f1268..667f1efe5ca0f 100644 --- a/docs/basic-features/data-fetching/client-side.md +++ b/docs/basic-features/data-fetching/client-side.md @@ -43,7 +43,7 @@ function Profile() { # Client-side data fetching with SWR -The team behind Next.js has created a React hook for data fetching called [**SWR**](https://swr.vercel.app/). It is **highly recommend** if you are fetching data on the client side. It handles caching, revalidation, focus tracking, refetching on interval, and more. +The team behind Next.js has created a React hook library for data fetching called [**SWR**](https://swr.vercel.app/). It is **highly recommend** if you are fetching data on the client-side. It handles caching, revalidation, focus tracking, refetching on intervals, and more. Using the same example as above, we can now use SWR to fetch the profile data. SWR will automatically cache the data for us, and will revalidate the data if it is stale. From 14136a547f2e5d3a5238892778f8c5ec41b92783 Mon Sep 17 00:00:00 2001 From: Rich Haines Date: Fri, 10 Dec 2021 09:22:43 +0100 Subject: [PATCH 49/70] Update docs/basic-features/data-fetching/client-side.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Balázs Orbán --- docs/basic-features/data-fetching/client-side.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/basic-features/data-fetching/client-side.md b/docs/basic-features/data-fetching/client-side.md index 667f1efe5ca0f..16a68db8856fa 100644 --- a/docs/basic-features/data-fetching/client-side.md +++ b/docs/basic-features/data-fetching/client-side.md @@ -45,7 +45,7 @@ function Profile() { The team behind Next.js has created a React hook library for data fetching called [**SWR**](https://swr.vercel.app/). It is **highly recommend** if you are fetching data on the client-side. It handles caching, revalidation, focus tracking, refetching on intervals, and more. -Using the same example as above, we can now use SWR to fetch the profile data. SWR will automatically cache the data for us, and will revalidate the data if it is stale. +Using the same example as above, we can now use SWR to fetch the profile data. SWR will automatically cache the data for us and will revalidate the data if it becomes stale. For more information on using SWR, check out the [SWR docs](https://swr.vercel.app/docs). From 58dce759ef774650717e37ce1e94dab339b6820c Mon Sep 17 00:00:00 2001 From: Rich Haines Date: Fri, 10 Dec 2021 09:23:05 +0100 Subject: [PATCH 50/70] Update docs/basic-features/data-fetching/getServerSideProps.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Balázs Orbán --- docs/basic-features/data-fetching/getServerSideProps.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/basic-features/data-fetching/getServerSideProps.md b/docs/basic-features/data-fetching/getServerSideProps.md index d255838475dab..4ac694ba833e6 100644 --- a/docs/basic-features/data-fetching/getServerSideProps.md +++ b/docs/basic-features/data-fetching/getServerSideProps.md @@ -18,7 +18,7 @@ The [`getServerSideProps` API reference](/docs/api-reference/data-fetching/getSe ## When should I use `getServerSideProps`? -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)](/learn/seo/web-performance) will be slower than [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) because the server must compute the result on every request, and the result can only be cached by a CDN using `cache-control` headers (which could require extra configuration). +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)](/learn/seo/web-performance) will be higher than [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) because the server must compute the result on every request, and the result can only be cached by a CDN using `cache-control` headers (which could require extra configuration). If you do not need to pre-render the data, then you should consider fetching data on the [client side](#fetching-data-on-the-client-side). From da73eeff9a13485567a06ce7da8ebee84735cf35 Mon Sep 17 00:00:00 2001 From: Rich Haines Date: Fri, 10 Dec 2021 09:23:18 +0100 Subject: [PATCH 51/70] Update docs/basic-features/data-fetching/getServerSideProps.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Balázs Orbán --- docs/basic-features/data-fetching/getServerSideProps.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/basic-features/data-fetching/getServerSideProps.md b/docs/basic-features/data-fetching/getServerSideProps.md index 4ac694ba833e6..4891371ed667f 100644 --- a/docs/basic-features/data-fetching/getServerSideProps.md +++ b/docs/basic-features/data-fetching/getServerSideProps.md @@ -72,7 +72,7 @@ export default Page `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`](/docs/api-reference/next/link.md)) or ([`next/router`](/docs/api-reference/next/router.md)), Next.js sends an API request to the server, which runs `getServerSideProps`. It’ll return 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`](/docs/api-reference/next/link.md) or [`next/router`](/docs/api-reference/next/router.md), Next.js sends an API request to the server, which runs `getServerSideProps`. It’ll return 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 You can use the [next-code-elimination tool](https://next-code-elimination.vercel.app/) to verify what Next.js eliminates from the client-side bundle. From b991731c16296050536dd617da00721a6bb3a91d Mon Sep 17 00:00:00 2001 From: Rich Haines Date: Fri, 10 Dec 2021 09:23:40 +0100 Subject: [PATCH 52/70] Update docs/basic-features/data-fetching/getServerSideProps.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Balázs Orbán --- docs/basic-features/data-fetching/getServerSideProps.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/basic-features/data-fetching/getServerSideProps.md b/docs/basic-features/data-fetching/getServerSideProps.md index 4891371ed667f..92e7b1e40cc20 100644 --- a/docs/basic-features/data-fetching/getServerSideProps.md +++ b/docs/basic-features/data-fetching/getServerSideProps.md @@ -78,7 +78,7 @@ You can use the [next-code-elimination tool](https://next-code-elimination.verce `getServerSideProps` can only be exported from a **page**. You can’t export it from non-page files. -Also, you must use `export async function getServerSideProps() {}` — it will **not** work if you add `getServerSideProps` as a property of the page component. +Also, you must export `getServerSideProps` as a standalone function. — it will **not** work if you add `getServerSideProps` as a property of the page component. ## Fetching data on the client side From 489f665b62b66db4c1fc9543ad9ff4c2dc9452f9 Mon Sep 17 00:00:00 2001 From: Rich Haines Date: Fri, 10 Dec 2021 09:23:51 +0100 Subject: [PATCH 53/70] Update docs/basic-features/data-fetching/getStaticPaths.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Balázs Orbán --- docs/basic-features/data-fetching/getStaticPaths.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/basic-features/data-fetching/getStaticPaths.md b/docs/basic-features/data-fetching/getStaticPaths.md index 1248508f55168..a2c6124e51435 100644 --- a/docs/basic-features/data-fetching/getStaticPaths.md +++ b/docs/basic-features/data-fetching/getStaticPaths.md @@ -14,7 +14,7 @@ export async function getStaticPaths() { paths: [ { params: { ... } } ], - fallback: true // false or blocking + fallback: true // false or 'blocking' }; } ``` From 16a57266d130c9a7ff7ec972e05c801a136ce61f Mon Sep 17 00:00:00 2001 From: Rich Haines Date: Fri, 10 Dec 2021 09:23:58 +0100 Subject: [PATCH 54/70] Update docs/basic-features/data-fetching/getStaticPaths.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Balázs Orbán --- docs/basic-features/data-fetching/getStaticPaths.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/basic-features/data-fetching/getStaticPaths.md b/docs/basic-features/data-fetching/getStaticPaths.md index a2c6124e51435..add046e3a9c77 100644 --- a/docs/basic-features/data-fetching/getStaticPaths.md +++ b/docs/basic-features/data-fetching/getStaticPaths.md @@ -59,7 +59,7 @@ Note that you **cannot** use `getStaticPaths` with [`getServerSideProps`](/docs/ `getStaticPaths` can only be exported from a **page**. You **cannot** export it from non-page files. -You must use `export async function getStaticPaths() {}` — it will **not** work if you add `getStaticPaths` as a property of the page component. +You must use export `getStaticPaths` as a standalone function — it will **not** work if you add `getStaticPaths` as a property of the page component. ### Runs on every request in development From edd14e79e2bb7f00e455452b73dc4c125e344467 Mon Sep 17 00:00:00 2001 From: Rich Haines Date: Fri, 10 Dec 2021 09:24:04 +0100 Subject: [PATCH 55/70] Update docs/basic-features/data-fetching/getStaticProps.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Balázs Orbán --- docs/basic-features/data-fetching/getStaticProps.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/basic-features/data-fetching/getStaticProps.md b/docs/basic-features/data-fetching/getStaticProps.md index b54449db54af9..3eb55f947ae05 100644 --- a/docs/basic-features/data-fetching/getStaticProps.md +++ b/docs/basic-features/data-fetching/getStaticProps.md @@ -134,7 +134,7 @@ When using Incremental Static Generation `getStaticProps` will be executed out o 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 `getStaticProps` as a standalone function — it will **not** work if you add `getStaticProps` as a property of the page component. ### Runs on every request in development From 988fe890ea366d5fc32375eb3e7925a7df13fe8d Mon Sep 17 00:00:00 2001 From: Rich Haines Date: Fri, 10 Dec 2021 09:24:10 +0100 Subject: [PATCH 56/70] Update docs/basic-features/data-fetching/incremental-static-regeneration.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Balázs Orbán --- .../data-fetching/incremental-static-regeneration.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/basic-features/data-fetching/incremental-static-regeneration.md b/docs/basic-features/data-fetching/incremental-static-regeneration.md index e82c8053f779a..b6233742136bc 100644 --- a/docs/basic-features/data-fetching/incremental-static-regeneration.md +++ b/docs/basic-features/data-fetching/incremental-static-regeneration.md @@ -81,7 +81,7 @@ When a request is made to a page that was pre-rendered at build time, it will in - Any requests to the page after the initial request and before 10 seconds are also cached and instantaneous. - After the 10-second window, the next request will still show the cached (stale) page - Next.js triggers a regeneration of the page in the background. -- Once the page has been successfully generated, Next.js will invalidate the cache and show the updated product page. If the background regeneration fails, the old page remains unaltered. +- Once the page has been successfully generated, Next.js will invalidate the cache and show the updated page. If the background regeneration fails, the old page remains unaltered. When a request is made to a path that hasn’t been generated, Next.js will server-render the page on the first request. Future requests will serve the static file from the cache. From 394ae35991c28f5d013c1e4907b261a356b030d0 Mon Sep 17 00:00:00 2001 From: Rich Haines Date: Fri, 10 Dec 2021 09:24:20 +0100 Subject: [PATCH 57/70] Update docs/basic-features/data-fetching/incremental-static-regeneration.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Balázs Orbán --- .../data-fetching/incremental-static-regeneration.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/basic-features/data-fetching/incremental-static-regeneration.md b/docs/basic-features/data-fetching/incremental-static-regeneration.md index b6233742136bc..f413c514eb201 100644 --- a/docs/basic-features/data-fetching/incremental-static-regeneration.md +++ b/docs/basic-features/data-fetching/incremental-static-regeneration.md @@ -85,4 +85,4 @@ When a request is made to a page that was pre-rendered at build time, it will in When a request is made to a path that hasn’t been generated, Next.js will server-render the page on the first request. Future requests will serve the static file from the cache. -[Incremental Static Regeneration](https://vercel.com/docs/next.js/incremental-static-regeneration) covers how to persist the cache globally and handle rollbacks. +[Incremental Static Regeneration](https://vercel.com/docs/concepts/next.js/incremental-static-regeneration) covers how to persist the cache globally and handle rollbacks. From 77f70b91630835444762491ea105cd019f11c508 Mon Sep 17 00:00:00 2001 From: molebox Date: Tue, 30 Nov 2021 17:27:02 +0100 Subject: [PATCH 58/70] Changed heading --- docs/basic-features/data-fetching/getStaticPaths.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/basic-features/data-fetching/getStaticPaths.md b/docs/basic-features/data-fetching/getStaticPaths.md index add046e3a9c77..278fc94e60e6c 100644 --- a/docs/basic-features/data-fetching/getStaticPaths.md +++ b/docs/basic-features/data-fetching/getStaticPaths.md @@ -51,7 +51,7 @@ When you use `getStaticProps` on a page with dynamic route parameters, you **mus Note that you **cannot** use `getStaticPaths` with [`getServerSideProps`](/docs/basic-features/data-fetching/getServerSideProps.md). -### Only runs at build time on server-side +### When does `getStaticPaths` run? `getStaticPaths` only runs at build time on server-side. If you're using [Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration.md), `getStaticPaths` can also be ran on-demand _in the background_, but still only on the server-side.. From b493d11070a312a2d5169a61666172e2512a6c1b Mon Sep 17 00:00:00 2001 From: molebox Date: Fri, 10 Dec 2021 09:29:52 +0100 Subject: [PATCH 59/70] Conflicts in getServerSideProps --- .../data-fetching/getServerSideProps.md | 37 ++++++++++ .../data-fetching/getStaticPaths.md | 12 ++++ .../data-fetching/getStaticProps.md | 40 +++++++++++ .../data-fetching/getServerSideProps.md | 67 +++++-------------- .../data-fetching/getStaticPaths.md | 30 ++------- .../data-fetching/getStaticProps.md | 60 ++--------------- 6 files changed, 116 insertions(+), 130 deletions(-) diff --git a/docs/api-reference/data-fetching/getServerSideProps.md b/docs/api-reference/data-fetching/getServerSideProps.md index 86e9eb01b2309..705efe8775a6b 100644 --- a/docs/api-reference/data-fetching/getServerSideProps.md +++ b/docs/api-reference/data-fetching/getServerSideProps.md @@ -102,6 +102,43 @@ export async function getServerSideProps(context) { } ``` +### `getServerSideProps` with TypeScript + +For TypeScript, you can use the `GetServerSideProps` type from `next`: + +```ts +import { GetServerSideProps } from 'next' + +export const getServerSideProps: GetServerSideProps = async (context) => { + // ... +} +``` + +If you want to get inferred typings for your props, you can use `InferGetServerSidePropsType`: + +```tsx +import { InferGetServerSidePropsType } from 'next' + +type Data = { ... } + +export const getServerSideProps = async () => { + const res = await fetch('https://.../data') + const data: Data = await res.json() + + return { + props: { + data, + }, + } +} + +function Page({ data }: InferGetServerSidePropsType) { + // will resolve posts to type Data +} + +export default Page +``` + ## Related For more information on what to do next, we recommend the following sections: diff --git a/docs/api-reference/data-fetching/getStaticPaths.md b/docs/api-reference/data-fetching/getStaticPaths.md index 949a56300710f..80bd2803028b1 100644 --- a/docs/api-reference/data-fetching/getStaticPaths.md +++ b/docs/api-reference/data-fetching/getStaticPaths.md @@ -198,3 +198,15 @@ export async function getStaticProps({ params }) { export default Post ``` + +## `getStaticProps` with TypeScript + +For TypeScript, you can use the `GetStaticPaths` type from `next`: + +```ts +import { GetStaticPaths } from 'next' + +export const getStaticPaths: GetStaticPaths = async () => { + // ... +} +``` diff --git a/docs/api-reference/data-fetching/getStaticProps.md b/docs/api-reference/data-fetching/getStaticProps.md index 33d1158e3a7bc..d779c9af65f44 100644 --- a/docs/api-reference/data-fetching/getStaticProps.md +++ b/docs/api-reference/data-fetching/getStaticProps.md @@ -198,6 +198,46 @@ export async function getStaticProps() { export default Blog ``` +## `getStaticProps` with TypeScript + +You can use the `GetStaticProps` type from `next` to type the function: + +```ts +import { GetStaticProps } from 'next' + +export const getStaticProps: GetStaticProps = async (context) => { + // ... +} +``` + +If you want to get inferred typings for your props, you can use `InferGetStaticPropsType`: + +```tsx +import { InferGetStaticPropsType } from 'next' + +type Post = { + author: string + content: string +} + +export const getStaticProps = async () => { + const res = await fetch('https://.../posts') + const posts: Post[] = await res.json() + + return { + props: { + posts, + }, + } +} + +function Blog({ posts }: InferGetStaticPropsType) { + // will resolve posts to type Post[] +} + +export default Blog +``` + ## Related For more information on what to do next, we recommend the following sections: diff --git a/docs/basic-features/data-fetching/getServerSideProps.md b/docs/basic-features/data-fetching/getServerSideProps.md index 92e7b1e40cc20..ccc03fdc8d0a8 100644 --- a/docs/basic-features/data-fetching/getServerSideProps.md +++ b/docs/basic-features/data-fetching/getServerSideProps.md @@ -14,71 +14,34 @@ export async function getServerSideProps(context) { } ``` -The [`getServerSideProps` API reference](/docs/api-reference/data-fetching/getServerSideProps.md) covers all parameters and props that can be used with `getServerSideProps`. - -## When should I use `getServerSideProps`? - -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)](/learn/seo/web-performance) will be higher than [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) because the server must compute the result on every request, and the result can only be cached by a CDN using `cache-control` headers (which could require extra configuration). - -If you do not need to pre-render the data, then you should consider fetching data on the [client side](#fetching-data-on-the-client-side). - -### `getServerSideProps` or API Routes? - -It can be tempting to reach for an [API Route](/docs/api-routes/introduction.md) when you want to fetch data from the server, then call that API route from `getServerSideProps`. This is an unnecessary and inefficient approach, as it will cause an extra request to be made due to both `getServerSideProps` and API Routes running on the server. - -Instead, directly import the logic used inside your API Route into `getServerSideProps`. This could mean calling a CMS, database, or other API directly from inside `getServerSideProps`. - -### TypeScript: Use `GetServerSideProps` - -For TypeScript, you can use the `GetServerSideProps` type from `next`: - -```ts -import { GetServerSideProps } from 'next' - -export const getServerSideProps: GetServerSideProps = async (context) => { - // ... -} -``` - -If you want to get inferred typings for your props, you can use `InferGetServerSidePropsType`: +## When does `getServerSideProps` run -```tsx -import { InferGetServerSidePropsType } from 'next' +`getServerSideProps` only runs on server-side and never runs on the browser. If a page uses `getServerSideProps`, then: -type Data = { ... } +- When you request this page directly, `getServerSideProps` runs at 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`](/docs/api-reference/next/link.md)) or ([`next/router`](/docs/api-reference/next/router.md)), Next.js sends an API request to the server, which runs `getServerSideProps`. -export const getServerSideProps = async () => { - const res = await fetch('https://.../data') - const data: Data = await res.json() +It then returns `JSON` that contains the result of running `getServerSideProps`, that `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. - return { - props: { - data, - }, - } -} +You can use the [next-code-elimination tool](https://next-code-elimination.vercel.app/) to verify what Next.js eliminates from the client-side bundle. -function Page({ data }: InferGetServerSidePropsType) { - // will resolve posts to type Data -} +`getServerSideProps` can only be exported from a **page**. You can’t export it from non-page files. -export default Page -``` +You must export `getServerSideProps` as a standalone function — it will **not** work if you add `getServerSideProps` as a property of the page component. -### Technical details +The [`getServerSideProps` API reference](/docs/api-reference/data-fetching/getServerSideProps.md) covers all parameters and props that can be used with `getServerSideProps`. -#### Only runs on server-side +## When should I use `getServerSideProps`? -`getServerSideProps` only runs on server-side and never runs on the browser. If a page uses `getServerSideProps`, then: +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)](/learn/seo/web-performance) will be slower than [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) because the server must compute the result on every request, and the result can only be cached by a CDN using `cache-control` headers (which could require extra configuration). -- 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`](/docs/api-reference/next/link.md) or [`next/router`](/docs/api-reference/next/router.md), Next.js sends an API request to the server, which runs `getServerSideProps`. It’ll return 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 +If you do not need to pre-render the data, then you should consider fetching data on the [client side](#fetching-data-on-the-client-side). -You can use the [next-code-elimination tool](https://next-code-elimination.vercel.app/) to verify what Next.js eliminates from the client-side bundle. +### `getServerSideProps` or API Routes? -`getServerSideProps` can only be exported from a **page**. You can’t export it from non-page files. +It can be tempting to reach for an [API Route](/docs/api-routes/introduction.md) when you want to fetch data from the server, then call that API route from `getServerSideProps`. This is an unnecessary and inefficient approach, as it will cause an extra request to be made due to both `getServerSideProps` and API Routes running on the server. -Also, you must export `getServerSideProps` as a standalone function. — it will **not** work if you add `getServerSideProps` as a property of the page component. +Instead, directly import the logic used inside your API Route into `getServerSideProps`. This could mean calling a CMS, database, or other API directly from inside `getServerSideProps`. ## Fetching data on the client side diff --git a/docs/basic-features/data-fetching/getStaticPaths.md b/docs/basic-features/data-fetching/getStaticPaths.md index 278fc94e60e6c..7cee625d929a9 100644 --- a/docs/basic-features/data-fetching/getStaticPaths.md +++ b/docs/basic-features/data-fetching/getStaticPaths.md @@ -19,6 +19,8 @@ export async function getStaticPaths() { } ``` +Note that`getStaticProps` **must** be used with `getStaticPaths`, and that you **cannot** use it with [`getServerSideProps`](/docs/basic-features/data-fetching/getServerSideProps.md). + The [`getStaticPaths` API reference](/docs/api-reference/data-fetching/getStaticPaths.md) covers all parameters and props that can be used with `getStaticPaths`. ## When should I use `getStaticPaths`? @@ -31,36 +33,16 @@ You should use `getStaticPaths` if you’re statically pre-rendering pages that - 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 -## TypeScript: Use `GetStaticPaths` - -For TypeScript, you can use the `GetStaticPaths` type from `next`: - -```ts -import { GetStaticPaths } from 'next' - -export const getStaticPaths: GetStaticPaths = async () => { - // ... -} -``` - -## Technical details - -### Use together with [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) - -When you use `getStaticProps` on a page with dynamic route parameters, you **must** use `getStaticPaths`. - -Note that you **cannot** use `getStaticPaths` with [`getServerSideProps`](/docs/basic-features/data-fetching/getServerSideProps.md). - -### When does `getStaticPaths` run? +## When does `getStaticPaths` run -`getStaticPaths` only runs at build time on server-side. If you're using [Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration.md), `getStaticPaths` can also be ran on-demand _in the background_, but still only on the server-side.. +`getStaticPaths` only runs at build time on server-side. If you're using [Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration.md), `getStaticPaths` can also be run on-demand _in the background_, but still only on the server-side. -### Only allowed in a page +## Where can I use `getStaticPaths` `getStaticPaths` can only be exported from a **page**. You **cannot** export it from non-page files. You must use export `getStaticPaths` as a standalone function — it will **not** work if you add `getStaticPaths` as a property of the page component. -### Runs on every request in development +## Runs on every request in development In development (`next dev`), `getStaticPaths` will be called on every request. diff --git a/docs/basic-features/data-fetching/getStaticProps.md b/docs/basic-features/data-fetching/getStaticProps.md index 3eb55f947ae05..b4c2009cafcc8 100644 --- a/docs/basic-features/data-fetching/getStaticProps.md +++ b/docs/basic-features/data-fetching/getStaticProps.md @@ -23,45 +23,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 -## TypeScript: Use `GetStaticProps` - -You can use the `GetStaticProps` type from `next` to type the function: - -```ts -import { GetStaticProps } from 'next' - -export const getStaticProps: GetStaticProps = async (context) => { - // ... -} -``` - -If you want to get inferred typings for your props, you can use `InferGetStaticPropsType`: - -```tsx -import { InferGetStaticPropsType } from 'next' - -type Post = { - author: string - content: string -} - -export const getStaticProps = async () => { - const res = await fetch('https://.../posts') - const posts: Post[] = await res.json() - - return { - props: { - posts, - }, - } -} - -function Blog({ posts }: InferGetStaticPropsType) { - // will resolve posts to type Post[] -} - -export default Blog -``` +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`. When combined with [Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration.md) however, it will run in the background while the stale page is being revalidated, and the fresh page served to the browser. ## Using `getStaticProps` to fetch data from a CMS @@ -102,25 +64,15 @@ export default Blog The [`getStaticProps` API reference](/docs/api-reference/data-fetching/getStaticProps.md) covers all parameters and props that can be used with `getStaticProps`. -## 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`. When combined with [Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration.md) however, it will run in the background while the stale page is being revalidated, and the fresh page served to the browser. - -### 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. - -### Write server-side code directly +## 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. +As `getStaticProps` runs only on the server-side, it will never 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`. +This means that instead of fetching an **API route** from `getStaticProps`, you can write the server-side code directly in `getStaticProps`. You can use the [next-code-elimination tool](https://next-code-elimination.vercel.app/) to verify what Next.js eliminates from the client-side bundle. -### Statically Generates both HTML and JSON +## 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`. @@ -128,7 +80,7 @@ This JSON file will be used in client-side routing through [`next/link`](/docs/a When using Incremental Static Generation `getStaticProps` will be executed out of band to generate the JSON needed for client-side navigation. You may see this in the form of multiple requests being made for the same page, however, this is intended and has no impact on end-user performance -### Only allowed in a page +### Where can I use `getStaticProps` `getStaticProps` can only be exported from a **page**. You **cannot** export it from non-page files. From ac8da9d76dc5bd5786187a01f1450b69277ed586 Mon Sep 17 00:00:00 2001 From: molebox Date: Fri, 10 Dec 2021 12:21:02 +0100 Subject: [PATCH 60/70] Feedback changes --- .../data-fetching/getServerSideProps.md | 4 ++-- docs/api-reference/data-fetching/getStaticPaths.md | 4 ++-- docs/api-reference/data-fetching/getStaticProps.md | 13 +++---------- docs/basic-features/data-fetching/client-side.md | 6 ++++-- .../data-fetching/getServerSideProps.md | 4 ++-- .../basic-features/data-fetching/getStaticProps.md | 14 +++++++++----- 6 files changed, 22 insertions(+), 23 deletions(-) diff --git a/docs/api-reference/data-fetching/getServerSideProps.md b/docs/api-reference/data-fetching/getServerSideProps.md index 705efe8775a6b..582b04db9e7b1 100644 --- a/docs/api-reference/data-fetching/getServerSideProps.md +++ b/docs/api-reference/data-fetching/getServerSideProps.md @@ -14,7 +14,7 @@ description: API reference for `getServerSideProps`. Learn how to fetch data on -When exporting an `async` function called `getServerSideProps` (server-side rendering) from a page, Next.js will pre-render this page on each request using the data returned by `getServerSideProps`. This is useful if you want to fetch data that changes often, and have the page update to show the most current data. +When exporting a function called `getServerSideProps` (Server-Side Rendering) from a page, Next.js will pre-render this page on each request using the data returned by `getServerSideProps`. This is useful if you want to fetch data that changes often, and have the page update to show the most current data. ```js export async function getServerSideProps(context) { @@ -47,7 +47,7 @@ The `getServerSideProps` function should return an object with the following **o ### `props` -The `props` object is a key-value pair, where each value is forwarded to the page component. It should be a [serializable object](https://en.wikipedia.org/wiki/Serialization). +The `props` object is a key-value pair, where each value is received by the page component. It should be a [serializable object](https://developer.mozilla.org/en-US/docs/Glossary/Serialization) so that any props passed, could be serialized with [`JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). ```jsx export async function getServerSideProps(context) { diff --git a/docs/api-reference/data-fetching/getStaticPaths.md b/docs/api-reference/data-fetching/getStaticPaths.md index 80bd2803028b1..7d537881667a2 100644 --- a/docs/api-reference/data-fetching/getStaticPaths.md +++ b/docs/api-reference/data-fetching/getStaticPaths.md @@ -14,7 +14,7 @@ description: API reference for `getStaticPaths`. Learn how to fetch data and gen -When exporting an `async` function called `getStaticPaths` from a page that uses [Dynamic Routes](/docs/routing/dynamic-routes.md), Next.js will statically pre-render all the paths specified by `getStaticPaths`. +When exporting a function called `getStaticPaths` from a page that uses [Dynamic Routes](/docs/routing/dynamic-routes.md), Next.js will statically pre-render all the paths specified by `getStaticPaths`. ```jsx export async function getStaticPaths() { @@ -55,7 +55,7 @@ The value for each `params` object must match the parameters used in the page na ### `fallback: false` -If `fallback` is `false`, then any paths not returned by `getStaticPaths` will result in a **404 page**. This is useful if you have a small number of paths to pre-render and want to statically generate them all during `next build`. +If `fallback` is `false`, then any paths not returned by `getStaticPaths` will result in a **404 page**. When `next build` is run, Next.js will check if `getStaticPaths` returned `fallback: false`, it will then build **only** the paths returned by `getStaticPaths`. This option is useful if you have a small number of paths to create, or new page data is not added often. If you find that you need to add more paths, and you have `fallback: false`, you will need to run `next build` again so that the new paths can be generated. diff --git a/docs/api-reference/data-fetching/getStaticProps.md b/docs/api-reference/data-fetching/getStaticProps.md index d779c9af65f44..df8dbfe854718 100644 --- a/docs/api-reference/data-fetching/getStaticProps.md +++ b/docs/api-reference/data-fetching/getStaticProps.md @@ -15,7 +15,7 @@ description: API reference for `getStaticProps`. Learn how to use `getStaticProp -Exporting an `async` function called `getStaticProps` will pre-render a page at build time using the props returned from the function: +Exporting a function called `getStaticProps` will pre-render a page at build time using the props returned from the function: ```jsx export async function getStaticProps(context) { @@ -25,14 +25,7 @@ export async function getStaticProps(context) { } ``` -You can import modules in top-level scope for use in `getStaticProps`. -Imports used will **not be bundled for the client-side**. This means you can write **server-side code directly in `getStaticProps`**, including fetching data from your database. - -If you are calling an external `API`, or fetching data from a database or Content Management System (CMS) in an `API` route, you can move that logic to `getStaticProps`, as both `API` routes and `getStaticProps` run on the server. - -Calling an `API` route from within `getStaticProps` can result in an additional call, reducing performance. - -Alternatively, if you are **not** using `API` routes to fetch data, then the [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) `API` _can_ be used directly in `getStaticProps` to fetch data. +You can import modules in top-level scope for use in `getStaticProps`. Imports used will **not be bundled for the client-side**. This means you can write **server-side code directly in `getStaticProps`**, including fetching data from your database. ## Context parameter @@ -51,7 +44,7 @@ The `getStaticProps` function should return an object with the following **optio ### `props` -The `props` object is a key-value pair, where each value is received by the page component. It should be a [serializable object](https://en.wikipedia.org/wiki/Serialization) +The `props` object is a key-value pair, where each value is received by the page component. It should be a [serializable object](https://developer.mozilla.org/en-US/docs/Glossary/Serialization) so that any props passed, could be serialized with [`JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). ```jsx export async function getStaticProps(context) { diff --git a/docs/basic-features/data-fetching/client-side.md b/docs/basic-features/data-fetching/client-side.md index 16a68db8856fa..eacf7f14d0c5f 100644 --- a/docs/basic-features/data-fetching/client-side.md +++ b/docs/basic-features/data-fetching/client-side.md @@ -1,5 +1,5 @@ --- -description: 'Learn how to use SWR, a data fetching React hook library that handles caching, revalidation, focus tracking, refetching on interval and more.' +description: 'Learn about client-side data fetching, and how to use SWR, a data fetching React hook library that handles caching, revalidation, focus tracking, refetching on interval and more.' --- # Client-side data fetching @@ -52,8 +52,10 @@ For more information on using SWR, check out the [SWR docs](https://swr.vercel.a ```jsx import useSWR from 'swr' +const fetcher = (...args) => fetch(...args).then((res) => res.json()) + function Profile() { - const { data, error } = useSWR('/api/profile-data', fetch) + const { data, error } = useSWR('/api/profile-data', fetcher) if (error) return
Failed to load
if (!data) return
Loading...
diff --git a/docs/basic-features/data-fetching/getServerSideProps.md b/docs/basic-features/data-fetching/getServerSideProps.md index ccc03fdc8d0a8..c7d6cbd283faa 100644 --- a/docs/basic-features/data-fetching/getServerSideProps.md +++ b/docs/basic-features/data-fetching/getServerSideProps.md @@ -37,11 +37,11 @@ You should use `getServerSideProps` only if you need to pre-render a page whose If you do not need to pre-render the data, then you should consider fetching data on the [client side](#fetching-data-on-the-client-side). -### `getServerSideProps` or API Routes? +### `getServerSideProps` or API Routes It can be tempting to reach for an [API Route](/docs/api-routes/introduction.md) when you want to fetch data from the server, then call that API route from `getServerSideProps`. This is an unnecessary and inefficient approach, as it will cause an extra request to be made due to both `getServerSideProps` and API Routes running on the server. -Instead, directly import the logic used inside your API Route into `getServerSideProps`. This could mean calling a CMS, database, or other API directly from inside `getServerSideProps`. +Take the following example. An API route is used to fetch some data from a CMS. That API route is then called directly from `getServerSideProps`. This produces an additional call, reducing performance. Instead, directly import the logic used inside your API Route into `getServerSideProps`. This could mean calling a CMS, database, or other API directly from inside `getServerSideProps`. ## Fetching data on the client side diff --git a/docs/basic-features/data-fetching/getStaticProps.md b/docs/basic-features/data-fetching/getStaticProps.md index b4c2009cafcc8..d0dfb8e811e5c 100644 --- a/docs/basic-features/data-fetching/getStaticProps.md +++ b/docs/basic-features/data-fetching/getStaticProps.md @@ -4,7 +4,7 @@ description: Fetch data and generate static pages with `getStaticProps`. Learn m # `getStaticProps` -If you export an `async` function called `getStaticProps` (static generation) from a page, Next.js will pre-render this page at build time using the props returned by `getStaticProps`. +If you export a function called `getStaticProps` (Static Site Generation) from a page, Next.js will pre-render this page at build time using the props returned by `getStaticProps`. ```jsx export async function getStaticProps(context) { @@ -43,7 +43,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. export async function getStaticProps() { // Call an external API endpoint to get posts. // You can use any data fetching library @@ -66,11 +66,15 @@ The [`getStaticProps` API reference](/docs/api-reference/data-fetching/getStatic ## Write server-side code directly -As `getStaticProps` runs only on the server-side, it will never 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. +As `getStaticProps` runs only on the server-side, it will never run on the client-side. It won’t even be included in the JS bundle for the browser, so you can write direct database queries without them being sent to browsers. -This means that instead of fetching an **API route** from `getStaticProps`, you can write the server-side code directly in `getStaticProps`. +This means that instead of fetching an **API route** from `getStaticProps` (that itself fetches data from an external source), you can write the server-side code directly in `getStaticProps`. -You can use the [next-code-elimination tool](https://next-code-elimination.vercel.app/) to verify what Next.js eliminates from the client-side bundle. +Take the following example. An API route is used to fetch some data from a CMS. That API route is then called directly from `getStaticProps`. This produces an additional call, reducing performance. Instead, the logic for fetching the data from the CMS can be moved to `getStaticProps`. + +Alternatively, if you are **not** using API routes to fetch data, then the [`fetch()`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) API _can_ be used directly in `getStaticProps` to fetch data. + +To verify what Next.js eliminates from the client-side bundle, you can use the [next-code-elimination tool](https://next-code-elimination.vercel.app/). ## Statically Generates both HTML and JSON From 7c75549db4c47d5ca46d6edcea050f53de4cb222 Mon Sep 17 00:00:00 2001 From: molebox Date: Fri, 10 Dec 2021 12:47:22 +0100 Subject: [PATCH 61/70] Fixed internal links to new pages --- .../automatic-static-optimization.md | 4 ++-- docs/advanced-features/custom-app.md | 6 +++--- docs/advanced-features/custom-document.md | 2 +- docs/advanced-features/custom-error-page.md | 4 ++-- docs/advanced-features/i18n-routing.md | 4 ++-- docs/advanced-features/preview-mode.md | 4 ++-- docs/advanced-features/static-html-export.md | 16 ++++++++-------- .../data-fetching/getInitialProps.md | 2 +- .../cdn-support-with-asset-prefix.md | 2 +- docs/api-reference/next.config.js/redirects.md | 2 +- docs/api-reference/next.config.js/rewrites.md | 2 +- docs/api-reference/next/link.md | 4 ++-- docs/api-reference/next/router.md | 6 +++--- docs/authentication.md | 8 ++++---- docs/basic-features/environment-variables.md | 4 ++-- docs/basic-features/pages.md | 12 ++++++------ docs/faq.md | 2 +- docs/getting-started.md | 2 +- docs/going-to-production.md | 2 +- docs/migrating/from-create-react-app.md | 6 +++--- docs/migrating/from-gatsby.md | 8 ++++---- docs/routing/introduction.md | 2 +- docs/routing/shallow-routing.md | 2 +- examples/blog/pages/posts/pages.md | 10 +++++----- 24 files changed, 58 insertions(+), 58 deletions(-) diff --git a/docs/advanced-features/automatic-static-optimization.md b/docs/advanced-features/automatic-static-optimization.md index 17a3ea787c3b9..a7c910bf9ed61 100644 --- a/docs/advanced-features/automatic-static-optimization.md +++ b/docs/advanced-features/automatic-static-optimization.md @@ -20,7 +20,7 @@ If the above is not the case, Next.js will **statically optimize** your page aut During prerendering, the router's `query` object will be empty since we do not have `query` information to provide during this phase. After hydration, Next.js will trigger an update to your application to provide the route parameters in the `query` object. -> **Note:** Parameters added with [dynamic routes](/docs/routing/dynamic-routes.md) to a page that's using [`getStaticProps`](/docs/basic-features/data-fetching.md#getstaticprops-static-generation) will always be available inside the `query` object. +> **Note:** Parameters added with [dynamic routes](/docs/routing/dynamic-routes.md) to a page that's using [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) will always be available inside the `query` object. `next build` will emit `.html` files for statically optimized pages. For example, the result for the page `pages/about.js` would be: @@ -36,5 +36,5 @@ And if you add `getServerSideProps` to the page, it will then be JavaScript, lik ## Caveats -- If you have a [custom `App`](/docs/advanced-features/custom-app.md) with `getInitialProps` then this optimization will be turned off in pages without [Static Generation](/docs/basic-features/data-fetching.md#getstaticprops-static-generation). +- If you have a [custom `App`](/docs/advanced-features/custom-app.md) with `getInitialProps` then this optimization will be turned off in pages without [Static Generation](/docs/basic-features/data-fetching/getStaticProps.md). - If you have a [custom `Document`](/docs/advanced-features/custom-document.md) with `getInitialProps` be sure you check if `ctx.req` is defined before assuming the page is server-side rendered. `ctx.req` will be `undefined` for pages that are prerendered. diff --git a/docs/advanced-features/custom-app.md b/docs/advanced-features/custom-app.md index 7add6c1d9b0c5..953eee3723101 100644 --- a/docs/advanced-features/custom-app.md +++ b/docs/advanced-features/custom-app.md @@ -38,14 +38,14 @@ export default MyApp The `Component` prop is the active `page`, so whenever you navigate between routes, `Component` will change to the new `page`. Therefore, any props you send to `Component` will be received by the `page`. -`pageProps` is an object with the initial props that were preloaded for your page by one of our [data fetching methods](/docs/basic-features/data-fetching.md), otherwise it's an empty object. +`pageProps` is an object with the initial props that were preloaded for your page by one of our [data fetching methods](/docs/basic-features/data-fetching/index.md), otherwise it's an empty object. ### Caveats - If your app is running and you added a custom `App`, you'll need to restart the development server. Only required if `pages/_app.js` didn't exist before. -- Adding a custom [`getInitialProps`](/docs/api-reference/data-fetching/getInitialProps.md) in your `App` will disable [Automatic Static Optimization](/docs/advanced-features/automatic-static-optimization.md) in pages without [Static Generation](/docs/basic-features/data-fetching.md#getstaticprops-static-generation). +- Adding a custom [`getInitialProps`](/docs/api-reference/data-fetching/getInitialProps.md) in your `App` will disable [Automatic Static Optimization](/docs/advanced-features/automatic-static-optimization.md) in pages without [Static Generation](/docs/basic-features/data-fetching/getStaticProps.md). - When you add `getInitialProps` in your custom app, you must `import App from "next/app"`, call `App.getInitialProps(appContext)` inside `getInitialProps` and merge the returned object into the return value. -- `App` currently does not support Next.js [Data Fetching methods](/docs/basic-features/data-fetching.md) like [`getStaticProps`](/docs/basic-features/data-fetching.md#getstaticprops-static-generation) or [`getServerSideProps`](/docs/basic-features/data-fetching.md#getserversideprops-server-side-rendering). +- `App` currently does not support Next.js [Data Fetching methods](/docs/basic-features/data-fetching/index.md) like [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) or [`getServerSideProps`](/docs/basic-features/data-fetching/getServerSideProps.md). ### TypeScript diff --git a/docs/advanced-features/custom-document.md b/docs/advanced-features/custom-document.md index 2c75cca86b376..e99d32e89abab 100644 --- a/docs/advanced-features/custom-document.md +++ b/docs/advanced-features/custom-document.md @@ -54,7 +54,7 @@ The `ctx` object is equivalent to the one received in [`getInitialProps`](/docs/ - `Document` is only rendered in the server, event handlers like `onClick` won't work. - React components outside of `
` will not be initialized by the browser. Do _not_ add application logic here or custom CSS (like `styled-jsx`). If you need shared components in all your pages (like a menu or a toolbar), take a look at the [`App`](/docs/advanced-features/custom-app.md) component instead. - `Document`'s `getInitialProps` function is not called during client-side transitions, nor when a page is [statically optimized](/docs/advanced-features/automatic-static-optimization.md). -- `Document` currently does not support Next.js [Data Fetching methods](/docs/basic-features/data-fetching.md) like [`getStaticProps`](/docs/basic-features/data-fetching.md#getstaticprops-static-generation) or [`getServerSideProps`](/docs/basic-features/data-fetching.md#getserversideprops-server-side-rendering). +- `Document` currently does not support Next.js [Data Fetching methods](/docs/basic-features/data-fetching/index.md) like [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) or [`getServerSideProps`](/docs/basic-features/data-fetching/getServerSideProps.md). ## Customizing `renderPage` diff --git a/docs/advanced-features/custom-error-page.md b/docs/advanced-features/custom-error-page.md index 6dfa999892be1..7f306e9d262e5 100644 --- a/docs/advanced-features/custom-error-page.md +++ b/docs/advanced-features/custom-error-page.md @@ -21,7 +21,7 @@ export default function Custom404() { } ``` -> **Note**: You can use [`getStaticProps`](/docs/basic-features/data-fetching.md#getstaticprops-static-generation) inside this page if you need to fetch data at build time. +> **Note**: You can use [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) inside this page if you need to fetch data at build time. ## 500 Page @@ -38,7 +38,7 @@ export default function Custom500() { } ``` -> **Note**: You can use [`getStaticProps`](/docs/basic-features/data-fetching.md#getstaticprops-static-generation) inside this page if you need to fetch data at build time. +> **Note**: You can use [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) inside this page if you need to fetch data at build time. ### More Advanced Error Page Customizing diff --git a/docs/advanced-features/i18n-routing.md b/docs/advanced-features/i18n-routing.md index 8272276b47418..2f9e8d77b348c 100644 --- a/docs/advanced-features/i18n-routing.md +++ b/docs/advanced-features/i18n-routing.md @@ -207,7 +207,7 @@ You can access the locale information via the Next.js router. For example, using - `locales` contains all configured locales. - `defaultLocale` contains the configured default locale. -When [pre-rendering](/docs/basic-features/pages.md#static-generation-recommended) pages with `getStaticProps` or `getServerSideProps`, the locale information is provided in [the context](/docs/basic-features/data-fetching.md#getstaticprops-static-generation) provided to the function. +When [pre-rendering](/docs/basic-features/pages.md#static-generation-recommended) pages with `getStaticProps` or `getServerSideProps`, the locale information is provided in [the context](/docs/basic-features/data-fetching/getStaticProps.md) provided to the function. When leveraging `getStaticPaths`, the configured locales are provided in the context parameter of the function under `locales` and the configured defaultLocale under `defaultLocale`. @@ -293,7 +293,7 @@ Next.js doesn't know about variants of a page so it's up to you to add the `href ### Dynamic Routes and `getStaticProps` Pages -For pages using `getStaticProps` with [Dynamic Routes](/docs/routing/dynamic-routes.md), all locale variants of the page desired to be prerendered need to be returned from [`getStaticPaths`](/docs/basic-features/data-fetching.md#getstaticpaths-static-generation). Along with the `params` object returned for `paths`, you can also return a `locale` field specifying which locale you want to render. For example: +For pages using `getStaticProps` with [Dynamic Routes](/docs/routing/dynamic-routes.md), all locale variants of the page desired to be prerendered need to be returned from [`getStaticPaths`](/docs/basic-features/data-fetching/getStaticPaths.md). Along with the `params` object returned for `paths`, you can also return a `locale` field specifying which locale you want to render. For example: ```js // pages/blog/[slug].js diff --git a/docs/advanced-features/preview-mode.md b/docs/advanced-features/preview-mode.md index 511974bad4264..a5b7ac69c3e65 100644 --- a/docs/advanced-features/preview-mode.md +++ b/docs/advanced-features/preview-mode.md @@ -27,7 +27,7 @@ description: Next.js has the preview mode for statically generated pages. You ca -In the [Pages documentation](/docs/basic-features/pages.md) and the [Data Fetching documentation](/docs/basic-features/data-fetching.md), we talked about how to pre-render a page at build time (**Static Generation**) using `getStaticProps` and `getStaticPaths`. +In the [Pages documentation](/docs/basic-features/pages.md) and the [Data Fetching documentation](/docs/basic-features/data-fetching/index.md), we talked about how to pre-render a page at build time (**Static Generation**) using `getStaticProps` and `getStaticPaths`. Static Generation is useful when your pages fetch data from a headless CMS. However, it’s not ideal when you’re writing a draft on your headless CMS and want to **preview** the draft immediately on your page. You’d want Next.js to render these pages at **request time** instead of build time and fetch the draft content instead of the published content. You’d want Next.js to bypass Static Generation only for this specific case. @@ -230,7 +230,7 @@ This ensures that the bypass cookie can’t be guessed. The following pages might also be useful.
- + Data Fetching: Learn more about data fetching in Next.js. diff --git a/docs/advanced-features/static-html-export.md b/docs/advanced-features/static-html-export.md index e37bd2ababcf4..c49da4959aef7 100644 --- a/docs/advanced-features/static-html-export.md +++ b/docs/advanced-features/static-html-export.md @@ -13,7 +13,7 @@ description: Export your Next.js app to static HTML, and run it standalone witho `next export` allows you to export your Next.js application to static HTML, which can be run standalone without the need of a Node.js server. It is recommended to only use `next export` if you don't need any of the [unsupported features](#unsupported-features) requiring a server. -If you're looking to build a hybrid site where only _some_ pages are prerendered to static HTML, Next.js already does that automatically. Learn more about [Automatic Static Optimization](/docs/advanced-features/automatic-static-optimization.md) and [Incremental Static Regeneration](/docs/basic-features/data-fetching.md#incremental-static-regeneration). +If you're looking to build a hybrid site where only _some_ pages are prerendered to static HTML, Next.js already does that automatically. Learn more about [Automatic Static Optimization](/docs/advanced-features/automatic-static-optimization.md) and [Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration.md). ## `next export` @@ -27,7 +27,7 @@ Update your build script in `package.json` to use `next export`: Running `npm run build` will generate an `out` directory. -`next export` builds an HTML version of your app. During `next build`, [`getStaticProps`](/docs/basic-features/data-fetching.md#getstaticprops-static-generation) and [`getStaticPaths`](/docs/basic-features/data-fetching.md#getstaticpaths-static-generation) will generate an HTML file for each page in your `pages` directory (or more for [dynamic routes](/docs/routing/dynamic-routes.md). Then, `next export` will copy the already exported files into the correct directory. `getInitialProps` will generate the HTML files during `next export` instead of `next build`. +`next export` builds an HTML version of your app. During `next build`, [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) and [`getStaticPaths`](/docs/basic-features/data-fetching/getStaticPaths.md) will generate an HTML file for each page in your `pages` directory (or more for [dynamic routes](/docs/routing/dynamic-routes.md). Then, `next export` will copy the already exported files into the correct directory. `getInitialProps` will generate the HTML files during `next export` instead of `next build`. For more advanced scenarios, you can define a parameter called [`exportPathMap`](/docs/api-reference/next.config.js/exportPathMap.md) in your [`next.config.js`](/docs/api-reference/next.config.js/introduction.md) file to configure exactly which pages will be generated. @@ -40,9 +40,9 @@ The majority of core Next.js features needed to build a static site are supporte - Preloading JavaScript - [Dynamic Imports](/docs/advanced-features/dynamic-import.md) - Any styling options (e.g. CSS Modules, styled-jsx) -- [Client-side data fetching](/docs/basic-features/data-fetching.md#fetching-data-on-the-client-side) -- [`getStaticProps`](/docs/basic-features/data-fetching.md#getstaticprops-static-generation) -- [`getStaticPaths`](/docs/basic-features/data-fetching.md#getstaticpaths-static-generation) +- [Client-side data fetching](/docs/basic-features/data-fetching/client-side.md) +- [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) +- [`getStaticPaths`](/docs/basic-features/data-fetching/getStaticPaths.md) - [Image Optimization](/docs/basic-features/image-optimization.md) using a [custom loader](/docs/basic-features/image-optimization.md#loader) ## Unsupported Features @@ -56,9 +56,9 @@ Features that require a Node.js server, or dynamic logic that cannot be computed - [Redirects](/docs/api-reference/next.config.js/redirects.md) - [Headers](/docs/api-reference/next.config.js/headers.md) - [Middleware](/docs/middleware.md) -- [Incremental Static Regeneration](/docs/basic-features/data-fetching.md#incremental-static-regeneration) -- [`fallback: true`](/docs/basic-features/data-fetching.md#fallback-true) -- [`getServerSideProps`](/docs/basic-features/data-fetching.md#getserversideprops-server-side-rendering) +- [Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration.md) +- [`fallback: true`](/docs/api-reference/data-fetching/getStaticPaths.md#fallback-true) +- [`getServerSideProps`](/docs/basic-features/data-fetching/getServerSideProps.md) ### `getInitialProps` diff --git a/docs/api-reference/data-fetching/getInitialProps.md b/docs/api-reference/data-fetching/getInitialProps.md index a83593067d252..a209da0612502 100644 --- a/docs/api-reference/data-fetching/getInitialProps.md +++ b/docs/api-reference/data-fetching/getInitialProps.md @@ -4,7 +4,7 @@ description: Enable Server-Side Rendering in a page and do initial data populati # getInitialProps -**Recommended: [`getStaticProps`](/docs/basic-features/data-fetching.md#getstaticprops-static-generation) or [`getServerSideProps`](/docs/basic-features/data-fetching.md#getserversideprops-server-side-rendering)** instead of `getInitialProps`. These data fetching methods allow you to have a granular choice between static generation and server-side rendering. +**Recommended: [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) or [`getServerSideProps`](/docs/basic-features/data-fetching/getServerSideProps.md)** instead of `getInitialProps`. These data fetching methods allow you to have a granular choice between static generation and server-side rendering. `getInitialProps` enables [server-side rendering](/docs/basic-features/pages.md#server-side-rendering) in a page and allows you to do **initial data population**, it means sending the [page](/docs/basic-features/pages.md) with the data already populated from the server. This is especially useful for [SEO](https://en.wikipedia.org/wiki/Search_engine_optimization). diff --git a/docs/api-reference/next.config.js/cdn-support-with-asset-prefix.md b/docs/api-reference/next.config.js/cdn-support-with-asset-prefix.md index 20056521d6e78..0383f6ee6e6d2 100644 --- a/docs/api-reference/next.config.js/cdn-support-with-asset-prefix.md +++ b/docs/api-reference/next.config.js/cdn-support-with-asset-prefix.md @@ -42,7 +42,7 @@ While `assetPrefix` covers requests to `_next/static`, it does not influence the - Files in the [public](/docs/basic-features/static-file-serving.md) folder; if you want to serve those assets over a CDN, you'll have to introduce the prefix yourself - `/_next/data/` requests for `getServerSideProps` pages. These requests will always be made against the main domain since they're not static. -- `/_next/data/` requests for `getStaticProps` pages. These requests will always be made against the main domain to support [Incremental Static Generation](/docs/basic-features/data-fetching.md#incremental-static-regeneration), even if you're not using it (for consistency). +- `/_next/data/` requests for `getStaticProps` pages. These requests will always be made against the main domain to support [Incremental Static Generation](/docs/basic-features/data-fetching/incremental-static-regeneration.md), even if you're not using it (for consistency). ## Related diff --git a/docs/api-reference/next.config.js/redirects.md b/docs/api-reference/next.config.js/redirects.md index 6a8e110db82f4..b0b396d2678e4 100644 --- a/docs/api-reference/next.config.js/redirects.md +++ b/docs/api-reference/next.config.js/redirects.md @@ -292,4 +292,4 @@ In some rare cases, you might need to assign a custom status code for older HTTP ## Other Redirects - Inside [API Routes](/docs/api-routes/response-helpers.md), you can use `res.redirect()`. -- Inside [`getStaticProps`](/docs/basic-features/data-fetching.md#getstaticprops-static-generation) and [`getServerSideProps`](/docs/basic-features/data-fetching.md#getserversideprops-server-side-rendering), you can redirect specific pages at request-time. +- Inside [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) and [`getServerSideProps`](/docs/basic-features/data-fetching/getServerSideProps.md), you can redirect specific pages at request-time. diff --git a/docs/api-reference/next.config.js/rewrites.md b/docs/api-reference/next.config.js/rewrites.md index 3a54cf4288ef9..d49e4dec93e62 100644 --- a/docs/api-reference/next.config.js/rewrites.md +++ b/docs/api-reference/next.config.js/rewrites.md @@ -148,7 +148,7 @@ module.exports = { } ``` -Note: for static pages from the [Automatic Static Optimization](/docs/advanced-features/automatic-static-optimization.md) or [prerendering](/docs/basic-features/data-fetching.md#getstaticprops-static-generation) params from rewrites will be parsed on the client after hydration and provided in the query. +Note: for static pages from the [Automatic Static Optimization](/docs/advanced-features/automatic-static-optimization.md) or [prerendering](/docs/basic-features/data-fetching/getStaticProps.md) params from rewrites will be parsed on the client after hydration and provided in the query. ## Path Matching diff --git a/docs/api-reference/next/link.md b/docs/api-reference/next/link.md index ba6b656b7aa9b..99d0cc423cde5 100644 --- a/docs/api-reference/next/link.md +++ b/docs/api-reference/next/link.md @@ -57,10 +57,10 @@ export default Home - `href` - The path or URL to navigate to. This is the only required prop - `as` - Optional decorator for the path that will be shown in the browser URL bar. Before Next.js 9.5.3 this was used for dynamic routes, check our [previous docs](https://nextjs.org/docs/tag/v9.5.2/api-reference/next/link#dynamic-routes) to see how it worked. Note: when this path differs from the one provided in `href` the previous `href`/`as` behavior is used as shown in the [previous docs](https://nextjs.org/docs/tag/v9.5.2/api-reference/next/link#dynamic-routes). - [`passHref`](#if-the-child-is-a-custom-component-that-wraps-an-a-tag) - Forces `Link` to send the `href` property to its child. Defaults to `false` -- `prefetch` - Prefetch the page in the background. Defaults to `true`. Any `` that is in the viewport (initially or through scroll) will be preloaded. Prefetch can be disabled by passing `prefetch={false}`. When `prefetch` is set to `false`, prefetching will still occur on hover. Pages using [Static Generation](/docs/basic-features/data-fetching.md#getstaticprops-static-generation) will preload `JSON` files with the data for faster page transitions. Prefetching is only enabled in production. +- `prefetch` - Prefetch the page in the background. Defaults to `true`. Any `` that is in the viewport (initially or through scroll) will be preloaded. Prefetch can be disabled by passing `prefetch={false}`. When `prefetch` is set to `false`, prefetching will still occur on hover. Pages using [Static Generation](/docs/basic-features/data-fetching/getStaticProps.md) will preload `JSON` files with the data for faster page transitions. Prefetching is only enabled in production. - [`replace`](#replace-the-url-instead-of-push) - Replace the current `history` state instead of adding a new url into the stack. Defaults to `false` - [`scroll`](#disable-scrolling-to-the-top-of-the-page) - Scroll to the top of the page after a navigation. Defaults to `true` -- [`shallow`](/docs/routing/shallow-routing.md) - Update the path of the current page without rerunning [`getStaticProps`](/docs/basic-features/data-fetching.md#getstaticprops-static-generation), [`getServerSideProps`](/docs/basic-features/data-fetching.md#getserversideprops-server-side-rendering) or [`getInitialProps`](/docs/api-reference/data-fetching/getInitialProps.md). Defaults to `false` +- [`shallow`](/docs/routing/shallow-routing.md) - Update the path of the current page without rerunning [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md), [`getServerSideProps`](/docs/basic-features/data-fetching/getServerSideProps.md) or [`getInitialProps`](/docs/api-reference/data-fetching/getInitialProps.md). Defaults to `false` - `locale` - The active locale is automatically prepended. `locale` allows for providing a different locale. When `false` `href` has to include the locale as the default behavior is disabled. ## If the route has dynamic segments diff --git a/docs/api-reference/next/router.md b/docs/api-reference/next/router.md index 5eb2fea698a36..c7877bbe1d329 100644 --- a/docs/api-reference/next/router.md +++ b/docs/api-reference/next/router.md @@ -42,9 +42,9 @@ export default ActiveLink The following is the definition of the `router` object returned by both [`useRouter`](#useRouter) and [`withRouter`](#withRouter): - `pathname`: `String` - Current route. That is the path of the page in `/pages`, the configured `basePath` or `locale` is not included. -- `query`: `Object` - The query string parsed to an object. It will be an empty object during prerendering if the page doesn't have [data fetching requirements](/docs/basic-features/data-fetching.md). Defaults to `{}` +- `query`: `Object` - The query string parsed to an object. It will be an empty object during prerendering if the page doesn't have [data fetching requirements](/docs/basic-features/data-fetching/index.md). Defaults to `{}` - `asPath`: `String` - The path (including the query) shown in the browser without the configured `basePath` or `locale`. -- `isFallback`: `boolean` - Whether the current page is in [fallback mode](/docs/basic-features/data-fetching.md#fallback-pages). +- `isFallback`: `boolean` - Whether the current page is in [fallback mode](/docs/api-reference/data-fetching/getStaticPaths.md#fallback-pages). - `basePath`: `String` - The active [basePath](/docs/api-reference/next.config.js/basepath.md) (if enabled). - `locale`: `String` - The active locale (if enabled). - `locales`: `String[]` - All supported locales (if enabled). @@ -74,7 +74,7 @@ router.push(url, as, options) - `as`: `UrlObject | String` - Optional decorator for the path that will be shown in the browser URL bar. Before Next.js 9.5.3 this was used for dynamic routes, check our [previous docs](https://nextjs.org/docs/tag/v9.5.2/api-reference/next/link#dynamic-routes) to see how it worked. Note: when this path differs from the one provided in `href` the previous `href`/`as` behavior is used as shown in the [previous docs](https://nextjs.org/docs/tag/v9.5.2/api-reference/next/link#dynamic-routes) - `options` - Optional object with the following configuration options: - `scroll` - Optional boolean, controls scrolling to the top of the page after navigation. Defaults to `true` - - [`shallow`](/docs/routing/shallow-routing.md): Update the path of the current page without rerunning [`getStaticProps`](/docs/basic-features/data-fetching.md#getstaticprops-static-generation), [`getServerSideProps`](/docs/basic-features/data-fetching.md#getserversideprops-server-side-rendering) or [`getInitialProps`](/docs/api-reference/data-fetching/getInitialProps.md). Defaults to `false` + - [`shallow`](/docs/routing/shallow-routing.md): Update the path of the current page without rerunning [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md), [`getServerSideProps`](/docs/basic-features/data-fetching/getServerSideProps.md) or [`getInitialProps`](/docs/api-reference/data-fetching/getInitialProps.md). Defaults to `false` - `locale` - Optional string, indicates locale of the new page > You don't need to use `router.push` for external URLs. [window.location](https://developer.mozilla.org/en-US/docs/Web/API/Window/location) is better suited for those cases. diff --git a/docs/authentication.md b/docs/authentication.md index 2afc9a05f9cf7..0d1ab70d0a62e 100644 --- a/docs/authentication.md +++ b/docs/authentication.md @@ -8,14 +8,14 @@ Authentication verifies who a user is, while authorization controls what a user ## Authentication Patterns -The first step to identifying which authentication pattern you need is understanding the [data-fetching strategy](/docs/basic-features/data-fetching.md) you want. We can then determine which authentication providers support this strategy. There are two main patterns: +The first step to identifying which authentication pattern you need is understanding the [data-fetching strategy](/docs/basic-features/data-fetching/index.md) you want. We can then determine which authentication providers support this strategy. There are two main patterns: - Use [static generation](/docs/basic-features/pages.md#static-generation-recommended) to server-render a loading state, followed by fetching user data client-side. - Fetch user data [server-side](/docs/basic-features/pages.md#server-side-rendering) to eliminate a flash of unauthenticated content. ### Authenticating Statically Generated Pages -Next.js automatically determines that a page is static if there are no blocking data requirements. This means the absence of [`getServerSideProps`](/docs/basic-features/data-fetching.md#getserversideprops-server-side-rendering) and `getInitialProps` in the page. Instead, your page can render a loading state from the server, followed by fetching the user client-side. +Next.js automatically determines that a page is static if there are no blocking data requirements. This means the absence of [`getServerSideProps`](/docs/basic-features/data-fetching/getServerSideProps.md) and `getInitialProps` in the page. Instead, your page can render a loading state from the server, followed by fetching the user client-side. One advantage of this pattern is it allows pages to be served from a global CDN and preloaded using [`next/link`](/docs/api-reference/next/link.md). In practice, this results in a faster TTI ([Time to Interactive](https://web.dev/interactive/)). @@ -52,7 +52,7 @@ You can view this [example in action](https://iron-session-example.vercel.app/). ### Authenticating Server-Rendered Pages -If you export an `async` function called [`getServerSideProps`](/docs/basic-features/data-fetching.md#getserversideprops-server-side-rendering) from a page, Next.js will pre-render this page on each request using the data returned by `getServerSideProps`. +If you export an `async` function called [`getServerSideProps`](/docs/basic-features/data-fetching/getServerSideProps.md) from a page, Next.js will pre-render this page on each request using the data returned by `getServerSideProps`. ```jsx export async function getServerSideProps(context) { @@ -154,7 +154,7 @@ For more information on what to do next, we recommend the following sections:
- + Data Fetching: Learn more about data fetching in Next.js. diff --git a/docs/basic-features/environment-variables.md b/docs/basic-features/environment-variables.md index 246c82e081df8..afceb8fd59cf3 100644 --- a/docs/basic-features/environment-variables.md +++ b/docs/basic-features/environment-variables.md @@ -30,9 +30,9 @@ DB_USER=myuser DB_PASS=mypassword ``` -This loads `process.env.DB_HOST`, `process.env.DB_USER`, and `process.env.DB_PASS` into the Node.js environment automatically allowing you to use them in [Next.js data fetching methods](/docs/basic-features/data-fetching.md) and [API routes](/docs/api-routes/introduction.md). +This loads `process.env.DB_HOST`, `process.env.DB_USER`, and `process.env.DB_PASS` into the Node.js environment automatically allowing you to use them in [Next.js data fetching methods](/docs/basic-features/data-fetching/index.md) and [API routes](/docs/api-routes/introduction.md). -For example, using [`getStaticProps`](/docs/basic-features/data-fetching.md#getstaticprops-static-generation): +For example, using [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md): ```js // pages/index.js diff --git a/docs/basic-features/pages.md b/docs/basic-features/pages.md index c01b5f046ce21..775efb9304c4a 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 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 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. +You can also 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/client-side.md) documentation. ## Static Generation (Recommended) @@ -137,7 +137,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.md#getstaticprops-static-generation). +To learn more about how `getStaticProps` works, check out the [Data Fetching documentation](/docs/basic-features/data-fetching/getStaticProps.md). #### Scenario 2: Your page paths depend on external data @@ -196,7 +196,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-static-generation). +To learn more about how `getStaticPaths` works, check out the [Data Fetching documentation](/docs/basic-features/data-fetching/getStaticPaths.md). ### When should I use Static Generation? @@ -215,7 +215,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.md#fetching-data-on-the-client-side). +- 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/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 @@ -248,7 +248,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-server-side-rendering) +To learn more about how `getServerSideProps` works, check out our [Data Fetching documentation](/docs/basic-features/data-fetching/getServerSideProps.md) ## Summary @@ -262,7 +262,7 @@ We've discussed two forms of pre-rendering for Next.js. We recommend you to read the following sections next:
- + Data Fetching: Learn more about data fetching in Next.js. diff --git a/docs/faq.md b/docs/faq.md index 8a1cec7254a91..187f8836762c3 100644 --- a/docs/faq.md +++ b/docs/faq.md @@ -39,7 +39,7 @@ description: Get to know more about Next.js with the frequently asked questions.
How do I fetch data? -

It's up to you. You can use the fetch API or SWR inside your React components for remote data fetching; or use our data fetching methods for initial data population.

+

It's up to you. You can use the fetch API or SWR inside your React components for remote data fetching; or use our data fetching methods for initial data population.

diff --git a/docs/getting-started.md b/docs/getting-started.md index d037f7ed9e418..a9d0501b1941b 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -91,7 +91,7 @@ So far, we get: - Automatic compilation and bundling (with webpack and babel) - [React Fast Refresh](https://nextjs.org/blog/next-9-4#fast-refresh) -- [Static generation and server-side rendering](/docs/basic-features/data-fetching.md) of [`./pages/`](/docs/basic-features/pages.md) +- [Static generation and server-side rendering](/docs/basic-features/data-fetching/index.md) of [`./pages/`](/docs/basic-features/pages.md) - [Static file serving](/docs/basic-features/static-file-serving.md). `./public/` is mapped to `/` In addition, any Next.js application is ready for production from the start, read more in our [Deployment documentation](/docs/deployment.md). diff --git a/docs/going-to-production.md b/docs/going-to-production.md index 55d94ef2b5728..d8547627b5712 100644 --- a/docs/going-to-production.md +++ b/docs/going-to-production.md @@ -38,7 +38,7 @@ Caching improves response times and reduces the number of requests to external s Cache-Control: public, max-age=31536000, immutable ``` -`Cache-Control` headers set in `next.config.js` will be overwritten in production to ensure that static assets can be cached effectively. If you need to revalidate the cache of a page that has been [statically generated](/docs/basic-features/pages.md#static-generation-recommended), you can do so by setting `revalidate` in the page's [`getStaticProps`](/docs/basic-features/data-fetching.md#getstaticprops-static-generation) function. If you're using `next/image`, there are also [specific caching rules](/docs/basic-features/image-optimization.md#caching) for the default Image Optimization loader. +`Cache-Control` headers set in `next.config.js` will be overwritten in production to ensure that static assets can be cached effectively. If you need to revalidate the cache of a page that has been [statically generated](/docs/basic-features/pages.md#static-generation-recommended), you can do so by setting `revalidate` in the page's [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) function. If you're using `next/image`, there are also [specific caching rules](/docs/basic-features/image-optimization.md#caching) for the default Image Optimization loader. **Note:** When running your application locally with `next dev`, your headers are overwritten to prevent caching locally. diff --git a/docs/migrating/from-create-react-app.md b/docs/migrating/from-create-react-app.md index 07ff81fd30cd3..f7d6eb980bd57 100644 --- a/docs/migrating/from-create-react-app.md +++ b/docs/migrating/from-create-react-app.md @@ -6,8 +6,8 @@ description: Learn how to transition an existing Create React App project to Nex This guide will help you understand how to transition from an existing non-ejected Create React App project to Next.js. Migrating to Next.js will allow you to: -- Choose which [data fetching](/docs/basic-features/data-fetching.md) strategy you want on a per-page basis. -- Use [Incremental Static Regeneration](/docs/basic-features/data-fetching.md#incremental-static-regeneration) to update _existing_ pages by re-rendering them in the background as traffic comes in. +- Choose which [data fetching](/docs/basic-features/data-fetching/index.md) strategy you want on a per-page basis. +- Use [Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration.md) to update _existing_ pages by re-rendering them in the background as traffic comes in. - Use [API Routes](/docs/api-routes/introduction.md). And more! Let’s walk through a series of steps to complete the migration. @@ -51,7 +51,7 @@ Create React App uses the `public` directory for the [entry HTML file](https://c With Create React App, you're likely using React Router. Instead of using a third-party library, Next.js includes its own [file-system based routing](/docs/routing/introduction.md). - Convert all `Route` components to new files in the `pages` directory. -- For routes that require dynamic content (e.g. `/blog/:slug`), you can use [Dynamic Routes](/docs/routing/dynamic-routes.md) with Next.js (e.g. `pages/blog/[slug].js`). The value of `slug` is accessible through a [query parameter](/docs/routing/dynamic-routes.md). For example, the route `/blog/first-post` would forward the query object `{ 'slug': 'first-post' }` to `pages/blog/[slug].js` ([learn more here](/docs/basic-features/data-fetching.md#getstaticpaths-static-generation)). +- For routes that require dynamic content (e.g. `/blog/:slug`), you can use [Dynamic Routes](/docs/routing/dynamic-routes.md) with Next.js (e.g. `pages/blog/[slug].js`). The value of `slug` is accessible through a [query parameter](/docs/routing/dynamic-routes.md). For example, the route `/blog/first-post` would forward the query object `{ 'slug': 'first-post' }` to `pages/blog/[slug].js` ([learn more here](/docs/basic-features/data-fetching/getStaticPaths.md)). For more information, see [Migrating from React Router](/docs/migrating/from-react-router.md). diff --git a/docs/migrating/from-gatsby.md b/docs/migrating/from-gatsby.md index 8198ee0ce5c8a..26fee4bc1726b 100644 --- a/docs/migrating/from-gatsby.md +++ b/docs/migrating/from-gatsby.md @@ -6,8 +6,8 @@ description: Learn how to transition an existing Gatsby project to Next.js. This guide will help you understand how to transition from an existing Gatsby project to Next.js. Migrating to Next.js will allow you to: -- Choose which [data fetching](/docs/basic-features/data-fetching.md) strategy you want on a per-page basis. -- Use [Incremental Static Regeneration](/docs/basic-features/data-fetching.md#incremental-static-regeneration) to update _existing_ pages by re-rendering them in the background as traffic comes in. +- Choose which [data fetching](/docs/basic-features/data-fetching/index.md) strategy you want on a per-page basis. +- Use [Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration.md) to update _existing_ pages by re-rendering them in the background as traffic comes in. - Use [API Routes](/docs/api-routes/introduction.md). And more! Let’s walk through a series of steps to complete the migration. @@ -52,7 +52,7 @@ Both Gatsby and Next support a `pages` directory, which uses [file-system based Gatsby creates dynamic routes using the `createPages` API inside of `gatsby-node.js`. With Next, we can use [Dynamic Routes](/docs/routing/dynamic-routes.md) inside of `pages` to achieve the same effect. Rather than having a `template` directory, you can use the React component inside your dynamic route file. For example: - **Gatsby:** `createPages` API inside `gatsby-node.js` for each blog post, then have a template file at `src/templates/blog-post.js`. -- **Next:** Create `pages/blog/[slug].js` which contains the blog post template. The value of `slug` is accessible through a [query parameter](/docs/routing/dynamic-routes.md). For example, the route `/blog/first-post` would forward the query object `{ 'slug': 'first-post' }` to `pages/blog/[slug].js` ([learn more here](/docs/basic-features/data-fetching.md#getstaticpaths-static-generation)). +- **Next:** Create `pages/blog/[slug].js` which contains the blog post template. The value of `slug` is accessible through a [query parameter](/docs/routing/dynamic-routes.md). For example, the route `/blog/first-post` would forward the query object `{ 'slug': 'first-post' }` to `pages/blog/[slug].js` ([learn more here](/docs/basic-features/data-fetching/getStaticPaths.md)). ## Styling @@ -92,7 +92,7 @@ Update any import statements, switch `to` to `href`, and add an `` tag as a c The largest difference between Gatsby and Next.js is how data fetching is implemented. Gatsby is opinionated with GraphQL being the default strategy for retrieving data across your application. With Next.js, you get to choose which strategy you want (GraphQL is one supported option). -Gatsby uses the `graphql` tag to query data in the pages of your site. This may include local data, remote data, or information about your site configuration. Gatsby only allows the creation of static pages. With Next.js, you can choose on a [per-page basis](/docs/basic-features/pages.md) which [data fetching strategy](/docs/basic-features/data-fetching.md) you want. For example, `getServerSideProps` allows you to do server-side rendering. If you wanted to generate a static page, you'd export `getStaticProps` / `getStaticPaths` inside the page, rather than using `pageQuery`. For example: +Gatsby uses the `graphql` tag to query data in the pages of your site. This may include local data, remote data, or information about your site configuration. Gatsby only allows the creation of static pages. With Next.js, you can choose on a [per-page basis](/docs/basic-features/pages.md) which [data fetching strategy](/docs/basic-features/data-fetching/index.md) you want. For example, `getServerSideProps` allows you to do server-side rendering. If you wanted to generate a static page, you'd export `getStaticProps` / `getStaticPaths` inside the page, rather than using `pageQuery`. For example: ```js // src/pages/[slug].js diff --git a/docs/routing/introduction.md b/docs/routing/introduction.md index 2481440ff15ce..6abb5b933d65a 100644 --- a/docs/routing/introduction.md +++ b/docs/routing/introduction.md @@ -74,7 +74,7 @@ The example above uses multiple links. Each one maps a path (`href`) to a known - `/about` → `pages/about.js` - `/blog/hello-world` → `pages/blog/[slug].js` -Any `` in the viewport (initially or through scroll) will be prefetched by default (including the corresponding data) for pages using [Static Generation](/docs/basic-features/data-fetching.md#getstaticprops-static-generation). The corresponding data for [server-rendered](https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering) routes is _not_ prefetched. +Any `` in the viewport (initially or through scroll) will be prefetched by default (including the corresponding data) for pages using [Static Generation](/docs/basic-features/data-fetching/getStaticProps.md). The corresponding data for [server-rendered](https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering) routes is _not_ prefetched. ### Linking to dynamic paths diff --git a/docs/routing/shallow-routing.md b/docs/routing/shallow-routing.md index caa9cf35138e1..377597282d1bc 100644 --- a/docs/routing/shallow-routing.md +++ b/docs/routing/shallow-routing.md @@ -11,7 +11,7 @@ description: You can use shallow routing to change the URL without triggering a
-Shallow routing allows you to change the URL without running data fetching methods again, that includes [`getServerSideProps`](/docs/basic-features/data-fetching.md#getserversideprops-server-side-rendering), [`getStaticProps`](/docs/basic-features/data-fetching.md#getstaticprops-static-generation), and [`getInitialProps`](/docs/api-reference/data-fetching/getInitialProps.md). +Shallow routing allows you to change the URL without running data fetching methods again, that includes [`getServerSideProps`](/docs/basic-features/data-fetching/getServerSideProps.md), [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md), and [`getInitialProps`](/docs/api-reference/data-fetching/getInitialProps.md). You'll receive the updated `pathname` and the `query` via the [`router` object](/docs/api-reference/next/router.md#router-object) (added by [`useRouter`](/docs/api-reference/next/router.md#useRouter) or [`withRouter`](/docs/api-reference/next/router.md#withRouter)), without losing state. diff --git a/examples/blog/pages/posts/pages.md b/examples/blog/pages/posts/pages.md index d97c0afefc3d8..b719fd7afe2b9 100644 --- a/examples/blog/pages/posts/pages.md +++ b/examples/blog/pages/posts/pages.md @@ -43,7 +43,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 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 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. +You can also 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/client-side.md) documentation. ## Static Generation (Recommended) @@ -117,7 +117,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.md#getstaticprops-static-generation). +To learn more about how `getStaticProps` works, check out the [Data Fetching documentation](/docs/basic-features/data-fetching/getStaticProps.md). #### Scenario 2: Your page paths depend on external data @@ -176,7 +176,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-static-generation). +To learn more about how `getStaticPaths` works, check out the [Data Fetching documentation](/docs/basic-features/data-fetching/getStaticPaths.md). ### When should I use Static Generation? @@ -195,7 +195,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.md#fetching-data-on-the-client-side). +- 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/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 @@ -228,7 +228,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-server-side-rendering) +To learn more about how `getServerSideProps` works, check out our [Data Fetching documentation](/docs/basic-features/data-fetching/getServerSideProps.md) ## Summary From ae0eff3c68ed25e85c86614341e23bed284ac3c0 Mon Sep 17 00:00:00 2001 From: molebox Date: Fri, 10 Dec 2021 13:04:42 +0100 Subject: [PATCH 62/70] Conflicts + fix links --- docs/api-reference/data-fetching/getStaticPaths.md | 4 ++-- docs/api-reference/data-fetching/getStaticProps.md | 2 +- docs/basic-features/data-fetching/getServerSideProps.md | 2 +- docs/basic-features/data-fetching/getStaticPaths.md | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/api-reference/data-fetching/getStaticPaths.md b/docs/api-reference/data-fetching/getStaticPaths.md index 7d537881667a2..f1b7b02f56dcd 100644 --- a/docs/api-reference/data-fetching/getStaticPaths.md +++ b/docs/api-reference/data-fetching/getStaticPaths.md @@ -127,7 +127,7 @@ Shortly after, `getStaticProps` finishes and the page will be rendered with the This ensures that users always have a fast experience while preserving fast builds and the benefits of Static Generation. -`fallback: true` will not _update_ generated pages, for that take a look at [Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration). +`fallback: true` will not _update_ generated pages, for that take a look at [Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration.md). ### `fallback: 'blocking'` @@ -140,7 +140,7 @@ If `fallback` is `'blocking'`, new paths not returned by `getStaticPaths` will w - When complete, the browser receives the `HTML` for the generated path. From the user’s perspective, it will transition from "the browser is requesting the page" to "the full page is loaded". There is no flash of loading/fallback state. - 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: 'blocking'` will not _update_ generated pages by default. To update generated pages, use [Incremental Static Regeneration](/docs/basic-features/data-fetching/index#incremental-static-regeneration) in conjunction with `fallback: 'blocking'`. +`fallback: 'blocking'` will not _update_ generated pages by default. To update generated pages, use [Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration.md) in conjunction with `fallback: 'blocking'`. > **Note:** `fallback: 'blocking'` is not supported when using [`next export`](/docs/advanced-features/static-html-export.md). diff --git a/docs/api-reference/data-fetching/getStaticProps.md b/docs/api-reference/data-fetching/getStaticProps.md index df8dbfe854718..ed1763528b045 100644 --- a/docs/api-reference/data-fetching/getStaticProps.md +++ b/docs/api-reference/data-fetching/getStaticProps.md @@ -78,7 +78,7 @@ export async function getStaticProps() { } ``` -Learn more about [Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration) +Learn more about [Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration.md) ### `notFound` diff --git a/docs/basic-features/data-fetching/getServerSideProps.md b/docs/basic-features/data-fetching/getServerSideProps.md index c7d6cbd283faa..48ac1981cccc1 100644 --- a/docs/basic-features/data-fetching/getServerSideProps.md +++ b/docs/basic-features/data-fetching/getServerSideProps.md @@ -4,7 +4,7 @@ description: Fetch data on each request with `getServerSideProps`. # `getServerSideProps` -If you export an `async` function called `getServerSideProps` (server-side rendering) from a page, Next.js will pre-render this page on each request using the data returned by `getServerSideProps`. +If you export a function called `getServerSideProps` (Server-Side Rendering) 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) { diff --git a/docs/basic-features/data-fetching/getStaticPaths.md b/docs/basic-features/data-fetching/getStaticPaths.md index 7cee625d929a9..035d60fc6c30f 100644 --- a/docs/basic-features/data-fetching/getStaticPaths.md +++ b/docs/basic-features/data-fetching/getStaticPaths.md @@ -6,7 +6,7 @@ description: Fetch data and generate static pages with `getStaticProps`. Learn m If a page has [Dynamic Routes](/docs/routing/dynamic-routes.md) and uses `getStaticProps`, it needs to define a list of paths to be statically generated. -When you export an `async` function called `getStaticPaths` (static generation) from a page that uses dynamic routes, Next.js will statically pre-render all the paths specified by `getStaticPaths`. +When you export a function called `getStaticPaths` (Static Site Generation) from a page that uses dynamic routes, Next.js will statically pre-render all the paths specified by `getStaticPaths`. ```jsx export async function getStaticPaths() { From e277eac00689395dbb9343d08d64b031d2083501 Mon Sep 17 00:00:00 2001 From: molebox Date: Fri, 10 Dec 2021 13:16:13 +0100 Subject: [PATCH 63/70] Fixed meta description rendering because of ' --- docs/basic-features/data-fetching/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/basic-features/data-fetching/index.md b/docs/basic-features/data-fetching/index.md index ad5d3e72c7aa5..af201869a58bc 100644 --- a/docs/basic-features/data-fetching/index.md +++ b/docs/basic-features/data-fetching/index.md @@ -1,5 +1,5 @@ --- -description: 'Data fetching in Next.js allows you to render your content in different ways, depending on your application's use case. These include pre-rendering with server-side rendering or static-site generation, and incremental static regeneration. Learn how to manage your application data in Next.js.' +description: 'Data fetching in Next.js allows you to render your content in different ways, depending on your applications use case. These include pre-rendering with server-side rendering or static-site generation, and incremental static regeneration. Learn how to manage your application data in Next.js.' --- # Data Fetching Overview From c30c1042d2c6f366a6f3baed68111d7fd7fbb5a9 Mon Sep 17 00:00:00 2001 From: molebox Date: Fri, 10 Dec 2021 13:35:12 +0100 Subject: [PATCH 64/70] Added missing suggestions from feedback --- docs/api-reference/data-fetching/getStaticProps.md | 1 + docs/basic-features/data-fetching/client-side.md | 2 +- docs/basic-features/data-fetching/getServerSideProps.md | 6 +++--- docs/basic-features/data-fetching/getStaticPaths.md | 2 +- docs/basic-features/data-fetching/getStaticProps.md | 6 +++--- 5 files changed, 9 insertions(+), 8 deletions(-) diff --git a/docs/api-reference/data-fetching/getStaticProps.md b/docs/api-reference/data-fetching/getStaticProps.md index ed1763528b045..604a3a7f813e4 100644 --- a/docs/api-reference/data-fetching/getStaticProps.md +++ b/docs/api-reference/data-fetching/getStaticProps.md @@ -12,6 +12,7 @@ description: API reference for `getStaticProps`. Learn how to use `getStaticProp | `v10.0.0` | `locale`, `locales`, `defaultLocale`, and `notFound` options added. | | `v9.5.0` | Stable [Incremental Static Regeneration](https://nextjs.org/blog/next-9-5#stable-incremental-static-regeneration) | | `v9.3.0` | `getStaticProps` introduced. | +| `v10.0.0` | `fallback: 'blocking'` return option added. | diff --git a/docs/basic-features/data-fetching/client-side.md b/docs/basic-features/data-fetching/client-side.md index eacf7f14d0c5f..6c0837e191d12 100644 --- a/docs/basic-features/data-fetching/client-side.md +++ b/docs/basic-features/data-fetching/client-side.md @@ -41,7 +41,7 @@ function Profile() { } ``` -# Client-side data fetching with SWR +## Client-side data fetching with SWR The team behind Next.js has created a React hook library for data fetching called [**SWR**](https://swr.vercel.app/). It is **highly recommend** if you are fetching data on the client-side. It handles caching, revalidation, focus tracking, refetching on intervals, and more. diff --git a/docs/basic-features/data-fetching/getServerSideProps.md b/docs/basic-features/data-fetching/getServerSideProps.md index 48ac1981cccc1..92714fb469944 100644 --- a/docs/basic-features/data-fetching/getServerSideProps.md +++ b/docs/basic-features/data-fetching/getServerSideProps.md @@ -19,7 +19,7 @@ export async function getServerSideProps(context) { `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 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`](/docs/api-reference/next/link.md)) or ([`next/router`](/docs/api-reference/next/router.md)), Next.js sends an API request to the server, which runs `getServerSideProps`. +- When you request this page on client-side page transitions through [`next/link`](/docs/api-reference/next/link.md) or [`next/router`](/docs/api-reference/next/router.md), Next.js sends an API request to the server, which runs `getServerSideProps`. It then returns `JSON` that contains the result of running `getServerSideProps`, that `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. @@ -27,13 +27,13 @@ You can use the [next-code-elimination tool](https://next-code-elimination.verce `getServerSideProps` can only be exported from a **page**. You can’t export it from non-page files. -You must export `getServerSideProps` as a standalone function — it will **not** work if you add `getServerSideProps` as a property of the page component. +Note that you must export `getServerSideProps` as a standalone function — it will **not** work if you add `getServerSideProps` as a property of the page component. The [`getServerSideProps` API reference](/docs/api-reference/data-fetching/getServerSideProps.md) covers all parameters and props that can be used with `getServerSideProps`. ## When should I use `getServerSideProps`? -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)](/learn/seo/web-performance) will be slower than [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) because the server must compute the result on every request, and the result can only be cached by a CDN using `cache-control` headers (which could require extra configuration). +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)](/learn/seo/web-performance) will be higher than [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) because the server must compute the result on every request, and the result can only be cached by a CDN using `cache-control` headers (which could require extra configuration). If you do not need to pre-render the data, then you should consider fetching data on the [client side](#fetching-data-on-the-client-side). diff --git a/docs/basic-features/data-fetching/getStaticPaths.md b/docs/basic-features/data-fetching/getStaticPaths.md index 035d60fc6c30f..b4ddfe861f69a 100644 --- a/docs/basic-features/data-fetching/getStaticPaths.md +++ b/docs/basic-features/data-fetching/getStaticPaths.md @@ -41,7 +41,7 @@ You should use `getStaticPaths` if you’re statically pre-rendering pages that `getStaticPaths` can only be exported from a **page**. You **cannot** export it from non-page files. -You must use export `getStaticPaths` as a standalone function — it will **not** work if you add `getStaticPaths` as a property of the page component. +Note that you must use export `getStaticPaths` as a standalone function — it will **not** work if you add `getStaticPaths` as a property of the page component. ## Runs on every request in development diff --git a/docs/basic-features/data-fetching/getStaticProps.md b/docs/basic-features/data-fetching/getStaticProps.md index d0dfb8e811e5c..5de3a33a881d4 100644 --- a/docs/basic-features/data-fetching/getStaticProps.md +++ b/docs/basic-features/data-fetching/getStaticProps.md @@ -84,7 +84,7 @@ This JSON file will be used in client-side routing through [`next/link`](/docs/a When using Incremental Static Generation `getStaticProps` will be executed out of band to generate the JSON needed for client-side navigation. You may see this in the form of multiple requests being made for the same page, however, this is intended and has no impact on end-user performance -### Where can I use `getStaticProps` +## Where can I use `getStaticProps` `getStaticProps` can only be exported from a **page**. You **cannot** export it from non-page files. @@ -92,11 +92,11 @@ One of the reasons for this restriction is that React needs to have all the requ Also, you must use export `getStaticProps` as a standalone function — it will **not** work if you add `getStaticProps` as a property of the page component. -### Runs on every request in development +## Runs on every request in development In development (`next dev`), `getStaticProps` will be called on every request. -### Preview Mode +## Preview Mode In some cases, you might want to temporarily bypass Static Generation and render the page at **request time** instead of build time. For example, you might be using a headless CMS and want to preview drafts before they're published. From d141210d57c784ff011635ffa90514e1e68b0110 Mon Sep 17 00:00:00 2001 From: molebox Date: Fri, 10 Dec 2021 13:38:58 +0100 Subject: [PATCH 65/70] Removed comment that linked to removed section --- docs/api-reference/data-fetching/getStaticProps.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api-reference/data-fetching/getStaticProps.md b/docs/api-reference/data-fetching/getStaticProps.md index 604a3a7f813e4..c737a59006ed1 100644 --- a/docs/api-reference/data-fetching/getStaticProps.md +++ b/docs/api-reference/data-fetching/getStaticProps.md @@ -163,7 +163,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. export async function getStaticProps() { const postsDirectory = path.join(process.cwd(), 'posts') const filenames = await fs.readdir(postsDirectory) From b257aa2046df74e0ce8870b72d8a132116a02da5 Mon Sep 17 00:00:00 2001 From: molebox Date: Tue, 14 Dec 2021 09:58:07 +0100 Subject: [PATCH 66/70] Fixed alex warnings --- docs/api-reference/data-fetching/getStaticPaths.md | 4 ++-- .../data-fetching/incremental-static-regeneration.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/api-reference/data-fetching/getStaticPaths.md b/docs/api-reference/data-fetching/getStaticPaths.md index f1b7b02f56dcd..ebefdffbab47e 100644 --- a/docs/api-reference/data-fetching/getStaticPaths.md +++ b/docs/api-reference/data-fetching/getStaticPaths.md @@ -113,7 +113,7 @@ If `fallback` is `true`, then the behavior of `getStaticProps` changes in the fo - The paths that have not been generated at build time will **not** result in a 404 page. Instead, Next.js will serve a [“fallback”](#fallback-pages) version of the page on the first request to such a path. - In the background, Next.js will statically generate the requested path `HTML` and `JSON`. This includes running `getStaticProps`. - When complete, 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. +- 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, like other pages pre-rendered at build time. > **Note:** `fallback: true` is not supported when using [`next export`](/docs/advanced-features/static-html-export.md). @@ -138,7 +138,7 @@ If `fallback` is `'blocking'`, new paths not returned by `getStaticPaths` will w - The paths returned from `getStaticPaths` will be rendered to `HTML` at build time by `getStaticProps`. - The paths that have not been generated at build time will **not** result in a 404 page. Instead, Next.js will SSR on the first request and return the generated `HTML`. - When complete, the browser receives the `HTML` for the generated path. From the user’s perspective, it will transition from "the browser is requesting the page" to "the full page is loaded". There is no flash of loading/fallback state. -- 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. +- 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, like other pages pre-rendered at build time. `fallback: 'blocking'` will not _update_ generated pages by default. To update generated pages, use [Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration.md) in conjunction with `fallback: 'blocking'`. diff --git a/docs/basic-features/data-fetching/incremental-static-regeneration.md b/docs/basic-features/data-fetching/incremental-static-regeneration.md index f413c514eb201..7a7d197c3d09c 100644 --- a/docs/basic-features/data-fetching/incremental-static-regeneration.md +++ b/docs/basic-features/data-fetching/incremental-static-regeneration.md @@ -81,7 +81,7 @@ When a request is made to a page that was pre-rendered at build time, it will in - Any requests to the page after the initial request and before 10 seconds are also cached and instantaneous. - After the 10-second window, the next request will still show the cached (stale) page - Next.js triggers a regeneration of the page in the background. -- Once the page has been successfully generated, Next.js will invalidate the cache and show the updated page. If the background regeneration fails, the old page remains unaltered. +- Once the page has been successfully generated, Next.js will invalidate the cache and show the updated page. If the background regeneration fails, the old page would still be unaltered. When a request is made to a path that hasn’t been generated, Next.js will server-render the page on the first request. Future requests will serve the static file from the cache. From ef2131ca6cf0357d97c0725a6bb959a35e2a47d8 Mon Sep 17 00:00:00 2001 From: molebox Date: Mon, 20 Dec 2021 14:12:16 +0100 Subject: [PATCH 67/70] Changed path of getInitialProps and getServerSideProps to kebab-case --- docs/advanced-features/custom-app.md | 4 ++-- docs/advanced-features/custom-document.md | 4 ++-- docs/advanced-features/static-html-export.md | 6 +++--- .../{getInitialProps.md => get-initial-props.md} | 2 +- .../{getServerSideProps.md => get-server-side-props.md} | 0 docs/api-reference/next.config.js/redirects.md | 2 +- docs/api-reference/next/link.md | 2 +- docs/api-reference/next/router.md | 2 +- docs/authentication.md | 4 ++-- .../{getServerSideProps.md => get-server-side-props.md} | 2 +- docs/basic-features/data-fetching/getStaticPaths.md | 2 +- docs/basic-features/data-fetching/index.md | 2 +- docs/basic-features/pages.md | 2 +- docs/basic-features/typescript.md | 2 +- docs/manifest.json | 6 +++--- docs/routing/shallow-routing.md | 2 +- errors/get-initial-props-as-an-instance-method.md | 2 +- examples/blog/pages/posts/pages.md | 2 +- 18 files changed, 24 insertions(+), 24 deletions(-) rename docs/api-reference/data-fetching/{getInitialProps.md => get-initial-props.md} (96%) rename docs/api-reference/data-fetching/{getServerSideProps.md => get-server-side-props.md} (100%) rename docs/basic-features/data-fetching/{getServerSideProps.md => get-server-side-props.md} (97%) diff --git a/docs/advanced-features/custom-app.md b/docs/advanced-features/custom-app.md index 953eee3723101..b436569f1272f 100644 --- a/docs/advanced-features/custom-app.md +++ b/docs/advanced-features/custom-app.md @@ -43,9 +43,9 @@ The `Component` prop is the active `page`, so whenever you navigate between rout ### Caveats - If your app is running and you added a custom `App`, you'll need to restart the development server. Only required if `pages/_app.js` didn't exist before. -- Adding a custom [`getInitialProps`](/docs/api-reference/data-fetching/getInitialProps.md) in your `App` will disable [Automatic Static Optimization](/docs/advanced-features/automatic-static-optimization.md) in pages without [Static Generation](/docs/basic-features/data-fetching/getStaticProps.md). +- Adding a custom [`getInitialProps`](/docs/api-reference/data-fetching/get-initial-props.md) in your `App` will disable [Automatic Static Optimization](/docs/advanced-features/automatic-static-optimization.md) in pages without [Static Generation](/docs/basic-features/data-fetching/getStaticProps.md). - When you add `getInitialProps` in your custom app, you must `import App from "next/app"`, call `App.getInitialProps(appContext)` inside `getInitialProps` and merge the returned object into the return value. -- `App` currently does not support Next.js [Data Fetching methods](/docs/basic-features/data-fetching/index.md) like [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) or [`getServerSideProps`](/docs/basic-features/data-fetching/getServerSideProps.md). +- `App` currently does not support Next.js [Data Fetching methods](/docs/basic-features/data-fetching/index.md) like [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) or [`getServerSideProps`](/docs/basic-features/data-fetching/get-server-side-props.md). ### TypeScript diff --git a/docs/advanced-features/custom-document.md b/docs/advanced-features/custom-document.md index e99d32e89abab..a726b09d62d60 100644 --- a/docs/advanced-features/custom-document.md +++ b/docs/advanced-features/custom-document.md @@ -45,7 +45,7 @@ Custom attributes are allowed as props, like `lang`: The `` component used here is not the same one from [`next/head`](/docs/api-reference/next/head.md). The `` component used here should only be used for any `` code that is common for all pages. For all other cases, such as `` tags, we recommend using [`next/head`](/docs/api-reference/next/head.md) in your pages or components. -The `ctx` object is equivalent to the one received in [`getInitialProps`](/docs/api-reference/data-fetching/getInitialProps.md#context-object), with one addition: +The `ctx` object is equivalent to the one received in [`getInitialProps`](/docs/api-reference/data-fetching/get-initial-props.md#context-object), with one addition: - `renderPage`: `Function` - a callback that runs the actual React rendering logic (synchronously). It's useful to decorate this function in order to support server-rendering wrappers like Aphrodite's [`renderStatic`](https://github.com/Khan/aphrodite#server-side-rendering) @@ -54,7 +54,7 @@ The `ctx` object is equivalent to the one received in [`getInitialProps`](/docs/ - `Document` is only rendered in the server, event handlers like `onClick` won't work. - React components outside of `<Main />` will not be initialized by the browser. Do _not_ add application logic here or custom CSS (like `styled-jsx`). If you need shared components in all your pages (like a menu or a toolbar), take a look at the [`App`](/docs/advanced-features/custom-app.md) component instead. - `Document`'s `getInitialProps` function is not called during client-side transitions, nor when a page is [statically optimized](/docs/advanced-features/automatic-static-optimization.md). -- `Document` currently does not support Next.js [Data Fetching methods](/docs/basic-features/data-fetching/index.md) like [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) or [`getServerSideProps`](/docs/basic-features/data-fetching/getServerSideProps.md). +- `Document` currently does not support Next.js [Data Fetching methods](/docs/basic-features/data-fetching/index.md) like [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) or [`getServerSideProps`](/docs/basic-features/data-fetching/get-server-side-props.md). ## Customizing `renderPage` diff --git a/docs/advanced-features/static-html-export.md b/docs/advanced-features/static-html-export.md index c49da4959aef7..37546e0a12592 100644 --- a/docs/advanced-features/static-html-export.md +++ b/docs/advanced-features/static-html-export.md @@ -58,14 +58,14 @@ Features that require a Node.js server, or dynamic logic that cannot be computed - [Middleware](/docs/middleware.md) - [Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration.md) - [`fallback: true`](/docs/api-reference/data-fetching/getStaticPaths.md#fallback-true) -- [`getServerSideProps`](/docs/basic-features/data-fetching/getServerSideProps.md) +- [`getServerSideProps`](/docs/basic-features/data-fetching/get-server-side-props.md) ### `getInitialProps` -It's possible to use the [`getInitialProps`](/docs/api-reference/data-fetching/getInitialProps.md) API instead of `getStaticProps`, but it comes with a few caveats: +It's possible to use the [`getInitialProps`](/docs/api-reference/data-fetching/get-initial-props.md) API instead of `getStaticProps`, but it comes with a few caveats: - `getInitialProps` cannot be used alongside `getStaticProps` or `getStaticPaths` on any given page. If you have dynamic routes, instead of using `getStaticPaths` you'll need to configure the [`exportPathMap`](/docs/api-reference/next.config.js/exportPathMap.md) parameter in your [`next.config.js`](/docs/api-reference/next.config.js/introduction.md) file to let the exporter know which HTML files it should output. -- When `getInitialProps` is called during export, the `req` and `res` fields of its [`context`](/docs/api-reference/data-fetching/getInitialProps.md#context-object) parameter will be empty objects, since during export there is no server running. +- When `getInitialProps` is called during export, the `req` and `res` fields of its [`context`](/docs/api-reference/data-fetching/get-initial-props.md#context-object) parameter will be empty objects, since during export there is no server running. - `getInitialProps` **will be called on every client-side navigation**, if you'd like to only fetch data at build-time, switch to `getStaticProps`. - `getInitialProps` should fetch from an API and cannot use Node.js-specific libraries or the file system like `getStaticProps` can. diff --git a/docs/api-reference/data-fetching/getInitialProps.md b/docs/api-reference/data-fetching/get-initial-props.md similarity index 96% rename from docs/api-reference/data-fetching/getInitialProps.md rename to docs/api-reference/data-fetching/get-initial-props.md index a209da0612502..a9deb90e17128 100644 --- a/docs/api-reference/data-fetching/getInitialProps.md +++ b/docs/api-reference/data-fetching/get-initial-props.md @@ -4,7 +4,7 @@ description: Enable Server-Side Rendering in a page and do initial data populati # getInitialProps -**Recommended: [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) or [`getServerSideProps`](/docs/basic-features/data-fetching/getServerSideProps.md)** instead of `getInitialProps`. These data fetching methods allow you to have a granular choice between static generation and server-side rendering. +**Recommended: [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) or [`getServerSideProps`](/docs/basic-features/data-fetching/get-server-side-props.md)** instead of `getInitialProps`. These data fetching methods allow you to have a granular choice between static generation and server-side rendering. `getInitialProps` enables [server-side rendering](/docs/basic-features/pages.md#server-side-rendering) in a page and allows you to do **initial data population**, it means sending the [page](/docs/basic-features/pages.md) with the data already populated from the server. This is especially useful for [SEO](https://en.wikipedia.org/wiki/Search_engine_optimization). diff --git a/docs/api-reference/data-fetching/getServerSideProps.md b/docs/api-reference/data-fetching/get-server-side-props.md similarity index 100% rename from docs/api-reference/data-fetching/getServerSideProps.md rename to docs/api-reference/data-fetching/get-server-side-props.md diff --git a/docs/api-reference/next.config.js/redirects.md b/docs/api-reference/next.config.js/redirects.md index b0b396d2678e4..b60af50241d82 100644 --- a/docs/api-reference/next.config.js/redirects.md +++ b/docs/api-reference/next.config.js/redirects.md @@ -292,4 +292,4 @@ In some rare cases, you might need to assign a custom status code for older HTTP ## Other Redirects - Inside [API Routes](/docs/api-routes/response-helpers.md), you can use `res.redirect()`. -- Inside [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) and [`getServerSideProps`](/docs/basic-features/data-fetching/getServerSideProps.md), you can redirect specific pages at request-time. +- Inside [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) and [`getServerSideProps`](/docs/basic-features/data-fetching/get-server-side-props.md), you can redirect specific pages at request-time. diff --git a/docs/api-reference/next/link.md b/docs/api-reference/next/link.md index 99d0cc423cde5..0646b9a029eb1 100644 --- a/docs/api-reference/next/link.md +++ b/docs/api-reference/next/link.md @@ -60,7 +60,7 @@ export default Home - `prefetch` - Prefetch the page in the background. Defaults to `true`. Any `<Link />` that is in the viewport (initially or through scroll) will be preloaded. Prefetch can be disabled by passing `prefetch={false}`. When `prefetch` is set to `false`, prefetching will still occur on hover. Pages using [Static Generation](/docs/basic-features/data-fetching/getStaticProps.md) will preload `JSON` files with the data for faster page transitions. Prefetching is only enabled in production. - [`replace`](#replace-the-url-instead-of-push) - Replace the current `history` state instead of adding a new url into the stack. Defaults to `false` - [`scroll`](#disable-scrolling-to-the-top-of-the-page) - Scroll to the top of the page after a navigation. Defaults to `true` -- [`shallow`](/docs/routing/shallow-routing.md) - Update the path of the current page without rerunning [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md), [`getServerSideProps`](/docs/basic-features/data-fetching/getServerSideProps.md) or [`getInitialProps`](/docs/api-reference/data-fetching/getInitialProps.md). Defaults to `false` +- [`shallow`](/docs/routing/shallow-routing.md) - Update the path of the current page without rerunning [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md), [`getServerSideProps`](/docs/basic-features/data-fetching/get-server-side-props.md) or [`getInitialProps`](/docs/api-reference/data-fetching/get-initial-props.md). Defaults to `false` - `locale` - The active locale is automatically prepended. `locale` allows for providing a different locale. When `false` `href` has to include the locale as the default behavior is disabled. ## If the route has dynamic segments diff --git a/docs/api-reference/next/router.md b/docs/api-reference/next/router.md index be75fb6278a20..27301660c6855 100644 --- a/docs/api-reference/next/router.md +++ b/docs/api-reference/next/router.md @@ -74,7 +74,7 @@ router.push(url, as, options) - `as`: `UrlObject | String` - Optional decorator for the path that will be shown in the browser URL bar. Before Next.js 9.5.3 this was used for dynamic routes, check our [previous docs](https://nextjs.org/docs/tag/v9.5.2/api-reference/next/link#dynamic-routes) to see how it worked. Note: when this path differs from the one provided in `href` the previous `href`/`as` behavior is used as shown in the [previous docs](https://nextjs.org/docs/tag/v9.5.2/api-reference/next/link#dynamic-routes) - `options` - Optional object with the following configuration options: - `scroll` - Optional boolean, controls scrolling to the top of the page after navigation. Defaults to `true` - - [`shallow`](/docs/routing/shallow-routing.md): Update the path of the current page without rerunning [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md), [`getServerSideProps`](/docs/basic-features/data-fetching/getServerSideProps.md) or [`getInitialProps`](/docs/api-reference/data-fetching/getInitialProps.md). Defaults to `false` + - [`shallow`](/docs/routing/shallow-routing.md): Update the path of the current page without rerunning [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md), [`getServerSideProps`](/docs/basic-features/data-fetching/get-server-side-props.md) or [`getInitialProps`](/docs/api-reference/data-fetching/get-initial-props.md). Defaults to `false` - `locale` - Optional string, indicates locale of the new page > You don't need to use `router.push` for external URLs. [window.location](https://developer.mozilla.org/en-US/docs/Web/API/Window/location) is better suited for those cases. diff --git a/docs/authentication.md b/docs/authentication.md index 0d1ab70d0a62e..45dc5bbe185a4 100644 --- a/docs/authentication.md +++ b/docs/authentication.md @@ -15,7 +15,7 @@ The first step to identifying which authentication pattern you need is understan ### Authenticating Statically Generated Pages -Next.js automatically determines that a page is static if there are no blocking data requirements. This means the absence of [`getServerSideProps`](/docs/basic-features/data-fetching/getServerSideProps.md) and `getInitialProps` in the page. Instead, your page can render a loading state from the server, followed by fetching the user client-side. +Next.js automatically determines that a page is static if there are no blocking data requirements. This means the absence of [`getServerSideProps`](/docs/basic-features/data-fetching/get-server-side-props.md) and `getInitialProps` in the page. Instead, your page can render a loading state from the server, followed by fetching the user client-side. One advantage of this pattern is it allows pages to be served from a global CDN and preloaded using [`next/link`](/docs/api-reference/next/link.md). In practice, this results in a faster TTI ([Time to Interactive](https://web.dev/interactive/)). @@ -52,7 +52,7 @@ You can view this [example in action](https://iron-session-example.vercel.app/). ### Authenticating Server-Rendered Pages -If you export an `async` function called [`getServerSideProps`](/docs/basic-features/data-fetching/getServerSideProps.md) from a page, Next.js will pre-render this page on each request using the data returned by `getServerSideProps`. +If you export an `async` function called [`getServerSideProps`](/docs/basic-features/data-fetching/get-server-side-props.md) from a page, Next.js will pre-render this page on each request using the data returned by `getServerSideProps`. ```jsx export async function getServerSideProps(context) { diff --git a/docs/basic-features/data-fetching/getServerSideProps.md b/docs/basic-features/data-fetching/get-server-side-props.md similarity index 97% rename from docs/basic-features/data-fetching/getServerSideProps.md rename to docs/basic-features/data-fetching/get-server-side-props.md index 92714fb469944..a49848fb092e1 100644 --- a/docs/basic-features/data-fetching/getServerSideProps.md +++ b/docs/basic-features/data-fetching/get-server-side-props.md @@ -29,7 +29,7 @@ You can use the [next-code-elimination tool](https://next-code-elimination.verce Note that you must export `getServerSideProps` as a standalone function — it will **not** work if you add `getServerSideProps` as a property of the page component. -The [`getServerSideProps` API reference](/docs/api-reference/data-fetching/getServerSideProps.md) covers all parameters and props that can be used with `getServerSideProps`. +The [`getServerSideProps` API reference](/docs/api-reference/data-fetching/get-server-side-props.md) covers all parameters and props that can be used with `getServerSideProps`. ## When should I use `getServerSideProps`? diff --git a/docs/basic-features/data-fetching/getStaticPaths.md b/docs/basic-features/data-fetching/getStaticPaths.md index b4ddfe861f69a..ac70793844eb4 100644 --- a/docs/basic-features/data-fetching/getStaticPaths.md +++ b/docs/basic-features/data-fetching/getStaticPaths.md @@ -19,7 +19,7 @@ export async function getStaticPaths() { } ``` -Note that`getStaticProps` **must** be used with `getStaticPaths`, and that you **cannot** use it with [`getServerSideProps`](/docs/basic-features/data-fetching/getServerSideProps.md). +Note that`getStaticProps` **must** be used with `getStaticPaths`, and that you **cannot** use it with [`getServerSideProps`](/docs/basic-features/data-fetching/get-server-side-props.md). The [`getStaticPaths` API reference](/docs/api-reference/data-fetching/getStaticPaths.md) covers all parameters and props that can be used with `getStaticPaths`. diff --git a/docs/basic-features/data-fetching/index.md b/docs/basic-features/data-fetching/index.md index af201869a58bc..0273b713df64a 100644 --- a/docs/basic-features/data-fetching/index.md +++ b/docs/basic-features/data-fetching/index.md @@ -36,7 +36,7 @@ Data fetching in Next.js allows you to render your content in different ways, de </div> <div class="card"> - <a href="/docs/basic-features/data-fetching/getServerSideProps.md"> + <a href="/docs/basic-features/data-fetching/get-server-side-props.md"> <b>SSR: Server-side rendering</b> <small>Learn more about server-side rendering in Next.js with getServerSideProps.</small> </a> diff --git a/docs/basic-features/pages.md b/docs/basic-features/pages.md index 775efb9304c4a..1559eb7d70278 100644 --- a/docs/basic-features/pages.md +++ b/docs/basic-features/pages.md @@ -248,7 +248,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/getServerSideProps.md) +To learn more about how `getServerSideProps` works, check out our [Data Fetching documentation](/docs/basic-features/data-fetching/get-server-side-props.md) ## Summary diff --git a/docs/basic-features/typescript.md b/docs/basic-features/typescript.md index 3290a8477063d..f56028f7fe5f5 100644 --- a/docs/basic-features/typescript.md +++ b/docs/basic-features/typescript.md @@ -85,7 +85,7 @@ export const getServerSideProps: GetServerSideProps = async (context) => { } ``` -> If you're using `getInitialProps`, you can [follow the directions on this page](/docs/api-reference/data-fetching/getInitialProps.md#typescript). +> If you're using `getInitialProps`, you can [follow the directions on this page](/docs/api-reference/data-fetching/get-initial-props.md#typescript). ## API Routes diff --git a/docs/manifest.json b/docs/manifest.json index 70d7eb91d0e50..335b44c918429 100644 --- a/docs/manifest.json +++ b/docs/manifest.json @@ -23,7 +23,7 @@ }, { "title": "getServerSideProps", - "path": "/docs/basic-features/data-fetching/getServerSideProps.md" + "path": "/docs/basic-features/data-fetching/get-server-side-props.md" }, { "title": "getStaticPaths", @@ -347,11 +347,11 @@ "routes": [ { "title": "getInitialProps", - "path": "/docs/api-reference/data-fetching/getInitialProps.md" + "path": "/docs/api-reference/data-fetching/get-initial-props.md" }, { "title": "getServerSideProps", - "path": "/docs/api-reference/data-fetching/getServerSideProps.md" + "path": "/docs/api-reference/data-fetching/get-server-side-props.md" }, { "title": "getStaticPaths", diff --git a/docs/routing/shallow-routing.md b/docs/routing/shallow-routing.md index 377597282d1bc..dee76b81b2139 100644 --- a/docs/routing/shallow-routing.md +++ b/docs/routing/shallow-routing.md @@ -11,7 +11,7 @@ description: You can use shallow routing to change the URL without triggering a </ul> </details> -Shallow routing allows you to change the URL without running data fetching methods again, that includes [`getServerSideProps`](/docs/basic-features/data-fetching/getServerSideProps.md), [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md), and [`getInitialProps`](/docs/api-reference/data-fetching/getInitialProps.md). +Shallow routing allows you to change the URL without running data fetching methods again, that includes [`getServerSideProps`](/docs/basic-features/data-fetching/get-server-side-props.md), [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md), and [`getInitialProps`](/docs/api-reference/data-fetching/get-initial-props.md). You'll receive the updated `pathname` and the `query` via the [`router` object](/docs/api-reference/next/router.md#router-object) (added by [`useRouter`](/docs/api-reference/next/router.md#useRouter) or [`withRouter`](/docs/api-reference/next/router.md#withRouter)), without losing state. diff --git a/errors/get-initial-props-as-an-instance-method.md b/errors/get-initial-props-as-an-instance-method.md index 26218c66e28eb..805055202f40c 100644 --- a/errors/get-initial-props-as-an-instance-method.md +++ b/errors/get-initial-props-as-an-instance-method.md @@ -36,4 +36,4 @@ export default YourEntryComponent ### Useful Links -- [Fetching data and component lifecycle](https://nextjs.org/docs/api-reference/data-fetching/getInitialProps) +- [Fetching data and component lifecycle](https://nextjs.org/docs/api-reference/data-fetching/get-initial-props) diff --git a/examples/blog/pages/posts/pages.md b/examples/blog/pages/posts/pages.md index b719fd7afe2b9..d5394296b3b96 100644 --- a/examples/blog/pages/posts/pages.md +++ b/examples/blog/pages/posts/pages.md @@ -228,7 +228,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/getServerSideProps.md) +To learn more about how `getServerSideProps` works, check out our [Data Fetching documentation](/docs/basic-features/data-fetching/get-server-side-props.md) ## Summary From 93ff21982a337fa33ae712df2f60a9d5f82703e3 Mon Sep 17 00:00:00 2001 From: molebox <hello@richardhaines.dev> Date: Mon, 20 Dec 2021 14:14:42 +0100 Subject: [PATCH 68/70] Changed path of getStaticPaths to kebab-case --- docs/advanced-features/i18n-routing.md | 2 +- docs/advanced-features/static-html-export.md | 6 +++--- .../{getStaticPaths.md => get-static-paths.md} | 0 docs/api-reference/data-fetching/getStaticProps.md | 2 +- docs/api-reference/next/router.md | 2 +- docs/basic-features/data-fetching/getStaticPaths.md | 2 +- docs/basic-features/data-fetching/index.md | 2 +- docs/basic-features/pages.md | 2 +- docs/manifest.json | 4 ++-- docs/migrating/from-create-react-app.md | 2 +- docs/migrating/from-gatsby.md | 2 +- examples/blog/pages/posts/pages.md | 2 +- 12 files changed, 14 insertions(+), 14 deletions(-) rename docs/api-reference/data-fetching/{getStaticPaths.md => get-static-paths.md} (100%) diff --git a/docs/advanced-features/i18n-routing.md b/docs/advanced-features/i18n-routing.md index 2f9e8d77b348c..901f7496142f9 100644 --- a/docs/advanced-features/i18n-routing.md +++ b/docs/advanced-features/i18n-routing.md @@ -293,7 +293,7 @@ Next.js doesn't know about variants of a page so it's up to you to add the `href ### Dynamic Routes and `getStaticProps` Pages -For pages using `getStaticProps` with [Dynamic Routes](/docs/routing/dynamic-routes.md), all locale variants of the page desired to be prerendered need to be returned from [`getStaticPaths`](/docs/basic-features/data-fetching/getStaticPaths.md). Along with the `params` object returned for `paths`, you can also return a `locale` field specifying which locale you want to render. For example: +For pages using `getStaticProps` with [Dynamic Routes](/docs/routing/dynamic-routes.md), all locale variants of the page desired to be prerendered need to be returned from [`getStaticPaths`](/docs/basic-features/data-fetching/get-static-paths.md). Along with the `params` object returned for `paths`, you can also return a `locale` field specifying which locale you want to render. For example: ```js // pages/blog/[slug].js diff --git a/docs/advanced-features/static-html-export.md b/docs/advanced-features/static-html-export.md index 37546e0a12592..e0a0690e76e6c 100644 --- a/docs/advanced-features/static-html-export.md +++ b/docs/advanced-features/static-html-export.md @@ -27,7 +27,7 @@ Update your build script in `package.json` to use `next export`: Running `npm run build` will generate an `out` directory. -`next export` builds an HTML version of your app. During `next build`, [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) and [`getStaticPaths`](/docs/basic-features/data-fetching/getStaticPaths.md) will generate an HTML file for each page in your `pages` directory (or more for [dynamic routes](/docs/routing/dynamic-routes.md). Then, `next export` will copy the already exported files into the correct directory. `getInitialProps` will generate the HTML files during `next export` instead of `next build`. +`next export` builds an HTML version of your app. During `next build`, [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) and [`getStaticPaths`](/docs/basic-features/data-fetching/get-static-paths.md) will generate an HTML file for each page in your `pages` directory (or more for [dynamic routes](/docs/routing/dynamic-routes.md). Then, `next export` will copy the already exported files into the correct directory. `getInitialProps` will generate the HTML files during `next export` instead of `next build`. For more advanced scenarios, you can define a parameter called [`exportPathMap`](/docs/api-reference/next.config.js/exportPathMap.md) in your [`next.config.js`](/docs/api-reference/next.config.js/introduction.md) file to configure exactly which pages will be generated. @@ -42,7 +42,7 @@ The majority of core Next.js features needed to build a static site are supporte - Any styling options (e.g. CSS Modules, styled-jsx) - [Client-side data fetching](/docs/basic-features/data-fetching/client-side.md) - [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) -- [`getStaticPaths`](/docs/basic-features/data-fetching/getStaticPaths.md) +- [`getStaticPaths`](/docs/basic-features/data-fetching/get-static-paths.md) - [Image Optimization](/docs/basic-features/image-optimization.md) using a [custom loader](/docs/basic-features/image-optimization.md#loader) ## Unsupported Features @@ -57,7 +57,7 @@ Features that require a Node.js server, or dynamic logic that cannot be computed - [Headers](/docs/api-reference/next.config.js/headers.md) - [Middleware](/docs/middleware.md) - [Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration.md) -- [`fallback: true`](/docs/api-reference/data-fetching/getStaticPaths.md#fallback-true) +- [`fallback: true`](/docs/api-reference/data-fetching/get-static-paths.md#fallback-true) - [`getServerSideProps`](/docs/basic-features/data-fetching/get-server-side-props.md) ### `getInitialProps` diff --git a/docs/api-reference/data-fetching/getStaticPaths.md b/docs/api-reference/data-fetching/get-static-paths.md similarity index 100% rename from docs/api-reference/data-fetching/getStaticPaths.md rename to docs/api-reference/data-fetching/get-static-paths.md diff --git a/docs/api-reference/data-fetching/getStaticProps.md b/docs/api-reference/data-fetching/getStaticProps.md index c737a59006ed1..2ab5ddb9f2625 100644 --- a/docs/api-reference/data-fetching/getStaticProps.md +++ b/docs/api-reference/data-fetching/getStaticProps.md @@ -102,7 +102,7 @@ export async function getStaticProps(context) { } ``` -> **Note**: `notFound` is not needed for [`fallback: false`](/docs/api-reference/data-fetching/getStaticPaths#fallback-false) mode as only paths returned from `getStaticPaths` will be pre-rendered. +> **Note**: `notFound` is not needed for [`fallback: false`](/docs/api-reference/data-fetching/get-static-paths#fallback-false) mode as only paths returned from `getStaticPaths` will be pre-rendered. ### `redirect` diff --git a/docs/api-reference/next/router.md b/docs/api-reference/next/router.md index 27301660c6855..451e938043641 100644 --- a/docs/api-reference/next/router.md +++ b/docs/api-reference/next/router.md @@ -44,7 +44,7 @@ The following is the definition of the `router` object returned by both [`useRou - `pathname`: `String` - Current route. That is the path of the page in `/pages`, the configured `basePath` or `locale` is not included. - `query`: `Object` - The query string parsed to an object. It will be an empty object during prerendering if the page doesn't have [data fetching requirements](/docs/basic-features/data-fetching/index.md). Defaults to `{}` - `asPath`: `String` - The path (including the query) shown in the browser without the configured `basePath` or `locale`. -- `isFallback`: `boolean` - Whether the current page is in [fallback mode](/docs/api-reference/data-fetching/getStaticPaths.md#fallback-pages). +- `isFallback`: `boolean` - Whether the current page is in [fallback mode](/docs/api-reference/data-fetching/get-static-paths.md#fallback-pages). - `basePath`: `String` - The active [basePath](/docs/api-reference/next.config.js/basepath.md) (if enabled). - `locale`: `String` - The active locale (if enabled). - `locales`: `String[]` - All supported locales (if enabled). diff --git a/docs/basic-features/data-fetching/getStaticPaths.md b/docs/basic-features/data-fetching/getStaticPaths.md index ac70793844eb4..9ba7a450928f9 100644 --- a/docs/basic-features/data-fetching/getStaticPaths.md +++ b/docs/basic-features/data-fetching/getStaticPaths.md @@ -21,7 +21,7 @@ export async function getStaticPaths() { Note that`getStaticProps` **must** be used with `getStaticPaths`, and that you **cannot** use it with [`getServerSideProps`](/docs/basic-features/data-fetching/get-server-side-props.md). -The [`getStaticPaths` API reference](/docs/api-reference/data-fetching/getStaticPaths.md) covers all parameters and props that can be used with `getStaticPaths`. +The [`getStaticPaths` API reference](/docs/api-reference/data-fetching/get-static-paths.md) covers all parameters and props that can be used with `getStaticPaths`. ## When should I use `getStaticPaths`? diff --git a/docs/basic-features/data-fetching/index.md b/docs/basic-features/data-fetching/index.md index 0273b713df64a..e0345c5c31452 100644 --- a/docs/basic-features/data-fetching/index.md +++ b/docs/basic-features/data-fetching/index.md @@ -50,7 +50,7 @@ Data fetching in Next.js allows you to render your content in different ways, de </div> <div class="card"> - <a href="/docs/basic-features/data-fetching/getStaticPaths.md"> + <a href="/docs/basic-features/data-fetching/get-static-paths.md"> <b>Dynamic routing</b> <small>Learn more about dynamic routing in Next.js with getStaticPaths.</small> </a> diff --git a/docs/basic-features/pages.md b/docs/basic-features/pages.md index 1559eb7d70278..c04c93f70f069 100644 --- a/docs/basic-features/pages.md +++ b/docs/basic-features/pages.md @@ -196,7 +196,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/getStaticPaths.md). +To learn more about how `getStaticPaths` works, check out the [Data Fetching documentation](/docs/basic-features/data-fetching/get-static-paths.md). ### When should I use Static Generation? diff --git a/docs/manifest.json b/docs/manifest.json index 335b44c918429..984c06d5a7006 100644 --- a/docs/manifest.json +++ b/docs/manifest.json @@ -27,7 +27,7 @@ }, { "title": "getStaticPaths", - "path": "/docs/basic-features/data-fetching/getStaticPaths.md" + "path": "/docs/basic-features/data-fetching/get-static-paths.md" }, { "title": "getStaticProps", @@ -355,7 +355,7 @@ }, { "title": "getStaticPaths", - "path": "/docs/api-reference/data-fetching/getStaticPaths.md" + "path": "/docs/api-reference/data-fetching/get-static-paths.md" }, { "title": "getStaticProps", diff --git a/docs/migrating/from-create-react-app.md b/docs/migrating/from-create-react-app.md index 974fe75931cdd..77697644ec1c4 100644 --- a/docs/migrating/from-create-react-app.md +++ b/docs/migrating/from-create-react-app.md @@ -51,7 +51,7 @@ Create React App uses the `public` directory for the [entry HTML file](https://c With Create React App, you're likely using React Router. Instead of using a third-party library, Next.js includes its own [file-system based routing](/docs/routing/introduction.md). - Convert all `Route` components to new files in the `pages` directory. -- For routes that require dynamic content (e.g. `/blog/:slug`), you can use [Dynamic Routes](/docs/routing/dynamic-routes.md) with Next.js (e.g. `pages/blog/[slug].js`). The value of `slug` is accessible through a [query parameter](/docs/routing/dynamic-routes.md). For example, the route `/blog/first-post` would forward the query object `{ 'slug': 'first-post' }` to `pages/blog/[slug].js` ([learn more here](/docs/basic-features/data-fetching/getStaticPaths.md)). +- For routes that require dynamic content (e.g. `/blog/:slug`), you can use [Dynamic Routes](/docs/routing/dynamic-routes.md) with Next.js (e.g. `pages/blog/[slug].js`). The value of `slug` is accessible through a [query parameter](/docs/routing/dynamic-routes.md). For example, the route `/blog/first-post` would forward the query object `{ 'slug': 'first-post' }` to `pages/blog/[slug].js` ([learn more here](/docs/basic-features/data-fetching/get-static-paths.md)). For more information, see [Migrating from React Router](/docs/migrating/from-react-router.md). diff --git a/docs/migrating/from-gatsby.md b/docs/migrating/from-gatsby.md index 26fee4bc1726b..fa46c9819c22b 100644 --- a/docs/migrating/from-gatsby.md +++ b/docs/migrating/from-gatsby.md @@ -52,7 +52,7 @@ Both Gatsby and Next support a `pages` directory, which uses [file-system based Gatsby creates dynamic routes using the `createPages` API inside of `gatsby-node.js`. With Next, we can use [Dynamic Routes](/docs/routing/dynamic-routes.md) inside of `pages` to achieve the same effect. Rather than having a `template` directory, you can use the React component inside your dynamic route file. For example: - **Gatsby:** `createPages` API inside `gatsby-node.js` for each blog post, then have a template file at `src/templates/blog-post.js`. -- **Next:** Create `pages/blog/[slug].js` which contains the blog post template. The value of `slug` is accessible through a [query parameter](/docs/routing/dynamic-routes.md). For example, the route `/blog/first-post` would forward the query object `{ 'slug': 'first-post' }` to `pages/blog/[slug].js` ([learn more here](/docs/basic-features/data-fetching/getStaticPaths.md)). +- **Next:** Create `pages/blog/[slug].js` which contains the blog post template. The value of `slug` is accessible through a [query parameter](/docs/routing/dynamic-routes.md). For example, the route `/blog/first-post` would forward the query object `{ 'slug': 'first-post' }` to `pages/blog/[slug].js` ([learn more here](/docs/basic-features/data-fetching/get-static-paths.md)). ## Styling diff --git a/examples/blog/pages/posts/pages.md b/examples/blog/pages/posts/pages.md index d5394296b3b96..442d11c3e425a 100644 --- a/examples/blog/pages/posts/pages.md +++ b/examples/blog/pages/posts/pages.md @@ -176,7 +176,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/getStaticPaths.md). +To learn more about how `getStaticPaths` works, check out the [Data Fetching documentation](/docs/basic-features/data-fetching/get-static-paths.md). ### When should I use Static Generation? From ceea662cf9edeb5a517f6a4156cb526d95ff4b4f Mon Sep 17 00:00:00 2001 From: molebox <hello@richardhaines.dev> Date: Mon, 20 Dec 2021 14:18:02 +0100 Subject: [PATCH 69/70] Chnaged path of getStaticProps to kebab-case --- docs/advanced-features/automatic-static-optimization.md | 4 ++-- docs/advanced-features/custom-app.md | 4 ++-- docs/advanced-features/custom-document.md | 2 +- docs/advanced-features/custom-error-page.md | 4 ++-- docs/advanced-features/i18n-routing.md | 2 +- docs/advanced-features/static-html-export.md | 4 ++-- docs/api-reference/data-fetching/get-initial-props.md | 2 +- docs/api-reference/data-fetching/get-static-paths.md | 2 +- .../data-fetching/{getStaticProps.md => get-static-props.md} | 0 docs/api-reference/next.config.js/redirects.md | 2 +- docs/api-reference/next.config.js/rewrites.md | 2 +- docs/api-reference/next/link.md | 4 ++-- docs/api-reference/next/router.md | 2 +- docs/basic-features/data-fetching/get-server-side-props.md | 2 +- .../data-fetching/{getStaticPaths.md => get-static-paths.md} | 0 .../data-fetching/{getStaticProps.md => get-static-props.md} | 2 +- docs/basic-features/data-fetching/index.md | 2 +- docs/basic-features/environment-variables.md | 2 +- docs/basic-features/pages.md | 2 +- docs/going-to-production.md | 2 +- docs/manifest.json | 4 ++-- docs/routing/introduction.md | 2 +- docs/routing/shallow-routing.md | 2 +- examples/blog/pages/posts/pages.md | 2 +- 24 files changed, 28 insertions(+), 28 deletions(-) rename docs/api-reference/data-fetching/{getStaticProps.md => get-static-props.md} (100%) rename docs/basic-features/data-fetching/{getStaticPaths.md => get-static-paths.md} (100%) rename docs/basic-features/data-fetching/{getStaticProps.md => get-static-props.md} (98%) diff --git a/docs/advanced-features/automatic-static-optimization.md b/docs/advanced-features/automatic-static-optimization.md index a7c910bf9ed61..abf202aacbd67 100644 --- a/docs/advanced-features/automatic-static-optimization.md +++ b/docs/advanced-features/automatic-static-optimization.md @@ -20,7 +20,7 @@ If the above is not the case, Next.js will **statically optimize** your page aut During prerendering, the router's `query` object will be empty since we do not have `query` information to provide during this phase. After hydration, Next.js will trigger an update to your application to provide the route parameters in the `query` object. -> **Note:** Parameters added with [dynamic routes](/docs/routing/dynamic-routes.md) to a page that's using [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) will always be available inside the `query` object. +> **Note:** Parameters added with [dynamic routes](/docs/routing/dynamic-routes.md) to a page that's using [`getStaticProps`](/docs/basic-features/data-fetching/get-static-props.md) will always be available inside the `query` object. `next build` will emit `.html` files for statically optimized pages. For example, the result for the page `pages/about.js` would be: @@ -36,5 +36,5 @@ And if you add `getServerSideProps` to the page, it will then be JavaScript, lik ## Caveats -- If you have a [custom `App`](/docs/advanced-features/custom-app.md) with `getInitialProps` then this optimization will be turned off in pages without [Static Generation](/docs/basic-features/data-fetching/getStaticProps.md). +- If you have a [custom `App`](/docs/advanced-features/custom-app.md) with `getInitialProps` then this optimization will be turned off in pages without [Static Generation](/docs/basic-features/data-fetching/get-static-props.md). - If you have a [custom `Document`](/docs/advanced-features/custom-document.md) with `getInitialProps` be sure you check if `ctx.req` is defined before assuming the page is server-side rendered. `ctx.req` will be `undefined` for pages that are prerendered. diff --git a/docs/advanced-features/custom-app.md b/docs/advanced-features/custom-app.md index b436569f1272f..73d65f5666a97 100644 --- a/docs/advanced-features/custom-app.md +++ b/docs/advanced-features/custom-app.md @@ -43,9 +43,9 @@ The `Component` prop is the active `page`, so whenever you navigate between rout ### Caveats - If your app is running and you added a custom `App`, you'll need to restart the development server. Only required if `pages/_app.js` didn't exist before. -- Adding a custom [`getInitialProps`](/docs/api-reference/data-fetching/get-initial-props.md) in your `App` will disable [Automatic Static Optimization](/docs/advanced-features/automatic-static-optimization.md) in pages without [Static Generation](/docs/basic-features/data-fetching/getStaticProps.md). +- Adding a custom [`getInitialProps`](/docs/api-reference/data-fetching/get-initial-props.md) in your `App` will disable [Automatic Static Optimization](/docs/advanced-features/automatic-static-optimization.md) in pages without [Static Generation](/docs/basic-features/data-fetching/get-static-props.md). - When you add `getInitialProps` in your custom app, you must `import App from "next/app"`, call `App.getInitialProps(appContext)` inside `getInitialProps` and merge the returned object into the return value. -- `App` currently does not support Next.js [Data Fetching methods](/docs/basic-features/data-fetching/index.md) like [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) or [`getServerSideProps`](/docs/basic-features/data-fetching/get-server-side-props.md). +- `App` currently does not support Next.js [Data Fetching methods](/docs/basic-features/data-fetching/index.md) like [`getStaticProps`](/docs/basic-features/data-fetching/get-static-props.md) or [`getServerSideProps`](/docs/basic-features/data-fetching/get-server-side-props.md). ### TypeScript diff --git a/docs/advanced-features/custom-document.md b/docs/advanced-features/custom-document.md index a726b09d62d60..3ec0e856bee7b 100644 --- a/docs/advanced-features/custom-document.md +++ b/docs/advanced-features/custom-document.md @@ -54,7 +54,7 @@ The `ctx` object is equivalent to the one received in [`getInitialProps`](/docs/ - `Document` is only rendered in the server, event handlers like `onClick` won't work. - React components outside of `<Main />` will not be initialized by the browser. Do _not_ add application logic here or custom CSS (like `styled-jsx`). If you need shared components in all your pages (like a menu or a toolbar), take a look at the [`App`](/docs/advanced-features/custom-app.md) component instead. - `Document`'s `getInitialProps` function is not called during client-side transitions, nor when a page is [statically optimized](/docs/advanced-features/automatic-static-optimization.md). -- `Document` currently does not support Next.js [Data Fetching methods](/docs/basic-features/data-fetching/index.md) like [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) or [`getServerSideProps`](/docs/basic-features/data-fetching/get-server-side-props.md). +- `Document` currently does not support Next.js [Data Fetching methods](/docs/basic-features/data-fetching/index.md) like [`getStaticProps`](/docs/basic-features/data-fetching/get-static-props.md) or [`getServerSideProps`](/docs/basic-features/data-fetching/get-server-side-props.md). ## Customizing `renderPage` diff --git a/docs/advanced-features/custom-error-page.md b/docs/advanced-features/custom-error-page.md index 7f306e9d262e5..c7cc7b9ffd10d 100644 --- a/docs/advanced-features/custom-error-page.md +++ b/docs/advanced-features/custom-error-page.md @@ -21,7 +21,7 @@ export default function Custom404() { } ``` -> **Note**: You can use [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) inside this page if you need to fetch data at build time. +> **Note**: You can use [`getStaticProps`](/docs/basic-features/data-fetching/get-static-props.md) inside this page if you need to fetch data at build time. ## 500 Page @@ -38,7 +38,7 @@ export default function Custom500() { } ``` -> **Note**: You can use [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) inside this page if you need to fetch data at build time. +> **Note**: You can use [`getStaticProps`](/docs/basic-features/data-fetching/get-static-props.md) inside this page if you need to fetch data at build time. ### More Advanced Error Page Customizing diff --git a/docs/advanced-features/i18n-routing.md b/docs/advanced-features/i18n-routing.md index 901f7496142f9..6eb849294e063 100644 --- a/docs/advanced-features/i18n-routing.md +++ b/docs/advanced-features/i18n-routing.md @@ -207,7 +207,7 @@ You can access the locale information via the Next.js router. For example, using - `locales` contains all configured locales. - `defaultLocale` contains the configured default locale. -When [pre-rendering](/docs/basic-features/pages.md#static-generation-recommended) pages with `getStaticProps` or `getServerSideProps`, the locale information is provided in [the context](/docs/basic-features/data-fetching/getStaticProps.md) provided to the function. +When [pre-rendering](/docs/basic-features/pages.md#static-generation-recommended) pages with `getStaticProps` or `getServerSideProps`, the locale information is provided in [the context](/docs/basic-features/data-fetching/get-static-props.md) provided to the function. When leveraging `getStaticPaths`, the configured locales are provided in the context parameter of the function under `locales` and the configured defaultLocale under `defaultLocale`. diff --git a/docs/advanced-features/static-html-export.md b/docs/advanced-features/static-html-export.md index e0a0690e76e6c..6408adf0b7c68 100644 --- a/docs/advanced-features/static-html-export.md +++ b/docs/advanced-features/static-html-export.md @@ -27,7 +27,7 @@ Update your build script in `package.json` to use `next export`: Running `npm run build` will generate an `out` directory. -`next export` builds an HTML version of your app. During `next build`, [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) and [`getStaticPaths`](/docs/basic-features/data-fetching/get-static-paths.md) will generate an HTML file for each page in your `pages` directory (or more for [dynamic routes](/docs/routing/dynamic-routes.md). Then, `next export` will copy the already exported files into the correct directory. `getInitialProps` will generate the HTML files during `next export` instead of `next build`. +`next export` builds an HTML version of your app. During `next build`, [`getStaticProps`](/docs/basic-features/data-fetching/get-static-props.md) and [`getStaticPaths`](/docs/basic-features/data-fetching/get-static-paths.md) will generate an HTML file for each page in your `pages` directory (or more for [dynamic routes](/docs/routing/dynamic-routes.md). Then, `next export` will copy the already exported files into the correct directory. `getInitialProps` will generate the HTML files during `next export` instead of `next build`. For more advanced scenarios, you can define a parameter called [`exportPathMap`](/docs/api-reference/next.config.js/exportPathMap.md) in your [`next.config.js`](/docs/api-reference/next.config.js/introduction.md) file to configure exactly which pages will be generated. @@ -41,7 +41,7 @@ The majority of core Next.js features needed to build a static site are supporte - [Dynamic Imports](/docs/advanced-features/dynamic-import.md) - Any styling options (e.g. CSS Modules, styled-jsx) - [Client-side data fetching](/docs/basic-features/data-fetching/client-side.md) -- [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) +- [`getStaticProps`](/docs/basic-features/data-fetching/get-static-props.md) - [`getStaticPaths`](/docs/basic-features/data-fetching/get-static-paths.md) - [Image Optimization](/docs/basic-features/image-optimization.md) using a [custom loader](/docs/basic-features/image-optimization.md#loader) diff --git a/docs/api-reference/data-fetching/get-initial-props.md b/docs/api-reference/data-fetching/get-initial-props.md index a9deb90e17128..f8295dbda52c2 100644 --- a/docs/api-reference/data-fetching/get-initial-props.md +++ b/docs/api-reference/data-fetching/get-initial-props.md @@ -4,7 +4,7 @@ description: Enable Server-Side Rendering in a page and do initial data populati # getInitialProps -**Recommended: [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) or [`getServerSideProps`](/docs/basic-features/data-fetching/get-server-side-props.md)** instead of `getInitialProps`. These data fetching methods allow you to have a granular choice between static generation and server-side rendering. +**Recommended: [`getStaticProps`](/docs/basic-features/data-fetching/get-static-props.md) or [`getServerSideProps`](/docs/basic-features/data-fetching/get-server-side-props.md)** instead of `getInitialProps`. These data fetching methods allow you to have a granular choice between static generation and server-side rendering. `getInitialProps` enables [server-side rendering](/docs/basic-features/pages.md#server-side-rendering) in a page and allows you to do **initial data population**, it means sending the [page](/docs/basic-features/pages.md) with the data already populated from the server. This is especially useful for [SEO](https://en.wikipedia.org/wiki/Search_engine_optimization). diff --git a/docs/api-reference/data-fetching/get-static-paths.md b/docs/api-reference/data-fetching/get-static-paths.md index ebefdffbab47e..d185922fae93d 100644 --- a/docs/api-reference/data-fetching/get-static-paths.md +++ b/docs/api-reference/data-fetching/get-static-paths.md @@ -59,7 +59,7 @@ If `fallback` is `false`, then any paths not returned by `getStaticPaths` will r When `next build` is run, Next.js will check if `getStaticPaths` returned `fallback: false`, it will then build **only** the paths returned by `getStaticPaths`. This option is useful if you have a small number of paths to create, or new page data is not added often. If you find that you need to add more paths, and you have `fallback: false`, you will need to run `next build` again so that the new paths can be generated. -The following example 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`](/docs/api-reference/data-fetching/getStaticProps.md). +The following example 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`](/docs/api-reference/data-fetching/get-static-props.md). ```jsx // pages/posts/[id].js diff --git a/docs/api-reference/data-fetching/getStaticProps.md b/docs/api-reference/data-fetching/get-static-props.md similarity index 100% rename from docs/api-reference/data-fetching/getStaticProps.md rename to docs/api-reference/data-fetching/get-static-props.md diff --git a/docs/api-reference/next.config.js/redirects.md b/docs/api-reference/next.config.js/redirects.md index b60af50241d82..15b370c420814 100644 --- a/docs/api-reference/next.config.js/redirects.md +++ b/docs/api-reference/next.config.js/redirects.md @@ -292,4 +292,4 @@ In some rare cases, you might need to assign a custom status code for older HTTP ## Other Redirects - Inside [API Routes](/docs/api-routes/response-helpers.md), you can use `res.redirect()`. -- Inside [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) and [`getServerSideProps`](/docs/basic-features/data-fetching/get-server-side-props.md), you can redirect specific pages at request-time. +- Inside [`getStaticProps`](/docs/basic-features/data-fetching/get-static-props.md) and [`getServerSideProps`](/docs/basic-features/data-fetching/get-server-side-props.md), you can redirect specific pages at request-time. diff --git a/docs/api-reference/next.config.js/rewrites.md b/docs/api-reference/next.config.js/rewrites.md index d49e4dec93e62..16ae2b533df85 100644 --- a/docs/api-reference/next.config.js/rewrites.md +++ b/docs/api-reference/next.config.js/rewrites.md @@ -148,7 +148,7 @@ module.exports = { } ``` -Note: for static pages from the [Automatic Static Optimization](/docs/advanced-features/automatic-static-optimization.md) or [prerendering](/docs/basic-features/data-fetching/getStaticProps.md) params from rewrites will be parsed on the client after hydration and provided in the query. +Note: for static pages from the [Automatic Static Optimization](/docs/advanced-features/automatic-static-optimization.md) or [prerendering](/docs/basic-features/data-fetching/get-static-props.md) params from rewrites will be parsed on the client after hydration and provided in the query. ## Path Matching diff --git a/docs/api-reference/next/link.md b/docs/api-reference/next/link.md index 0646b9a029eb1..b3357e433ca4d 100644 --- a/docs/api-reference/next/link.md +++ b/docs/api-reference/next/link.md @@ -57,10 +57,10 @@ export default Home - `href` - The path or URL to navigate to. This is the only required prop - `as` - Optional decorator for the path that will be shown in the browser URL bar. Before Next.js 9.5.3 this was used for dynamic routes, check our [previous docs](https://nextjs.org/docs/tag/v9.5.2/api-reference/next/link#dynamic-routes) to see how it worked. Note: when this path differs from the one provided in `href` the previous `href`/`as` behavior is used as shown in the [previous docs](https://nextjs.org/docs/tag/v9.5.2/api-reference/next/link#dynamic-routes). - [`passHref`](#if-the-child-is-a-custom-component-that-wraps-an-a-tag) - Forces `Link` to send the `href` property to its child. Defaults to `false` -- `prefetch` - Prefetch the page in the background. Defaults to `true`. Any `<Link />` that is in the viewport (initially or through scroll) will be preloaded. Prefetch can be disabled by passing `prefetch={false}`. When `prefetch` is set to `false`, prefetching will still occur on hover. Pages using [Static Generation](/docs/basic-features/data-fetching/getStaticProps.md) will preload `JSON` files with the data for faster page transitions. Prefetching is only enabled in production. +- `prefetch` - Prefetch the page in the background. Defaults to `true`. Any `<Link />` that is in the viewport (initially or through scroll) will be preloaded. Prefetch can be disabled by passing `prefetch={false}`. When `prefetch` is set to `false`, prefetching will still occur on hover. Pages using [Static Generation](/docs/basic-features/data-fetching/get-static-props.md) will preload `JSON` files with the data for faster page transitions. Prefetching is only enabled in production. - [`replace`](#replace-the-url-instead-of-push) - Replace the current `history` state instead of adding a new url into the stack. Defaults to `false` - [`scroll`](#disable-scrolling-to-the-top-of-the-page) - Scroll to the top of the page after a navigation. Defaults to `true` -- [`shallow`](/docs/routing/shallow-routing.md) - Update the path of the current page without rerunning [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md), [`getServerSideProps`](/docs/basic-features/data-fetching/get-server-side-props.md) or [`getInitialProps`](/docs/api-reference/data-fetching/get-initial-props.md). Defaults to `false` +- [`shallow`](/docs/routing/shallow-routing.md) - Update the path of the current page without rerunning [`getStaticProps`](/docs/basic-features/data-fetching/get-static-props.md), [`getServerSideProps`](/docs/basic-features/data-fetching/get-server-side-props.md) or [`getInitialProps`](/docs/api-reference/data-fetching/get-initial-props.md). Defaults to `false` - `locale` - The active locale is automatically prepended. `locale` allows for providing a different locale. When `false` `href` has to include the locale as the default behavior is disabled. ## If the route has dynamic segments diff --git a/docs/api-reference/next/router.md b/docs/api-reference/next/router.md index 451e938043641..d595c3ac54703 100644 --- a/docs/api-reference/next/router.md +++ b/docs/api-reference/next/router.md @@ -74,7 +74,7 @@ router.push(url, as, options) - `as`: `UrlObject | String` - Optional decorator for the path that will be shown in the browser URL bar. Before Next.js 9.5.3 this was used for dynamic routes, check our [previous docs](https://nextjs.org/docs/tag/v9.5.2/api-reference/next/link#dynamic-routes) to see how it worked. Note: when this path differs from the one provided in `href` the previous `href`/`as` behavior is used as shown in the [previous docs](https://nextjs.org/docs/tag/v9.5.2/api-reference/next/link#dynamic-routes) - `options` - Optional object with the following configuration options: - `scroll` - Optional boolean, controls scrolling to the top of the page after navigation. Defaults to `true` - - [`shallow`](/docs/routing/shallow-routing.md): Update the path of the current page without rerunning [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md), [`getServerSideProps`](/docs/basic-features/data-fetching/get-server-side-props.md) or [`getInitialProps`](/docs/api-reference/data-fetching/get-initial-props.md). Defaults to `false` + - [`shallow`](/docs/routing/shallow-routing.md): Update the path of the current page without rerunning [`getStaticProps`](/docs/basic-features/data-fetching/get-static-props.md), [`getServerSideProps`](/docs/basic-features/data-fetching/get-server-side-props.md) or [`getInitialProps`](/docs/api-reference/data-fetching/get-initial-props.md). Defaults to `false` - `locale` - Optional string, indicates locale of the new page > You don't need to use `router.push` for external URLs. [window.location](https://developer.mozilla.org/en-US/docs/Web/API/Window/location) is better suited for those cases. diff --git a/docs/basic-features/data-fetching/get-server-side-props.md b/docs/basic-features/data-fetching/get-server-side-props.md index a49848fb092e1..2e28a45cbb89d 100644 --- a/docs/basic-features/data-fetching/get-server-side-props.md +++ b/docs/basic-features/data-fetching/get-server-side-props.md @@ -33,7 +33,7 @@ The [`getServerSideProps` API reference](/docs/api-reference/data-fetching/get-s ## When should I use `getServerSideProps`? -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)](/learn/seo/web-performance) will be higher than [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) because the server must compute the result on every request, and the result can only be cached by a CDN using `cache-control` headers (which could require extra configuration). +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)](/learn/seo/web-performance) will be higher than [`getStaticProps`](/docs/basic-features/data-fetching/get-static-props.md) because the server must compute the result on every request, and the result can only be cached by a CDN using `cache-control` headers (which could require extra configuration). If you do not need to pre-render the data, then you should consider fetching data on the [client side](#fetching-data-on-the-client-side). diff --git a/docs/basic-features/data-fetching/getStaticPaths.md b/docs/basic-features/data-fetching/get-static-paths.md similarity index 100% rename from docs/basic-features/data-fetching/getStaticPaths.md rename to docs/basic-features/data-fetching/get-static-paths.md diff --git a/docs/basic-features/data-fetching/getStaticProps.md b/docs/basic-features/data-fetching/get-static-props.md similarity index 98% rename from docs/basic-features/data-fetching/getStaticProps.md rename to docs/basic-features/data-fetching/get-static-props.md index 5de3a33a881d4..adb8427fab01c 100644 --- a/docs/basic-features/data-fetching/getStaticProps.md +++ b/docs/basic-features/data-fetching/get-static-props.md @@ -62,7 +62,7 @@ export async function getStaticProps() { export default Blog ``` -The [`getStaticProps` API reference](/docs/api-reference/data-fetching/getStaticProps.md) covers all parameters and props that can be used with `getStaticProps`. +The [`getStaticProps` API reference](/docs/api-reference/data-fetching/get-static-props.md) covers all parameters and props that can be used with `getStaticProps`. ## Write server-side code directly diff --git a/docs/basic-features/data-fetching/index.md b/docs/basic-features/data-fetching/index.md index e0345c5c31452..4ac72d64bb7af 100644 --- a/docs/basic-features/data-fetching/index.md +++ b/docs/basic-features/data-fetching/index.md @@ -43,7 +43,7 @@ Data fetching in Next.js allows you to render your content in different ways, de </div> <div class="card"> - <a href="/docs/basic-features/data-fetching/getStaticProps.md"> + <a href="/docs/basic-features/data-fetching/get-static-props.md"> <b>SSG: Static-site generation</b> <small>Learn more about static site generation in Next.js with getStaticProps.</small> </a> diff --git a/docs/basic-features/environment-variables.md b/docs/basic-features/environment-variables.md index afceb8fd59cf3..1f6d1767971fc 100644 --- a/docs/basic-features/environment-variables.md +++ b/docs/basic-features/environment-variables.md @@ -32,7 +32,7 @@ DB_PASS=mypassword This loads `process.env.DB_HOST`, `process.env.DB_USER`, and `process.env.DB_PASS` into the Node.js environment automatically allowing you to use them in [Next.js data fetching methods](/docs/basic-features/data-fetching/index.md) and [API routes](/docs/api-routes/introduction.md). -For example, using [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md): +For example, using [`getStaticProps`](/docs/basic-features/data-fetching/get-static-props.md): ```js // pages/index.js diff --git a/docs/basic-features/pages.md b/docs/basic-features/pages.md index c04c93f70f069..ad46f39e5913a 100644 --- a/docs/basic-features/pages.md +++ b/docs/basic-features/pages.md @@ -137,7 +137,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.md). +To learn more about how `getStaticProps` works, check out the [Data Fetching documentation](/docs/basic-features/data-fetching/get-static-props.md). #### Scenario 2: Your page paths depend on external data diff --git a/docs/going-to-production.md b/docs/going-to-production.md index d8547627b5712..aa713bf04577c 100644 --- a/docs/going-to-production.md +++ b/docs/going-to-production.md @@ -38,7 +38,7 @@ Caching improves response times and reduces the number of requests to external s Cache-Control: public, max-age=31536000, immutable ``` -`Cache-Control` headers set in `next.config.js` will be overwritten in production to ensure that static assets can be cached effectively. If you need to revalidate the cache of a page that has been [statically generated](/docs/basic-features/pages.md#static-generation-recommended), you can do so by setting `revalidate` in the page's [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md) function. If you're using `next/image`, there are also [specific caching rules](/docs/basic-features/image-optimization.md#caching) for the default Image Optimization loader. +`Cache-Control` headers set in `next.config.js` will be overwritten in production to ensure that static assets can be cached effectively. If you need to revalidate the cache of a page that has been [statically generated](/docs/basic-features/pages.md#static-generation-recommended), you can do so by setting `revalidate` in the page's [`getStaticProps`](/docs/basic-features/data-fetching/get-static-props.md) function. If you're using `next/image`, there are also [specific caching rules](/docs/basic-features/image-optimization.md#caching) for the default Image Optimization loader. **Note:** When running your application locally with `next dev`, your headers are overwritten to prevent caching locally. diff --git a/docs/manifest.json b/docs/manifest.json index 984c06d5a7006..9e2534b1baa3d 100644 --- a/docs/manifest.json +++ b/docs/manifest.json @@ -31,7 +31,7 @@ }, { "title": "getStaticProps", - "path": "/docs/basic-features/data-fetching/getStaticProps.md" + "path": "/docs/basic-features/data-fetching/get-static-props.md" }, { "title": "Incremental Static Regeneration", @@ -359,7 +359,7 @@ }, { "title": "getStaticProps", - "path": "/docs/api-reference/data-fetching/getStaticProps.md" + "path": "/docs/api-reference/data-fetching/get-static-props.md" } ] }, diff --git a/docs/routing/introduction.md b/docs/routing/introduction.md index 6abb5b933d65a..6d165c22d6259 100644 --- a/docs/routing/introduction.md +++ b/docs/routing/introduction.md @@ -74,7 +74,7 @@ The example above uses multiple links. Each one maps a path (`href`) to a known - `/about` → `pages/about.js` - `/blog/hello-world` → `pages/blog/[slug].js` -Any `<Link />` in the viewport (initially or through scroll) will be prefetched by default (including the corresponding data) for pages using [Static Generation](/docs/basic-features/data-fetching/getStaticProps.md). The corresponding data for [server-rendered](https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering) routes is _not_ prefetched. +Any `<Link />` in the viewport (initially or through scroll) will be prefetched by default (including the corresponding data) for pages using [Static Generation](/docs/basic-features/data-fetching/get-static-props.md). The corresponding data for [server-rendered](https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering) routes is _not_ prefetched. ### Linking to dynamic paths diff --git a/docs/routing/shallow-routing.md b/docs/routing/shallow-routing.md index dee76b81b2139..d1703af6b6e1c 100644 --- a/docs/routing/shallow-routing.md +++ b/docs/routing/shallow-routing.md @@ -11,7 +11,7 @@ description: You can use shallow routing to change the URL without triggering a </ul> </details> -Shallow routing allows you to change the URL without running data fetching methods again, that includes [`getServerSideProps`](/docs/basic-features/data-fetching/get-server-side-props.md), [`getStaticProps`](/docs/basic-features/data-fetching/getStaticProps.md), and [`getInitialProps`](/docs/api-reference/data-fetching/get-initial-props.md). +Shallow routing allows you to change the URL without running data fetching methods again, that includes [`getServerSideProps`](/docs/basic-features/data-fetching/get-server-side-props.md), [`getStaticProps`](/docs/basic-features/data-fetching/get-static-props.md), and [`getInitialProps`](/docs/api-reference/data-fetching/get-initial-props.md). You'll receive the updated `pathname` and the `query` via the [`router` object](/docs/api-reference/next/router.md#router-object) (added by [`useRouter`](/docs/api-reference/next/router.md#useRouter) or [`withRouter`](/docs/api-reference/next/router.md#withRouter)), without losing state. diff --git a/examples/blog/pages/posts/pages.md b/examples/blog/pages/posts/pages.md index 442d11c3e425a..98d4c8333d218 100644 --- a/examples/blog/pages/posts/pages.md +++ b/examples/blog/pages/posts/pages.md @@ -117,7 +117,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.md). +To learn more about how `getStaticProps` works, check out the [Data Fetching documentation](/docs/basic-features/data-fetching/get-static-props.md). #### Scenario 2: Your page paths depend on external data From b6a659bc6422c180f33049e756951a117b421f4b Mon Sep 17 00:00:00 2001 From: molebox <hello@richardhaines.dev> Date: Mon, 20 Dec 2021 14:19:22 +0100 Subject: [PATCH 70/70] Moved card linking client-side lower in the list --- docs/basic-features/data-fetching/index.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/docs/basic-features/data-fetching/index.md b/docs/basic-features/data-fetching/index.md index 4ac72d64bb7af..d414515f11ad8 100644 --- a/docs/basic-features/data-fetching/index.md +++ b/docs/basic-features/data-fetching/index.md @@ -28,13 +28,6 @@ description: 'Data fetching in Next.js allows you to render your content in diff Data fetching in Next.js allows you to render your content in different ways, depending on your application's use case. These include pre-rendering with **Server-side Rendering** or **Static Generation**, and updating or creating content at runtime with **Incremental Static Regeneration**. -<div class="card"> - <a href="/docs/basic-features/data-fetching/client-side.md"> - <b>CSR: Client-side rendering</b> - <small>Learn more about client side rendering in Next.js with SWR.</small> - </a> -</div> - <div class="card"> <a href="/docs/basic-features/data-fetching/get-server-side-props.md"> <b>SSR: Server-side rendering</b> @@ -49,6 +42,13 @@ Data fetching in Next.js allows you to render your content in different ways, de </a> </div> +<div class="card"> + <a href="/docs/basic-features/data-fetching/client-side.md"> + <b>CSR: Client-side rendering</b> + <small>Learn more about client side rendering in Next.js with SWR.</small> + </a> +</div> + <div class="card"> <a href="/docs/basic-features/data-fetching/get-static-paths.md"> <b>Dynamic routing</b>