File size: 7,358 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 |
---
title: Caching and Revalidating
description: Learn how to cache and revalidate data in your application.
related:
title: API Reference
description: Learn more about the features mentioned in this page by reading the API Reference.
links:
- app/api-reference/functions/fetch
- app/api-reference/functions/unstable_cache
- app/api-reference/functions/revalidatePath
- app/api-reference/functions/revalidateTag
---
Caching is a technique for storing the result of data fetching and other computations so that future requests for the same data can be served faster, without doing the work again. While revalidation allows you to update cache entries without having to rebuild your entire application.
Next.js provides a few APIs to handle caching and revalidation. This guide will walk you through when and how to use them.
- [`fetch`](#fetch)
- [`unstable_cache`](#unstable_cache)
- [`revalidatePath`](#revalidatepath)
- [`revalidateTag`](#revalidatetag)
## `fetch`
By default, [`fetch`](/docs/app/api-reference/functions/fetch) requests are not cached. You can cache individual requests by setting the `cache` option to `'force-cache'`.
```tsx filename="app/page.tsx" switcher
export default async function Page() {
const data = await fetch('https://...', { cache: 'force-cache' })
}
```
```jsx filename="app/page.jsx" switcher
export default async function Page() {
const data = await fetch('https://...', { cache: 'force-cache' })
}
```
> **Good to know**: Although `fetch` requests are not cached by default, Next.js will [prerender](/docs/app/getting-started/partial-prerendering#static-rendering) routes that have `fetch` requests and cache the HTML. If you want to guarantee a route is [dynamic](/docs/app/getting-started/partial-prerendering#dynamic-rendering), use the [`connection` API](/docs/app/api-reference/functions/connection).
To revalidate the data returned by a `fetch` request, you can use the `next.revalidate` option.
```tsx filename="app/page.tsx" switcher
export default async function Page() {
const data = await fetch('https://...', { next: { revalidate: 3600 } })
}
```
```jsx filename="app/page.jsx" switcher
export default async function Page() {
const data = await fetch('https://...', { next: { revalidate: 3600 } })
}
```
This will revalidate the data after a specified amount of seconds.
See the [`fetch` API reference](/docs/app/api-reference/functions/fetch) to learn more.
## `unstable_cache`
`unstable_cache` allows you to cache the result of database queries and other async functions. To use it, wrap `unstable_cache` around the function. For example:
```tsx filename="app/lib/data.ts swichter
import { db } from '@/lib/db'
export async function getUserById(id: string) {
return db
.select()
.from(users)
.where(eq(users.id, id))
.then((res) => res[0])
}
```
```jsx filename="app/lib/data.js" switcher
import { db } from '@/lib/db'
export async function getUserById(id) {
return db
.select()
.from(users)
.where(eq(users.id, id))
.then((res) => res[0])
}
```
```tsx filename="app/page.tsx" highlight={2,11,13} switcher
import { unstable_cache } from 'next/cache'
import { getUserById } from '@/app/lib/data'
export default async function Page({
params,
}: {
params: Promise<{ userId: string }>
}) {
const { userId } = await params
const getCachedUser = unstable_cache(
async () => {
return getUserById(userId)
},
[userId] // add the user ID to the cache key
)
}
```
```jsx filename="app/page.jsx" highlight={2,7,9} switcher
import { unstable_cache } from 'next/cache';
import { getUserById } from '@/app/lib/data';
export default async function Page({ params } }) {
const { userId } = await params
const getCachedUser = unstable_cache(
async () => {
return getUserById(userId)
},
[userId] // add the user ID to the cache key
);
}
```
The function accepts a third optional object to define how the cache should be revalidated. It accepts:
- `tags`: an array of tags used by Next.js to revalidate the cache.
- `revalidate`: the number of seconds after cache should be revalidated.
```tsx filename="app/page.tsx" highlight={6-9} switcher
const getCachedUser = unstable_cache(
async () => {
return getUserById(userId)
},
[userId],
{
tags: ['user'],
revalidate: 3600,
}
)
```
```jsx filename="app/page.js" highlight={6-9} switcher
const getCachedUser = unstable_cache(
async () => {
return getUserById(userId)
},
[userId],
{
tags: ['user'],
revalidate: 3600,
}
)
```
See the [`unstable_cache` API reference](/docs/app/api-reference/functions/unstable_cache) to learn more.
## `revalidateTag`
`revalidateTag` is used to revalidate cache entries based on a tag and following an event. To use it with `fetch`, start by tagging the function with the `next.tags` option:
```tsx filename="app/lib/data.ts" highlight={3-5} switcher
export async function getUserById(id: string) {
const data = await fetch(`https://...`, {
next: {
tags: ['user'],
},
})
}
```
```jsx filename="app/lib/data.js" highlight={3-5} switcher
export async function getUserById(id) {
const data = await fetch(`https://...`, {
next: {
tags: ['user'],
},
})
}
```
Alternatively, you can mark an `unstable_cache` function with the `tags` option:
```tsx filename="app/lib/data.ts" highlight={6-8} switcher
export const getUserById = unstable_cache(
async (id: string) => {
return db.query.users.findFirst({ where: eq(users.id, id) })
},
['user'], // Needed if variables are not passed as parameters
{
tags: ['user'],
}
)
```
```jsx filename="app/lib/data.js" highlight={6-8} switcher
export const getUserById = unstable_cache(
async (id) => {
return db.query.users.findFirst({ where: eq(users.id, id) })
},
['user'], // Needed if variables are not passed as parameters
{
tags: ['user'],
}
)
```
Then, call `revalidateTag` in a [Route Handler](/docs/app/api-reference/file-conventions/route) or Server Action:
```tsx filename="app/lib/actions.ts" highlight={1} switcher
import { revalidateTag } from 'next/cache'
export async function updateUser(id: string) {
// Mutate data
revalidateTag('user')
}
```
```jsx filename="app/lib/actions.js" highlight={1} switcher
import { revalidateTag } from 'next/cache'
export async function updateUser(id) {
// Mutate data
revalidateTag('user')
}
```
You can reuse the same tag in multiple functions to revalidate them all at once.
See the [`revalidateTag` API reference](/docs/app/api-reference/functions/revalidateTag) to learn more.
## `revalidatePath`
`revalidatePath` is used to revalidate a route and following an event. To use it, call it in a [Route Handler](/docs/app/api-reference/file-conventions/route) or Server Action:
```tsx filename="app/lib/actions.ts" highlight={1} switcher
import { revalidatePath } from 'next/cache'
export async function updateUser(id: string) {
// Mutate data
revalidatePath('/profile')
```
```jsx filename="app/lib/actions.js" highlight={1} switcher
import { revalidatePath } from 'next/cache'
export async function updateUser(id) {
// Mutate data
revalidatePath('/profile')
```
See the [`revalidatePath` API reference](/docs/app/api-reference/functions/revalidatePath) to learn more.
|