Commit 4348fa71 authored by Delba de Oliveira's avatar Delba de Oliveira

Create data-revalidation.mdx

parent 9e4e6d6f
---
title: Revalidating Cached Data
description: Learn how to keep cached pages fresh with periodic revalidation using cacheLife and on-demand revalidation using cacheTag and revalidateTag.
nav_title: Revalidating Data
---
[Prerendered](/docs/app/glossary#prerendering) pages load fast, but the data behind them can change and become stale. For example, a product's price changes, a description gets updated, new inventory arrives. You need a way to refresh cached content without rebuilding and redeploying your entire app.
This guide covers two [revalidation](/docs/app/glossary#revalidation) strategies: **periodic revalidation** to refresh data on a time-based schedule, and **on-demand revalidation** to expire specific cache entries the moment data changes.
## Example
We'll take an existing product page that already uses [`'use cache'`](/docs/app/api-reference/directives/use-cache) and [`generateStaticParams`](/docs/app/api-reference/functions/generate-static-params), and add a cache lifetime so product data refreshes daily. Then we'll add cache tags so individual products can be revalidated instantly through a [Route Handler](/docs/app/getting-started/route-handlers).
You can find the resources used in this example here:
- [Demo](https://cache-components-public-pages-revalidation.labs.vercel.dev/)
- [Code](https://github.com/vercel-labs/cache-components-public-pages-revalidation)
### Step 1: Set a cache lifetime with `cacheLife`
The product data function currently uses `'use cache'` with no explicit cache lifetime:
```tsx filename="app/products/data.ts"
export async function getProduct(slug: string): Promise<Product> {
'use cache'
const response = await fetch(
`https://next-recipe-api.vercel.dev/products/${slug}`
)
return response.json()
}
```
Import [`cacheLife`](/docs/app/api-reference/functions/cacheLife) from `next/cache` and set the lifetime to `days`:
```tsx filename="app/products/data.ts"
import { cacheLife } from 'next/cache'
export async function getProduct(slug: string): Promise<Product> {
'use cache'
cacheLife('days')
const response = await fetch(
`https://next-recipe-api.vercel.dev/products/${slug}`
)
return response.json()
}
```
#### Cache lifetime profiles
[`cacheLife`](/docs/app/api-reference/functions/cacheLife) accepts a named profile that configures how long cached data stays fresh before revalidating in the background. If you don't specify a profile, Next.js uses `default`. The built-in profiles are:
| Profile | Stale | Revalidate | Expire |
| ----------- | ----- | ---------- | ------ |
| `default` | 5m | 15m | 1y |
| `'seconds'` | 30s | 1s | 1m |
| `'minutes'` | 5m | 1m | 1h |
| `'hours'` | 5m | 1h | 1d |
| `'days'` | 5m | 1d | 1w |
| `'weeks'` | 5m | 1w | 30d |
| `'max'` | 5m | 30d | 1y |
With `cacheLife('days')`, the data is served from cache immediately, [revalidated](/docs/app/glossary#revalidation) in the background after a day, and expires after a week. This means the first visitor after the revalidation window gets a stale response while a fresh one is generated, subsequent visitors get the updated data.
If we run [`next build`](/docs/app/api-reference/cli/next#next-build-options), the route table reflects the new lifetime:
```bash filename="Terminal"
Route (app) Revalidate Expire
├ ◐ /products/[slug] 1d 1w
└ ◐ /_not-found
◐ (Partial Prerender) prerendered as static HTML with dynamic server-streamed content
```
### Step 2: Tag and revalidate on demand
Periodic revalidation works for data that changes on a predictable schedule. But sometimes you want data to be refreshed immediately, for example, when a product's price is updated in your CMS, you don't want to wait up to a day for the change to appear.
#### Cache tags
Import [`cacheTag`](/docs/app/api-reference/functions/cacheTag) and call it inside the cached function to label the cache entry:
```tsx filename="app/products/data.ts"
import { cacheLife, cacheTag } from 'next/cache'
export async function getProduct(slug: string): Promise<Product> {
'use cache'
cacheTag(`product-${slug}`)
cacheLife('days')
const response = await fetch(
`https://next-recipe-api.vercel.dev/products/${slug}`
)
return response.json()
}
```
`cacheTag` attaches one or more string labels to a cache entry. These tags don't affect caching behavior on their own. They exist so you can target specific entries for invalidation later.
You can tag the product list function too, so the full data layer looks like this:
```tsx filename="app/products/data.ts"
import { cacheLife, cacheTag } from 'next/cache'
export async function getProducts(): Promise<Product[]> {
'use cache'
cacheTag('products')
cacheLife('days')
const response = await fetch('https://next-recipe-api.vercel.dev/products')
return response.json()
}
export async function getProduct(slug: string): Promise<Product> {
'use cache'
cacheTag(`product-${slug}`)
cacheLife('days')
const response = await fetch(
`https://next-recipe-api.vercel.dev/products/${slug}`
)
return response.json()
}
```
#### On-demand revalidation
To invalidate a tagged entry, call [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag) from a [Route Handler](/docs/app/getting-started/route-handlers) or [Server Action](/docs/app/getting-started/updating-data).
Create a Route Handler that accepts a tag and invalidates it:
```tsx filename="app/api/revalidate/route.ts"
import { revalidateTag } from 'next/cache'
import type { NextRequest } from 'next/server'
export async function POST(request: NextRequest) {
const { tag } = await request.json()
revalidateTag(tag, 'days')
return Response.json({ revalidated: true, tag })
}
```
When this endpoint receives a POST request, it marks all cache entries matching the given tag as expired. The second argument to `revalidateTag` sets the [cache lifetime profile](#cache-lifetime-profiles) for the refreshed entry. The next visitor to that page triggers a fresh render with updated data.
You can test this locally with `curl`:
```bash filename="Terminal"
curl -X POST http://localhost:3000/api/revalidate \
-H 'Content-Type: application/json' \
-d '{"tag": "product-shorts"}'
```
This returns:
```json
{ "revalidated": true, "tag": "product-shorts" }
```
The next request to `/products/shorts` will return fresh data, you'll see the `updatedAt` timestamp on the product page change.
In production, a CMS would call this endpoint via a webhook when content changes.
### Step 3: Secure the revalidation endpoint
The Route Handler is currently public. Anyone who knows the URL can invalidate your cache.
To prevent this, check for a secret token before processing the request. For example, read the `Authorization` header and compare it against a server-side environment variable. If the token doesn't match, return a `401` error:
```tsx filename="app/api/revalidate/route.ts"
import { revalidateTag } from 'next/cache'
import type { NextRequest } from 'next/server'
export async function POST(request: NextRequest) {
const authHeader = request.headers.get('authorization')
if (authHeader !== `Bearer ${process.env.REVALIDATION_SECRET}`) {
return Response.json({ error: 'Unauthorized' }, { status: 401 })
}
const { tag } = await request.json()
revalidateTag(tag, 'days')
return Response.json({ revalidated: true, tag })
}
```
Store `REVALIDATION_SECRET` as an environment variable on your hosting provider and in an `.env` file for local development.
Now send the `curl` request with the `Authorization` header:
```bash filename="Terminal"
curl -X POST http://localhost:3000/api/revalidate \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer <YOUR_REVALIDATION_SECRET_HERE>' \
-d '{"tag": "product-shorts"}'
```
Without the header, the endpoint returns a `401`:
```json
{ "error": "Unauthorized" }
```
## Next steps
You now know how to control cache lifetimes with `cacheLife` and invalidate specific cache entries on demand with `cacheTag` and `revalidateTag`.
Next, learn how to:
- [Build variations of the same page](/docs/app/guides/page-variations)
- [Build public, static pages](/docs/app/guides/public-static-pages)
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