Unverified Commit 0adb4986 authored by Joseph's avatar Joseph Committed by GitHub

docs: GET handler behavior under cache components (#85389)

parent 7f503bfe
...@@ -575,6 +575,65 @@ export async function Table({ sortPromise }) { ...@@ -575,6 +575,65 @@ export async function Table({ sortPromise }) {
} }
``` ```
## Route Handlers with Cache Components
`GET` Route Handlers follow the same model as normal UI routes in your application. They are dynamic by default, can be pre-rendered when deterministic, and you can `use cache` to include more dynamic data in the cached response.
Dynamic example, returns a different number for every request:
```tsx filename="app/api/random-number/route.ts"
export async function GET() {
return Response.json({
randomNumber: Math.random(),
})
}
```
A handler that returns only static data will be pre-rendered at build time:
```tsx filename="app/api/project-info/route.ts"
export async function GET() {
return Response.json({
projectName: 'Next.js',
})
}
```
If you had a route that returned fresh dynamic data on every request, say products from a database:
```tsx filename="app/api/products/route.ts"
export async function GET() {
const products = await db.query('SELECT * FROM products')
return Response.json(products)
}
```
To cache this and avoid hitting the database on every request, extract the dynamic work into a `use cache` function and set `cacheLife('hours')` so the database is queried at most once per hour:
```tsx filename="app/api/products/route.ts"
import { cacheLife } from 'next/cache'
export async function GET() {
const products = await getProducts()
return Response.json(products)
}
async function getProducts() {
'use cache'
cacheLife('hours')
return await db.query('SELECT * FROM products')
}
```
> **Good to know**
>
> - `use cache` cannot be used directly inside a Route Handler body; extract to a helper.
> - Cached responses revalidate according to `cacheLife` when a new request arrives.
> - Using runtime APIs like [`cookies()`](/docs/app/api-reference/functions/cookies) or [`headers()`](/docs/app/api-reference/functions/headers), or calling [`connection()`](/docs/app/api-reference/functions/connection), always defers to request time (no pre-rendering).
## Frequently Asked Questions ## Frequently Asked Questions
### Does this replace Partial Prerendering (PPR)? ### Does this replace Partial Prerendering (PPR)?
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment