Skip to content

Commit d6cb99b

Browse files
authored
Add docs about SSR caching (yes, you can do this with Next.js) (#36588)
I've heard a lot of folks not realize this is possible 😄 Hopefully this helps.
1 parent 0de109b commit d6cb99b

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

docs/basic-features/data-fetching/get-server-side-props.md

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,32 @@ export async function getServerSideProps() {
7474
export default Page
7575
```
7676

77+
## Caching with Server-Side Rendering (SSR)
78+
79+
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/).
80+
81+
```jsx
82+
// This value is considered fresh for ten seconds (s-maxage=10).
83+
// If a request is repeated within the next 10 seconds, the previously
84+
// cached value will still be fresh. If the request is repeated before 59 seconds,
85+
// the cached value will be stale but still render (stale-while-revalidate=59).
86+
//
87+
// In the background, a revalidation request will be made to populate the cache
88+
// with a fresh value. If you refresh the page, you will see the new value.
89+
export async function getServerSideProps({ req, res }) {
90+
res.setHeader(
91+
'Cache-Control',
92+
'public, s-maxage=10, stale-while-revalidate=59'
93+
)
94+
95+
return {
96+
props: {},
97+
}
98+
}
99+
```
100+
101+
Learn more about [caching](/docs/going-to-production.md).
102+
77103
## Does getServerSideProps render an error page
78104

79105
If an error is thrown inside `getServerSideProps`, it will show the `pages/500.js` file. Check out the documentation for [500 page](/docs/advanced-features/custom-error-page#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.

0 commit comments

Comments
 (0)