Skip to content

Commit d2fd8f7

Browse files
Docs: Review and update getServerSideProps page (#59545)
- Remove recommendation for client-side rendering - Cut repetition - Improve tone
1 parent 5f1e909 commit d2fd8f7

File tree

2 files changed

+62
-73
lines changed

2 files changed

+62
-73
lines changed

docs/03-pages/01-building-your-application/03-data-fetching/03-get-server-side-props.mdx

Lines changed: 45 additions & 66 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,11 @@ title: getServerSideProps
33
description: Fetch data on each request with `getServerSideProps`.
44
---
55

6-
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`.
6+
`getServerSideProps` is a Next.js function that can be used fetch data and render the contents of a page at request time.
7+
8+
## Example
9+
10+
You can use `getServerSideProps` by exporting it from a Page Component. The example below how you can fetch data from a 3rd party API in `getServerSideProps`, and pass the data to the page as props:
711

812
```tsx filename="pages/index.tsx" switcher
913
import type { InferGetServerSidePropsType, GetServerSideProps } from 'next'
@@ -13,67 +17,75 @@ type Repo = {
1317
stargazers_count: number
1418
}
1519

16-
export const getServerSideProps = (async (context) => {
20+
export const getServerSideProps = (async () => {
21+
// Fetch data from external API
1722
const res = await fetch('https://api.github.com/repos/vercel/next.js')
18-
const repo = await res.json()
23+
const repo: Repo = await res.json()
24+
// Pass data to the page via props
1925
return { props: { repo } }
20-
}) satisfies GetServerSideProps<{
21-
repo: Repo
22-
}>
26+
}) satisfies GetServerSideProps<{ repo: Repo }>
2327

2428
export default function Page({
2529
repo,
2630
}: InferGetServerSidePropsType<typeof getServerSideProps>) {
27-
return repo.stargazers_count
31+
return (
32+
<main>
33+
<p>{repo.stargazers_count}</p>
34+
</main>
35+
)
2836
}
2937
```
3038

3139
```jsx filename="pages/index.js" switcher
3240
export async function getServerSideProps() {
41+
// Fetch data from external API
3342
const res = await fetch('https://api.github.com/repos/vercel/next.js')
3443
const repo = await res.json()
44+
// Pass data to the page via props
3545
return { props: { repo } }
3646
}
3747

3848
export default function Page({ repo }) {
39-
return repo.stargazers_count
49+
return (
50+
<main>
51+
<p>{repo.stargazers_count}</p>
52+
</main>
53+
)
4054
}
4155
```
4256

43-
> Note that irrespective of rendering type, any `props` will be passed to the page component and can be viewed on the client-side in the initial HTML. This is to allow the page to be [hydrated](https://react.dev/reference/react-dom/hydrate) correctly. Make sure that you don't pass any sensitive information that shouldn't be available on the client in `props`.
44-
45-
## When does getServerSideProps run
46-
47-
`getServerSideProps` only runs on server-side and never runs on the browser. If a page uses `getServerSideProps`, then:
48-
49-
- When you request this page directly, `getServerSideProps` runs at request time, and this page will be pre-rendered with the returned props
50-
- When you request this page on client-side page transitions through [`next/link`](/docs/pages/api-reference/components/link) or [`next/router`](/docs/pages/api-reference/functions/use-router), Next.js sends an API request to the server, which runs `getServerSideProps`
57+
## When should I use `getServerSideProps`?
5158

52-
`getServerSideProps` returns JSON which 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.
59+
You should use `getServerSideProps` if you need to render a page that relies on personalized user data, or information that can only be known at request time. For example, `authorization` headers or a geolocation.
5360

54-
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.
61+
If you do not need to fetch the data at request time, or would prefer to cache the data and pre-rendered HTML, we recommend using [`getStaticProps`](/docs/pages/building-your-application/data-fetching/get-static-props).
5562

56-
`getServerSideProps` can only be exported from a **page**. You can’t export it from non-page files.
63+
## Behavior
5764

58-
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.
65+
- `getServerSideProps` runs on the server.
66+
- `getServerSideProps` can only be exported from a **page**.
67+
- `getServerSideProps` returns JSON.
68+
- When a user visits a page, `getServerSideProps` will be used to fetch data at request time, and the data is used to render the initial HTML of the page.
69+
- `props` passed to the page component can be viewed on the client as part of the initial HTML. This is to allow the page to be [hydrated](https://react.dev/reference/react-dom/hydrate) correctly. Make sure that you don't pass any sensitive information that shouldn't be available on the client in `props`.
70+
- When a user visits the page through [`next/link`](/docs/pages/api-reference/components/link) or [`next/router`](/docs/pages/api-reference/functions/use-router), Next.js sends an API request to the server, which runs `getServerSideProps`.
71+
- You do not have to call a Next.js [API Route](/docs/pages/building-your-application/routing/api-routes) to fetch data when using `getServerSideProps` since the function runs on the server. Instead, you can call a CMS, database, or other third-party APIs directly from inside `getServerSideProps`.
5972

60-
The [`getServerSideProps` API reference](/docs/pages/api-reference/functions/get-server-side-props) covers all parameters and props that can be used with `getServerSideProps`.
73+
> **Good to know:**
74+
>
75+
> - See [`getServerSideProps` API reference](/docs/pages/api-reference/functions/get-server-side-props) for parameters and props that can be used with `getServerSideProps`.
76+
> - 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.
6177
62-
## When should I use getServerSideProps
78+
## Error Handling
6379

64-
You should use `getServerSideProps` only if you need to render a page whose data must be fetched at request time. This could be due to the nature of the data or properties of the request (such as `authorization` headers or geo location). Pages using `getServerSideProps` will be server side rendered at request time and only be cached if [cache-control headers are configured](/docs/pages/building-your-application/deploying/production-checklist#caching).
80+
If an error is thrown inside `getServerSideProps`, it will show the `pages/500.js` file. Check out the documentation for [500 page](/docs/pages/building-your-application/routing/custom-error#500-page) to learn more on how to create it. During development, this file will not be used and the development error overlay will be shown instead.
6581

66-
If you do not need to render the data during the request, then you should consider fetching data on the [client side](#fetching-data-on-the-client-side) or [`getStaticProps`](/docs/pages/building-your-application/data-fetching/get-static-props).
82+
## Edge Cases
6783

68-
### getServerSideProps or API Routes
84+
### Edge Runtime
6985

70-
It can be tempting to reach for an [API Route](/docs/pages/building-your-application/routing/api-routes) 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.
86+
`getServerSideProps` can be used with both [Serverless and Edge Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes), and you can set props in both.
7187

72-
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`.
73-
74-
### getServerSideProps with Edge API Routes
75-
76-
`getServerSideProps` can be used with both [Serverless and Edge Runtimes](/docs/pages/building-your-application/rendering/edge-and-nodejs-runtimes), and you can set props in both. However, currently in the Edge Runtime, you do not have access to the response object. This means that you cannot — for example — add cookies in `getServerSideProps`. To have access to the response object, you should **continue to use the Node.js runtime**, which is the default runtime.
88+
However, currently in the Edge Runtime, you do not have access to the response object. This means that you cannot — for example — add cookies in `getServerSideProps`. To have access to the response object, you should **continue to use the Node.js runtime**, which is the default runtime.
7789

7890
You can explicitly set the runtime on a per-page basis by modifying the `config`, for example:
7991

@@ -85,36 +97,7 @@ export const config = {
8597
export const getServerSideProps = async () => {}
8698
```
8799

88-
## Fetching data on the client side
89-
90-
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/pages/building-your-application/data-fetching/client-side). An example of this is user-specific data:
91-
92-
- 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
93-
- Then, fetch the data on the client side and display it when ready
94-
95-
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.
96-
97-
## Using getServerSideProps to fetch data at request time
98-
99-
The following example shows how to fetch data at request time and pre-render the result.
100-
101-
```jsx
102-
// This gets called on every request
103-
export async function getServerSideProps() {
104-
// Fetch data from external API
105-
const res = await fetch(`https://.../data`)
106-
const data = await res.json()
107-
108-
// Pass data to the page via props
109-
return { props: { data } }
110-
}
111-
112-
export default function Page({ data }) {
113-
// Render data...
114-
}
115-
```
116-
117-
## Caching with Server-Side Rendering (SSR)
100+
### Caching with Server-Side Rendering (SSR)
118101

119102
You can use caching headers (`Cache-Control`) inside `getServerSideProps` to cache dynamic responses. For example, using [`stale-while-revalidate`](https://web.dev/stale-while-revalidate/).
120103

@@ -138,8 +121,4 @@ export async function getServerSideProps({ req, res }) {
138121
}
139122
```
140123

141-
Learn more about [caching](/docs/pages/building-your-application/deploying/production-checklist#caching).
142-
143-
## Does getServerSideProps render an error page
144-
145-
If an error is thrown inside `getServerSideProps`, it will show the `pages/500.js` file. Check out the documentation for [500 page](/docs/pages/building-your-application/routing/custom-error#500-page) to learn more on how to create it. During development this file will not be used and the dev overlay will be shown instead.
124+
However, before reaching for `cache-control`, we recommend seeing if [`getStaticProps`](/docs/pages/building-your-application/data-fetching/get-static-props) with [ISR](/docs/pages/building-your-application/data-fetching/incremental-static-regeneration) is a better fit for your use case.

docs/03-pages/02-api-reference/02-functions/get-server-side-props.mdx

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,30 +13,40 @@ type Repo = {
1313
stargazers_count: number
1414
}
1515

16-
export const getServerSideProps = (async (context) => {
16+
export const getServerSideProps = (async () => {
17+
// Fetch data from external API
1718
const res = await fetch('https://api.github.com/repos/vercel/next.js')
18-
const repo = await res.json()
19+
const repo: Repo = await res.json()
20+
// Pass data to the page via props
1921
return { props: { repo } }
20-
}) satisfies GetServerSideProps<{
21-
repo: Repo
22-
}>
22+
}) satisfies GetServerSideProps<{ repo: Repo }>
2323

2424
export default function Page({
2525
repo,
2626
}: InferGetServerSidePropsType<typeof getServerSideProps>) {
27-
return repo.stargazers_count
27+
return (
28+
<main>
29+
<p>{repo.stargazers_count}</p>
30+
</main>
31+
)
2832
}
2933
```
3034

3135
```jsx filename="pages/index.js" switcher
3236
export async function getServerSideProps() {
37+
// Fetch data from external API
3338
const res = await fetch('https://api.github.com/repos/vercel/next.js')
3439
const repo = await res.json()
40+
// Pass data to the page via props
3541
return { props: { repo } }
3642
}
3743

3844
export default function Page({ repo }) {
39-
return repo.stargazers_count
45+
return (
46+
<main>
47+
<p>{repo.stargazers_count}</p>
48+
</main>
49+
)
4050
}
4151
```
4252

0 commit comments

Comments
 (0)