Skip to content

Commit 73b9201

Browse files
authored
Merge branch 'master' into chore/update-basic-features-script
2 parents 42f7fea + e27da30 commit 73b9201

16 files changed

+1330
-314
lines changed

.all-contributorsrc

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -407,6 +407,15 @@
407407
"contributions": [
408408
"translation"
409409
]
410+
},
411+
{
412+
"login": "TetsuyaNegishi",
413+
"name": "Tetsuya Negishi",
414+
"avatar_url": "https://avatars.githubusercontent.com/u/8405585?v=4",
415+
"profile": "https://github.com/TetsuyaNegishi",
416+
"contributions": [
417+
"translation"
418+
]
410419
}
411420
],
412421
"contributorsPerLine": 7,

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
<!-- textlint-enable -->
44

55
<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
6-
[![All Contributors](https://img.shields.io/badge/all_contributors-43-orange.svg?style=flat-square)](#contributors)
6+
[![All Contributors](https://img.shields.io/badge/all_contributors-44-orange.svg?style=flat-square)](#contributors)
77
<!-- ALL-CONTRIBUTORS-BADGE:END -->
88

99
![reviewdog](https://github.com/Nextjs-ja-translation/Nextjs-ja-translation-docs/workflows/reviewdog/badge.svg)
@@ -146,6 +146,7 @@ Thanks to these wonderful people ([emoji key](https://allcontributors.org/docs/e
146146
</tr>
147147
<tr>
148148
<td align="center"><a href="http://piyopanman.com"><img src="https://avatars.githubusercontent.com/u/66374097?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Piyopanman</b></sub></a><br /><a href="#translation-Piyopanman" title="Translation">🌍</a></td>
149+
<td align="center"><a href="https://github.com/TetsuyaNegishi"><img src="https://avatars.githubusercontent.com/u/8405585?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Tetsuya Negishi</b></sub></a><br /><a href="#translation-TetsuyaNegishi" title="Translation">🌍</a></td>
149150
</tr>
150151
</table>
151152

Lines changed: 78 additions & 172 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,10 @@
11
---
2-
description: API reference for `getStaticProps`. Learn how to use `getStaticProps` to generate static pages with Next.js.
2+
description: Fetch data and generate static pages with `getStaticProps`. Learn more about this API for data fetching in Next.js.
33
---
44

55
# getStaticProps
66

7-
<details>
8-
<summary><b>Version History</b></summary>
9-
10-
| Version | Changes |
11-
| --------- | ----------------------------------------------------------------------------------------------------------------- |
12-
| `v10.0.0` | `locale`, `locales`, `defaultLocale`, and `notFound` options added. |
13-
| `v9.5.0` | Stable [Incremental Static Regeneration](https://nextjs.org/blog/next-9-5#stable-incremental-static-regeneration) |
14-
| `v9.3.0` | `getStaticProps` introduced. |
15-
| `v10.0.0` | `fallback: 'blocking'` return option added. |
16-
17-
</details>
18-
19-
Exporting a function called `getStaticProps` will pre-render a page at build time using the props returned from the function:
7+
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`.
208

219
```jsx
2210
export async function getStaticProps(context) {
@@ -26,219 +14,137 @@ export async function getStaticProps(context) {
2614
}
2715
```
2816

29-
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.
17+
## When should I use getStaticProps?
3018

31-
## Context parameter
19+
You should use `getStaticProps` if:
3220

33-
The `context` parameter is an object containing the following keys:
21+
- The data required to render the page is available at build time ahead of a user’s request
22+
- The data comes from a headless CMS
23+
- The data can be publicly cached (not user-specific)
24+
- 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
3425

35-
- `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.
36-
- `preview` is `true` if the page is in the [Preview Mode](/docs/advanced-features/preview-mode.md) and `undefined` otherwise.
37-
- `previewData` contains the [preview](/docs/advanced-features/preview-mode.md) data set by `setPreviewData`.
38-
- `locale` contains the active locale (if enabled).
39-
- `locales` contains all supported locales (if enabled).
40-
- `defaultLocale` contains the configured default locale (if enabled).
26+
## When does getStaticProps run
4127

42-
## getStaticProps return values
28+
`getStaticProps` always runs on the server and never on the client. You can validate code written inside `getStaticProps` is removed from the client-side bundle [with this tool](https://next-code-elimination.vercel.app/).
4329

44-
The `getStaticProps` function should return an object containing either `props`, `redirect`, or `notFound` followed by an **optional** `revalidate` property.
30+
- `getStaticProps` always runs during `next build`
31+
- `getStaticProps` runs in the background when using `revalidate`
32+
- `getStaticProps` runs on-demand in the background when using [`unstable_revalidate`](/docs/basic-features/data-fetching/incremental-static-regeneration.md#on-demand-revalidation-beta)
4533

46-
### `props`
34+
When combined with [Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration.md), `getStaticProps` will run in the background while the stale page is being revalidated, and the fresh page served to the browser.
4735

48-
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).
36+
`getStaticProps` does not have access to the incoming request (such as query parameters or HTTP headers) as it generates static HTML. If you need access to the request for your page, consider using [Middleware](/docs/middleware.md) in addition to `getStaticProps`.
4937

50-
```jsx
51-
export async function getStaticProps(context) {
52-
return {
53-
props: { message: `Next.js is awesome` }, // will be passed to the page component as props
54-
}
55-
}
56-
```
38+
## Using getStaticProps to fetch data from a CMS
5739

58-
### `revalidate`
40+
The following example shows how you can fetch a list of blog posts from a CMS.
5941

60-
The `revalidate` property is the amount in seconds after which a page re-generation can occur (defaults to `false` or no revalidation).
42+
```jsx
43+
// posts will be populated at build time by getStaticProps()
44+
function Blog({ posts }) {
45+
return (
46+
<ul>
47+
{posts.map((post) => (
48+
<li>{post.title}</li>
49+
))}
50+
</ul>
51+
)
52+
}
6153

62-
```js
6354
// This function gets called at build time on server-side.
64-
// It may be called again, on a serverless function, if
65-
// revalidation is enabled and a new request comes in
55+
// It won't be called on client-side, so you can even do
56+
// direct database queries.
6657
export async function getStaticProps() {
58+
// Call an external API endpoint to get posts.
59+
// You can use any data fetching library
6760
const res = await fetch('https://.../posts')
6861
const posts = await res.json()
6962

63+
// By returning { props: { posts } }, the Blog component
64+
// will receive `posts` as a prop at build time
7065
return {
7166
props: {
7267
posts,
7368
},
74-
// Next.js will attempt to re-generate the page:
75-
// - When a request comes in
76-
// - At most once every 10 seconds
77-
revalidate: 10, // In seconds
78-
}
79-
}
80-
```
81-
82-
Learn more about [Incremental Static Regeneration](/docs/basic-features/data-fetching/incremental-static-regeneration.md)
83-
84-
### `notFound`
85-
86-
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.
87-
88-
```js
89-
export async function getStaticProps(context) {
90-
const res = await fetch(`https://.../data`)
91-
const data = await res.json()
92-
93-
if (!data) {
94-
return {
95-
notFound: true,
96-
}
97-
}
98-
99-
return {
100-
props: { data }, // will be passed to the page component as props
10169
}
10270
}
103-
```
104-
105-
> **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.
106-
107-
### `redirect`
108-
109-
The `redirect` object allows redirecting to internal or external resources. It should match the shape of `{ destination: string, permanent: boolean }`.
110-
111-
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`.
112-
113-
```js
114-
export async function getStaticProps(context) {
115-
const res = await fetch(`https://...`)
116-
const data = await res.json()
11771

118-
if (!data) {
119-
return {
120-
redirect: {
121-
destination: '/',
122-
permanent: false,
123-
// statusCode: 301
124-
},
125-
}
126-
}
127-
128-
return {
129-
props: { data }, // will be passed to the page component as props
130-
}
131-
}
72+
export default Blog
13273
```
13374

134-
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.
75+
The [`getStaticProps` API reference](/docs/api-reference/data-fetching/get-static-props.md) covers all parameters and props that can be used with `getStaticProps`.
13576

136-
## Reading files: Use `process.cwd()`
77+
## Write server-side code directly
13778

138-
Files can be read directly from the filesystem in `getStaticProps`.
79+
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.
13980

140-
In order to do so you have to get the full path to a file.
81+
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`.
14182

142-
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.
143-
144-
Instead you can use `process.cwd()` which gives you the directory where Next.js is being executed.
83+
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 shared by using a `lib/` directory. Then it can be shared with `getStaticProps`.
14584

14685
```jsx
147-
import { promises as fs } from 'fs'
148-
import path from 'path'
86+
// lib/fetch-posts.js
87+
88+
// The following function is shared
89+
// with getStaticProps and API routes
90+
// from a `lib/` directory
91+
export async function loadPosts() {
92+
// Call an external API endpoint to get posts
93+
const res = await fetch('https://.../posts/')
94+
const data = await res.json()
14995

150-
// posts will be populated at build time by getStaticProps()
151-
function Blog({ posts }) {
152-
return (
153-
<ul>
154-
{posts.map((post) => (
155-
<li>
156-
<h3>{post.filename}</h3>
157-
<p>{post.content}</p>
158-
</li>
159-
))}
160-
</ul>
161-
)
96+
return data
16297
}
16398

164-
// This function gets called at build time on server-side.
165-
// It won't be called on client-side, so you can even do
166-
// direct database queries.
99+
// pages/blog.js
100+
import { loadPosts } from '../lib/load-posts'
101+
102+
// This function runs only on the server side
167103
export async function getStaticProps() {
168-
const postsDirectory = path.join(process.cwd(), 'posts')
169-
const filenames = await fs.readdir(postsDirectory)
104+
// Instead of fetching your `/api` route you can call the same
105+
// function directly in `getStaticProps`
106+
const posts = await loadPosts()
170107

171-
const posts = filenames.map(async (filename) => {
172-
const filePath = path.join(postsDirectory, filename)
173-
const fileContents = await fs.readFile(filePath, 'utf8')
108+
// Props returned will be passed to the page component
109+
return { props: { posts } }
110+
}
111+
```
174112

175-
// Generally you would parse/transform the contents
176-
// For example you can transform markdown to HTML here
113+
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.
177114

178-
return {
179-
filename,
180-
content: fileContents,
181-
}
182-
})
183-
// By returning { props: { posts } }, the Blog component
184-
// will receive `posts` as a prop at build time
185-
return {
186-
props: {
187-
posts: await Promise.all(posts),
188-
},
189-
}
190-
}
115+
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/).
191116

192-
export default Blog
193-
```
117+
## Statically generates both HTML and JSON
194118

195-
## getStaticProps with TypeScript
119+
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`.
196120

197-
You can use the `GetStaticProps` type from `next` to type the function:
121+
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.
198122

199-
```ts
200-
import { GetStaticProps } from 'next'
123+
When using Incremental Static Generation, `getStaticProps` will be executed in the background 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.
201124

202-
export const getStaticProps: GetStaticProps = async (context) => {
203-
// ...
204-
}
205-
```
125+
## Where can I use getStaticProps
206126

207-
If you want to get inferred typings for your props, you can use `InferGetStaticPropsType<typeof getStaticProps>`:
127+
`getStaticProps` can only be exported from a **page**. You **cannot** export it from non-page files.
208128

209-
```tsx
210-
import { InferGetStaticPropsType } from 'next'
129+
One of the reasons for this restriction is that React needs to have all the required data before the page is rendered.
211130

212-
type Post = {
213-
author: string
214-
content: string
215-
}
131+
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.
216132

217-
export const getStaticProps = async () => {
218-
const res = await fetch('https://.../posts')
219-
const posts: Post[] = await res.json()
133+
## Runs on every request in development
220134

221-
return {
222-
props: {
223-
posts,
224-
},
225-
}
226-
}
135+
In development (`next dev`), `getStaticProps` will be called on every request.
227136

228-
function Blog({ posts }: InferGetStaticPropsType<typeof getStaticProps>) {
229-
// will resolve posts to type Post[]
230-
}
137+
## Preview Mode
231138

232-
export default Blog
233-
```
139+
You can temporarily bypass static generation and render the page at **request time** instead of build time using [**Preview Mode**](/docs/advanced-features/preview-mode.md). For example, you might be using a headless CMS and want to preview drafts before they're published.
234140

235141
## Related
236142

237143
For more information on what to do next, we recommend the following sections:
238144

239145
<div class="card">
240-
<a href="/docs/basic-features/data-fetching/overview.md">
241-
<b>Data Fetching:</b>
242-
<small>Learn more about data fetching in Next.js.</small>
146+
<a href="/docs/api-reference/data-fetching/get-static-props.md">
147+
<b>getStaticProps API Reference</b>
148+
<small>Read the API Reference for getStaticProps</small>
243149
</a>
244150
</div>

0 commit comments

Comments
 (0)