You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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`.
20
8
21
9
```jsx
22
10
exportasyncfunctiongetStaticProps(context) {
@@ -26,219 +14,137 @@ export async function getStaticProps(context) {
26
14
}
27
15
```
28
16
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?
30
18
31
-
## Context parameter
19
+
You should use `getStaticProps` if:
32
20
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
34
25
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
41
27
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/).
43
29
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)
45
33
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.
47
35
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`.
49
37
50
-
```jsx
51
-
exportasyncfunctiongetStaticProps(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
57
39
58
-
### `revalidate`
40
+
The following example shows how you can fetch a list of blog posts from a CMS.
59
41
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
+
functionBlog({ posts }) {
45
+
return (
46
+
<ul>
47
+
{posts.map((post) => (
48
+
<li>{post.title}</li>
49
+
))}
50
+
</ul>
51
+
)
52
+
}
61
53
62
-
```js
63
54
// 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.
66
57
exportasyncfunctiongetStaticProps() {
58
+
// Call an external API endpoint to get posts.
59
+
// You can use any data fetching library
67
60
constres=awaitfetch('https://.../posts')
68
61
constposts=awaitres.json()
69
62
63
+
// By returning { props: { posts } }, the Blog component
64
+
// will receive `posts` as a prop at build time
70
65
return {
71
66
props: {
72
67
posts,
73
68
},
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
-
exportasyncfunctiongetStaticProps(context) {
90
-
constres=awaitfetch(`https://.../data`)
91
-
constdata=awaitres.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
101
69
}
102
70
}
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
-
exportasyncfunctiongetStaticProps(context) {
115
-
constres=awaitfetch(`https://...`)
116
-
constdata=awaitres.json()
117
71
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
+
exportdefaultBlog
132
73
```
133
74
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`.
135
76
136
-
## Reading files: Use `process.cwd()`
77
+
## Write server-side code directly
137
78
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.
139
80
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`.
141
82
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`.
145
84
146
85
```jsx
147
-
import { promisesasfs } from'fs'
148
-
importpathfrom'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
+
exportasyncfunctionloadPosts() {
92
+
// Call an external API endpoint to get posts
93
+
constres=awaitfetch('https://.../posts/')
94
+
constdata=awaitres.json()
149
95
150
-
// posts will be populated at build time by getStaticProps()
151
-
functionBlog({ 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
162
97
}
163
98
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
// Props returned will be passed to the page component
109
+
return { props: { posts } }
110
+
}
111
+
```
174
112
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.
177
114
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:awaitPromise.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/).
191
116
192
-
exportdefaultBlog
193
-
```
117
+
## Statically generates both HTML and JSON
194
118
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`.
196
120
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.
198
122
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.
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.
208
128
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.
211
130
212
-
typePost= {
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.
216
132
217
-
exportconst getStaticProps =async () => {
218
-
const res =awaitfetch('https://.../posts')
219
-
const posts:Post[] =awaitres.json()
133
+
## Runs on every request in development
220
134
221
-
return {
222
-
props: {
223
-
posts,
224
-
},
225
-
}
226
-
}
135
+
In development (`next dev`), `getStaticProps` will be called on every request.
227
136
228
-
function Blog({ posts }:InferGetStaticPropsType<typeofgetStaticProps>) {
229
-
// will resolve posts to type Post[]
230
-
}
137
+
## Preview Mode
231
138
232
-
exportdefaultBlog
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.
234
140
235
141
## Related
236
142
237
143
For more information on what to do next, we recommend the following sections:
0 commit comments