Unverified Commit e598a4f9 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Add new updateTag API and new signature for revalidateTag (#83822)

parent 8d415853
......@@ -654,8 +654,6 @@ impl ReactServerComponentValidator {
// "unstable_cache", // useless in client, but doesn't technically error
"unstable_cacheLife",
"unstable_cacheTag",
"unstable_expirePath",
"unstable_expireTag",
// "unstable_noStore" // no-op in client, but allowed for legacy reasons
],
),
......
......@@ -9,6 +9,7 @@ related:
- app/api-reference/functions/unstable_cache
- app/api-reference/functions/revalidatePath
- app/api-reference/functions/revalidateTag
- app/api-reference/functions/updateTag
---
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.
......@@ -19,6 +20,7 @@ Next.js provides a few APIs to handle caching and revalidation. This guide will
- [`unstable_cache`](#unstable_cache)
- [`revalidatePath`](#revalidatepath)
- [`revalidateTag`](#revalidatetag)
- [`updateTag`](#updatetag)
## `fetch`
......@@ -154,7 +156,12 @@ See the [`unstable_cache` API reference](/docs/app/api-reference/functions/unsta
## `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:
`revalidateTag` is used to revalidate cache entries based on a tag and following an event. The function now supports two behaviors:
- **With `profile="max"`**: Uses stale-while-revalidate semantics, serving stale content while fetching fresh content in the background
- **Without the second argument**: Legacy behavior that immediately expires the cache (deprecated)
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) {
......@@ -204,21 +211,21 @@ export const getUserById = unstable_cache(
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
```tsx filename="app/lib/actions.ts" highlight={1,5} switcher
import { revalidateTag } from 'next/cache'
export async function updateUser(id: string) {
// Mutate data
revalidateTag('user')
revalidateTag('user', 'max') // Recommended: Uses stale-while-revalidate
}
```
```jsx filename="app/lib/actions.js" highlight={1} switcher
```jsx filename="app/lib/actions.js" highlight={1,5} switcher
import { revalidateTag } from 'next/cache'
export async function updateUser(id) {
// Mutate data
revalidateTag('user')
revalidateTag('user', 'max') // Recommended: Uses stale-while-revalidate
}
```
......@@ -247,3 +254,56 @@ export async function updateUser(id) {
```
See the [`revalidatePath` API reference](/docs/app/api-reference/functions/revalidatePath) to learn more.
## `updateTag`
`updateTag` is specifically designed for Server Actions to immediately expire cached data for read-your-own-writes scenarios. Unlike `revalidateTag`, it can only be used within Server Actions and immediately expires the cache entry.
```tsx filename="app/lib/actions.ts" highlight={1,6} switcher
import { updateTag } from 'next/cache'
import { redirect } from 'next/navigation'
export async function createPost(formData: FormData) {
// Create post in database
const post = await db.post.create({
data: {
title: formData.get('title'),
content: formData.get('content'),
},
})
// Immediately expire cache so the new post is visible
updateTag('posts')
updateTag(`post-${post.id}`)
redirect(`/posts/${post.id}`)
}
```
```jsx filename="app/lib/actions.js" highlight={1,6} switcher
import { updateTag } from 'next/cache'
import { redirect } from 'next/navigation'
export async function createPost(formData) {
// Create post in database
const post = await db.post.create({
data: {
title: formData.get('title'),
content: formData.get('content'),
},
})
// Immediately expire cache so the new post is visible
updateTag('posts')
updateTag(`post-${post.id}`)
redirect(`/posts/${post.id}`)
}
```
The key differences between `revalidateTag` and `updateTag`:
- **`updateTag`**: Only in Server Actions, immediately expires cache, for read-your-own-writes
- **`revalidateTag`**: In Server Actions and Route Handlers, supports stale-while-revalidate with `profile="max"`
See the [`updateTag` API reference](/docs/app/api-reference/functions/updateTag) to learn more.
......@@ -11,15 +11,24 @@ description: API Reference for the revalidateTag function.
`revalidateTag` cannot be called in Client Components or Middleware, as it only works in server environments.
> **Good to know**: `revalidateTag` marks tagged data as stale, but fresh data is only fetched when pages using that tag are next visited. This means calling `revalidateTag` will not immediately trigger many revalidations at once. The invalidation only happens when any page using that tag is next visited.
### Revalidation Behavior
The revalidation behavior depends on whether you provide the second argument:
- **With `profile="max"` (recommended)**: The tag entry is marked as stale, and the next time a resource with that tag is visited, it will use stale-while-revalidate semantics. This means the stale content is served while fresh content is fetched in the background.
- **With a custom cache life profile**: For advanced usage, you can specify any cache life profile that your application has defined, allowing for custom revalidation behaviors tailored to your specific caching requirements.
- **Without the second argument (deprecated)**: The tag entry is expired immediately, and the next request to that resource will be a blocking revalidate/cache miss. This behavior is now deprecated, and you should either use `profile="max"` or migrate to `updateTag`.
> **Good to know**: When using `profile="max"`, `revalidateTag` marks tagged data as stale, but fresh data is only fetched when pages using that tag are next visited. This means calling `revalidateTag` will not immediately trigger many revalidations at once. The invalidation only happens when any page using that tag is next visited.
## Parameters
```tsx
revalidateTag(tag: string): void;
revalidateTag(tag: string, profile?: string): void;
```
- `tag`: A string representing the cache tag associated with the data you want to revalidate. Must not exceed 256 characters. This value is case-sensitive.
- `profile`: A string that specifies the revalidation behavior. The recommended value is `"max"` which provides stale-while-revalidate semantics. For advanced usage, this can be configured to any cache life profile that your application defines.
You can add tags to `fetch` as follows:
......@@ -48,7 +57,7 @@ import { revalidateTag } from 'next/cache'
export default async function submit() {
await addPost()
revalidateTag('posts')
revalidateTag('posts', 'max')
}
```
......@@ -59,7 +68,7 @@ import { revalidateTag } from 'next/cache'
export default async function submit() {
await addPost()
revalidateTag('posts')
revalidateTag('posts', 'max')
}
```
......@@ -73,7 +82,7 @@ export async function GET(request: NextRequest) {
const tag = request.nextUrl.searchParams.get('tag')
if (tag) {
revalidateTag(tag)
revalidateTag(tag, 'max')
return Response.json({ revalidated: true, now: Date.now() })
}
......@@ -92,7 +101,7 @@ export async function GET(request) {
const tag = request.nextUrl.searchParams.get('tag')
if (tag) {
revalidateTag(tag)
revalidateTag(tag, 'max')
return Response.json({ revalidated: true, now: Date.now() })
}
......
---
title: updateTag
description: API Reference for the updateTag function.
---
`updateTag` allows you to update [cached data](/docs/app/guides/caching) on-demand for a specific cache tag from within Server Actions. This function is designed specifically for read-your-own-writes scenarios.
## Usage
`updateTag` can **only** be called from within Server Actions. It cannot be used in Route Handlers, Client Components, or any other context.
If you need to invalidate cache tags in Route Handlers or other contexts, use [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag) instead.
> **Good to know**: `updateTag` immediately expires the cached data for the specified tag, causing the next request to that resource to be a blocking revalidate/cache miss. This ensures that Server Actions can immediately see their own writes.
## Parameters
```tsx
updateTag(tag: string): void;
```
- `tag`: A string representing the cache tag associated with the data you want to update. Must not exceed 256 characters. This value is case-sensitive.
## Returns
`updateTag` does not return a value.
## Differences from revalidateTag
While both `updateTag` and `revalidateTag` invalidate cached data, they serve different purposes:
- **`updateTag`**:
- Can only be used in Server Actions
- Immediately expires the cache entry (blocking revalidate on next visit)
- Designed for read-your-own-writes scenarios
- **`revalidateTag`**:
- Can be used in Server Actions and Route Handlers
- With `profile="max"` (recommended): Uses stale-while-revalidate semantics
- With custom profile: Can be configured to any cache life profile for advanced usage
- Without profile: legacy behavior which is equivalent to `updateTag`
## Examples
### Server Action with Read-Your-Own-Writes
```ts filename="app/actions.ts" switcher
'use server'
import { updateTag } from 'next/cache'
import { redirect } from 'next/navigation'
export async function createPost(formData: FormData) {
const title = formData.get('title')
const content = formData.get('content')
// Create the post in your database
const post = await db.post.create({
data: { title, content },
})
// Update the cache so the new post is immediately visible
updateTag('posts')
updateTag(`post-${post.id}`)
// Redirect to the new post
redirect(`/posts/${post.id}`)
}
```
```js filename="app/actions.js" switcher
'use server'
import { updateTag } from 'next/cache'
import { redirect } from 'next/navigation'
export async function createPost(formData) {
const title = formData.get('title')
const content = formData.get('content')
// Create the post in your database
const post = await db.post.create({
data: { title, content },
})
// Update the cache so the new post is immediately visible
updateTag('posts')
updateTag(`post-${post.id}`)
// Redirect to the new post
redirect(`/posts/${post.id}`)
}
```
### Error when used outside Server Actions
```ts filename="app/api/posts/route.ts" switcher
import { updateTag } from 'next/cache'
export async function POST() {
// ❌ This will throw an error
updateTag('posts')
// Error: updateTag can only be called from within a Server Action
// ✅ Use revalidateTag instead in Route Handlers
revalidateTag('posts', 'max')
}
```
## When to use updateTag
Use `updateTag` when:
- You're in a Server Action
- You need immediate cache invalidation for read-your-own-writes
- You want to ensure the next request sees updated data
Use `revalidateTag` instead when:
- You're in a Route Handler or other non-action context
- You want stale-while-revalidate semantics
- You're building a webhook or API endpoint for cache invalidation
## Related
- [`revalidateTag`](/docs/app/api-reference/functions/revalidateTag) - For invalidating tags in Route Handlers
- [`revalidatePath`](/docs/app/api-reference/functions/revalidatePath) - For invalidating specific paths
---
title: revalidateTag Single Argument Deprecated
---
## Why This Error Occurred
You are using `revalidateTag` without providing the second argument, which is now deprecated. The function now requires a second argument to specify the revalidation behavior.
## Possible Ways to Fix It
### Option 1: Add the second argument
Update your `revalidateTag` calls to include the second argument `"max"`:
```js
// Before (deprecated)
revalidateTag('posts')
// After
revalidateTag('posts', 'max')
```
### Option 2: Use updateTag in Server Actions
If you're calling this from a Server Action and need immediate expiration for read-your-own-writes, use `updateTag` instead:
```js
// In a Server Action
import { updateTag } from 'next/cache'
export async function createPost() {
// ... create post ...
// Immediately expire the cache
updateTag('posts')
}
```
## Revalidation Behavior
- **`revalidateTag(tag, "max")` (recommended)**: The tag entry is marked as stale, and the next time a resource with that tag is visited, it will use stale-while-revalidate semantics. This means the stale content is served while fresh content is fetched in the background.
- **`revalidateTag(tag, profile)`**: For advanced usage, you can specify any cache life profile that your application has defined in your `next.config` instead of `"max"`, allowing for custom revalidation behaviors.
- **`updateTag(tag)`**: Only available in Server Actions. The tag entry is expired immediately, and the next request to that resource will be a blocking revalidate/cache miss. This ensures read-your-own-writes consistency.
- **`revalidateTag(tag)` without second argument (deprecated)**: Same behavior as `updateTag` but shows this deprecation warning.
## Useful Links
- [revalidateTag Documentation](/docs/app/api-reference/functions/revalidateTag)
- [updateTag Documentation](/docs/app/api-reference/functions/updateTag)
- [Caching in Next.js](/docs/app/getting-started/caching-and-revalidating)
......@@ -3,8 +3,7 @@ export { unstable_cache } from 'next/dist/server/web/spec-extension/unstable-cac
export {
revalidatePath,
revalidateTag,
unstable_expirePath,
unstable_expireTag,
updateTag,
refresh,
} from 'next/dist/server/web/spec-extension/revalidate'
......
......@@ -2,16 +2,14 @@ const cacheExports = {
unstable_cache: require('next/dist/server/web/spec-extension/unstable-cache')
.unstable_cache,
updateTag: require('next/dist/server/web/spec-extension/revalidate')
.updateTag,
revalidateTag: require('next/dist/server/web/spec-extension/revalidate')
.revalidateTag,
revalidatePath: require('next/dist/server/web/spec-extension/revalidate')
.revalidatePath,
unstable_expireTag: require('next/dist/server/web/spec-extension/revalidate')
.unstable_expireTag,
unstable_expirePath: require('next/dist/server/web/spec-extension/revalidate')
.unstable_expirePath,
refresh: require('next/dist/server/web/spec-extension/revalidate').refresh,
unstable_noStore:
......@@ -30,8 +28,7 @@ module.exports = cacheExports
exports.unstable_cache = cacheExports.unstable_cache
exports.revalidatePath = cacheExports.revalidatePath
exports.revalidateTag = cacheExports.revalidateTag
exports.unstable_expireTag = cacheExports.unstable_expireTag
exports.unstable_expirePath = cacheExports.unstable_expirePath
exports.updateTag = cacheExports.updateTag
exports.unstable_noStore = cacheExports.unstable_noStore
exports.unstable_cacheLife = cacheExports.unstable_cacheLife
exports.unstable_cacheTag = cacheExports.unstable_cacheTag
......
......@@ -869,5 +869,7 @@
"868": "No reference found for param: %s in reference: %s",
"869": "No reference found for segment: %s with reference: %s",
"870": "refresh can only be called from within a Server Action. See more info here: https://nextjs.org/docs/app/api-reference/functions/refresh",
"871": "Image with src \"%s\" is using a query string which is not configured in images.localPatterns.\\nRead more: https://nextjs.org/docs/messages/next-image-unconfigured-localpatterns"
"871": "Image with src \"%s\" is using a query string which is not configured in images.localPatterns.\\nRead more: https://nextjs.org/docs/messages/next-image-unconfigured-localpatterns",
"872": "updateTag can only be called from within a Server Action. To invalidate cache tags in Route Handlers or other contexts, use revalidateTag instead. See more info here: https://nextjs.org/docs/app/api-reference/functions/updateTag",
"873": "Invalid profile provided \"%s\" must be configured under cacheLife in next.config or be \"max\""
}
......@@ -530,10 +530,9 @@ function createCustomCacheLifeDefinitions(cacheLife: {
declare module 'next/cache' {
export { unstable_cache } from 'next/dist/server/web/spec-extension/unstable-cache'
export {
updateTag,
revalidateTag,
revalidatePath,
unstable_expireTag,
unstable_expirePath,
refresh,
} from 'next/dist/server/web/spec-extension/revalidate'
export { unstable_noStore } from 'next/dist/server/web/spec-extension/unstable-no-store'
......
......@@ -346,7 +346,7 @@ async function createRedirectRenderResult(
if (workStore.pendingRevalidatedTags) {
forwardedHeaders.set(
NEXT_CACHE_REVALIDATED_TAGS_HEADER,
workStore.pendingRevalidatedTags.join(',')
workStore.pendingRevalidatedTags.map((item) => item.tag).join(',')
)
forwardedHeaders.set(
NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER,
......
......@@ -66,7 +66,10 @@ export interface WorkStore {
* Tags that were revalidated during the current request. They need to be sent
* to cache handlers to propagate their revalidation.
*/
pendingRevalidatedTags?: string[]
pendingRevalidatedTags?: Array<{
tag: string
profile?: string | { stale?: number; revalidate?: number; expire?: number }
}>
/**
* Tags that were previously revalidated (e.g. by a redirecting server action)
......
......@@ -64,7 +64,7 @@ import RenderResult from './render-result'
import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash'
import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path'
import * as Log from '../build/output/log'
import { getPreviouslyRevalidatedTags, getServerUtils } from './server-utils'
import { getServerUtils } from './server-utils'
import isError, { getProperError } from '../lib/is-error'
import {
addRequestMeta,
......@@ -141,7 +141,6 @@ import { SegmentPrefixRSCPathnameNormalizer } from './normalizers/request/segmen
import { shouldServeStreamingMetadata } from './lib/streaming-metadata'
import { decodeQueryPathParameter } from './lib/decode-query-path-parameter'
import { NoFallbackError } from '../shared/lib/no-fallback-error.external'
import { getCacheHandlers } from './use-cache/handlers'
import { fixMojibake } from './lib/fix-mojibake'
import { computeCacheBustingSearchParam } from '../shared/lib/router/utils/cache-busting-search-param'
import { setCacheBustingSearchParamWithHash } from '../client/components/router-reducer/set-cache-busting-search-param'
......@@ -1440,29 +1439,6 @@ export default abstract class Server<
;(globalThis as any).__incrementalCache = incrementalCache
}
const cacheHandlers = getCacheHandlers()
if (cacheHandlers) {
await Promise.all(
[...cacheHandlers].map(async (cacheHandler) => {
if ('refreshTags' in cacheHandler) {
// Note: cacheHandler.refreshTags() is called lazily before the
// first cache entry is retrieved. It allows us to skip the
// refresh request if no caches are read at all.
} else {
const previouslyRevalidatedTags = getPreviouslyRevalidatedTags(
req.headers,
this.getPrerenderManifest().preview.previewModeId
)
await cacheHandler.receiveExpiredTags(
...previouslyRevalidatedTags
)
}
})
)
}
// set server components HMR cache to request meta so it can be passed
// down for edge functions
if (!getRequestMeta(req, 'serverComponentsHmrCache')) {
......
......@@ -1406,7 +1406,7 @@ export const defaultConfig = Object.freeze({
max: {
stale: 60 * 5, // 5 minutes
revalidate: 60 * 60 * 24 * 30, // 1 month
expire: INFINITE_CACHE, // Unbounded.
expire: 60 * 60 * 24 * 365, // 1 year
},
},
cacheHandlers: {
......
......@@ -8,10 +8,12 @@
*/
import { LRUCache } from '../lru-cache'
import type { CacheEntry, CacheHandlerV2 } from './types'
import type { CacheEntry, CacheHandler } from './types'
import {
isStale,
areTagsExpired,
areTagsStale,
tagsManifest,
type TagManifestEntry,
} from '../incremental-cache/tags-manifest.external'
type PrivateCacheEntry = {
......@@ -45,7 +47,7 @@ const debug = process.env.NEXT_PRIVATE_DEBUG_CACHE
? console.debug.bind(console, 'DefaultCacheHandler:')
: undefined
const DefaultCacheHandler: CacheHandlerV2 = {
const DefaultCacheHandler: CacheHandler = {
async get(cacheKey) {
const pendingPromise = pendingSets.get(cacheKey)
......@@ -74,23 +76,31 @@ const DefaultCacheHandler: CacheHandlerV2 = {
return undefined
}
if (isStale(entry.tags, entry.timestamp)) {
debug?.('get', cacheKey, 'had stale tag')
let revalidate = entry.revalidate
if (areTagsExpired(entry.tags, entry.timestamp)) {
debug?.('get', cacheKey, 'had expired tag')
return undefined
}
if (areTagsStale(entry.tags, entry.timestamp)) {
debug?.('get', cacheKey, 'had stale tag')
revalidate = -1
}
const [returnStream, newSaved] = entry.value.tee()
entry.value = newSaved
debug?.('get', cacheKey, 'found', {
tags: entry.tags,
timestamp: entry.timestamp,
revalidate: entry.revalidate,
expire: entry.expire,
revalidate,
})
return {
...entry,
revalidate,
value: returnStream,
}
},
......@@ -138,23 +148,45 @@ const DefaultCacheHandler: CacheHandlerV2 = {
// Nothing to do for an in-memory cache handler.
},
async getExpiration(...tags) {
const expiration = Math.max(
...tags.map((tag) => tagsManifest.get(tag) ?? 0)
)
async getExpiration(tags) {
const expirations = tags.map((tag) => {
const entry = tagsManifest.get(tag)
if (!entry) return 0
// Return the most recent timestamp (either expired or stale)
return entry.expired || 0
})
const expiration = Math.max(...expirations, 0)
debug?.('getExpiration', { tags, expiration })
return expiration
},
async expireTags(...tags) {
const timestamp = Math.round(performance.timeOrigin + performance.now())
debug?.('expireTags', { tags, timestamp })
async updateTags(tags, durations) {
const now = Math.round(performance.timeOrigin + performance.now())
debug?.('updateTags', { tags, timestamp: now })
for (const tag of tags) {
// TODO: update file-system-cache?
tagsManifest.set(tag, timestamp)
const existingEntry = tagsManifest.get(tag) || {}
if (durations) {
// Use provided durations directly
const updates: TagManifestEntry = { ...existingEntry }
// mark as stale immediately
updates.stale = now
if (durations.expire !== undefined) {
updates.expired = now + durations.expire * 1000 // Convert seconds to ms
}
tagsManifest.set(tag, updates)
} else {
// Update expired field for immediate expiration (default behavior when no durations provided)
tagsManifest.set(tag, { ...existingEntry, expired: now })
}
}
},
}
......
......@@ -39,43 +39,7 @@ export interface CacheEntry {
revalidate: number
}
/**
* @deprecated Use {@link CacheHandlerV2} instead.
*/
export interface CacheHandler {
/**
* Retrieve a cache entry for the given cache key, if available. The softTags
* should be used to check for staleness.
*/
get(cacheKey: string, softTags: string[]): Promise<undefined | CacheEntry>
/**
* Store a cache entry for the given cache key. When this is called, the entry
* may still be pending, i.e. its value stream may still be written to. So it
* needs to be awaited first. If a `get` for the same cache key is called
* before the pending entry is complete, the cache handler must wait for the
* `set` operation to finish, before returning the entry, instead of returning
* undefined.
*/
set(cacheKey: string, entry: Promise<CacheEntry>): Promise<void>
/**
* Next.js will call this method when `revalidateTag` or `revalidatePath()` is
* called. It should update the tags manifest accordingly.
*/
expireTags(...tags: string[]): Promise<void>
/**
* The `receiveExpiredTags` method is called when an action request sends the
* 'x-next-revalidated-tags' header to indicate which tags have been expired
* by the action. The local tags manifest should be updated accordingly. As
* opposed to `expireTags`, the tags don't need to be propagated to a tags
* service, as this was already done by the server action.
*/
receiveExpiredTags(...tags: string[]): Promise<void>
}
export interface CacheHandlerV2 {
/**
* Retrieve a cache entry for the given cache key, if available. Will return
* undefined if there's no valid entry, or if the given soft tags are stale.
......@@ -106,21 +70,11 @@ export interface CacheHandlerV2 {
* Returns `Infinity` if the soft tags are supposed to be passed into the
* `get` method instead to be checked for expiration.
*/
getExpiration(...tags: string[]): Promise<Timestamp>
getExpiration(tags: string[]): Promise<Timestamp>
/**
* This function is called when tags are revalidated/expired. If applicable,
* it should update the tags manifest accordingly.
*/
expireTags(...tags: string[]): Promise<void>
updateTags(tags: string[], durations?: { expire?: number }): Promise<void>
}
/**
* This is a compatibility type to ease migration between cache handler
* versions. Until the old `CacheHandler` type is removed, this type should be
* used for all internal Next.js functions that deal with cache handlers to
* ensure that we are compatible with both cache handler versions. An exception
* is the built-in default cache handler, which implements the
* {@link CacheHandlerV2} interface.
*/
export type CacheHandlerCompat = CacheHandler | CacheHandlerV2
......@@ -62,7 +62,7 @@ function createTagsExpirationsByCacheKind(
if ('getExpiration' in cacheHandler) {
expirationsByCacheKind.set(
kind,
createLazyResult(async () => cacheHandler.getExpiration(...tags))
createLazyResult(async () => cacheHandler.getExpiration(tags))
)
}
}
......
import type { RouteMetadata } from '../../../export/routes/types'
import type { CacheHandler, CacheHandlerContext, CacheHandlerValue } from '.'
import type { CacheFs } from '../../../shared/lib/utils'
import type { TagManifestEntry } from './tags-manifest.external'
import {
CachedRouteKind,
IncrementalCacheKind,
......@@ -21,7 +22,7 @@ import {
RSC_SEGMENTS_DIR_SUFFIX,
RSC_SUFFIX,
} from '../../../lib/constants'
import { isStale, tagsManifest } from './tags-manifest.external'
import { areTagsExpired, tagsManifest } from './tags-manifest.external'
import { MultiFileWriter } from '../../../lib/multi-file-writer'
import { getMemoryCache } from './memory-cache.external'
......@@ -65,22 +66,39 @@ export default class FileSystemCache implements CacheHandler {
public resetRequestCache(): void {}
public async revalidateTag(
...args: Parameters<CacheHandler['revalidateTag']>
tags: string | string[],
durations?: { expire?: number }
) {
let [tags] = args
tags = typeof tags === 'string' ? [tags] : tags
if (FileSystemCache.debug) {
console.log('FileSystemCache: revalidateTag', tags)
console.log('FileSystemCache: revalidateTag', tags, durations)
}
if (tags.length === 0) {
return
}
const now = Date.now()
for (const tag of tags) {
if (!tagsManifest.has(tag)) {
tagsManifest.set(tag, Date.now())
const existingEntry = tagsManifest.get(tag) || {}
if (durations) {
// Use provided durations directly
const updates: TagManifestEntry = { ...existingEntry }
// mark as stale immediately
updates.stale = now
if (durations.expire !== undefined) {
updates.expired = now + durations.expire * 1000 // Convert seconds to ms
}
tagsManifest.set(tag, updates)
} else {
// Update expired field for immediate expiration (default behavior when no durations provided)
tagsManifest.set(tag, { ...existingEntry, expired: now })
}
}
}
......@@ -297,9 +315,12 @@ export default class FileSystemCache implements CacheHandler {
// we trigger a blocking validation if an ISR page
// had a tag revalidated, if we want to be a background
// revalidation instead we return data.lastModified = -1
if (cacheTags.length > 0 && isStale(cacheTags, data.lastModified)) {
if (
cacheTags.length > 0 &&
areTagsExpired(cacheTags, data.lastModified)
) {
if (FileSystemCache.debug) {
console.log('FileSystemCache: stale tags', cacheTags)
console.log('FileSystemCache: expired tags', cacheTags)
}
return null
......@@ -321,9 +342,9 @@ export default class FileSystemCache implements CacheHandler {
return null
}
if (isStale(combinedTags, data.lastModified)) {
if (areTagsExpired(combinedTags, data.lastModified)) {
if (FileSystemCache.debug) {
console.log('FileSystemCache: stale tags', combinedTags)
console.log('FileSystemCache: expired tags', combinedTags)
}
return null
......
......@@ -35,7 +35,7 @@ import type { Revalidate } from '../cache-control'
import { getPreviouslyRevalidatedTags } from '../../server-utils'
import { workAsyncStorage } from '../../app-render/work-async-storage.external'
import { DetachedPromise } from '../../../lib/detached-promise'
import { isStale as isTagsStale } from './tags-manifest.external'
import { areTagsExpired, areTagsStale } from './tags-manifest.external'
export interface CacheHandlerContext {
fs?: CacheFs
......@@ -74,7 +74,8 @@ export class CacheHandler {
): Promise<void> {}
public async revalidateTag(
..._args: Parameters<IncrementalCache['revalidateTag']>
_tags: string | string[],
_durations?: { expire?: number }
): Promise<void> {}
public resetRequestCache(): void {}
......@@ -278,8 +279,11 @@ export class IncrementalCache implements IncrementalCacheType {
}
}
async revalidateTag(tags: string | string[]): Promise<void> {
return this.cacheHandler?.revalidateTag(tags)
async revalidateTag(
tags: string | string[],
durations?: { expire?: number }
): Promise<void> {
return this.cacheHandler?.revalidateTag(tags, durations)
}
// x-ref: https://github.com/facebook/react/blob/2655c9354d8e1c54ba888444220f63e836925caa/packages/react/src/ReactFetch.js#L23
......@@ -485,11 +489,11 @@ export class IncrementalCache implements IncrementalCacheType {
combinedTags.some(
(tag) =>
this.revalidatedTags?.includes(tag) ||
workStore?.pendingRevalidatedTags?.includes(tag)
workStore?.pendingRevalidatedTags?.some((item) => item.tag === tag)
)
) {
if (IncrementalCache.debug) {
console.log('IncrementalCache: stale tag', cacheKey)
console.log('IncrementalCache: expired tag', cacheKey)
}
return null
......@@ -523,9 +527,15 @@ export class IncrementalCache implements IncrementalCacheType {
(cacheData.lastModified || 0)) /
1000
const isStale = age > revalidate
let isStale = age > revalidate
const data = cacheData.value.data
if (areTagsExpired(combinedTags, cacheData.lastModified)) {
return null
} else if (areTagsStale(combinedTags, cacheData.lastModified)) {
isStale = true
}
return {
isStale,
value: { kind: CachedRouteKind.FETCH, data, revalidate },
......@@ -560,7 +570,7 @@ export class IncrementalCache implements IncrementalCacheType {
revalidateAfter !== false && revalidateAfter < now ? true : undefined
// If the stale time couldn't be determined based on the revalidation
// time, we check if the tags are stale.
// time, we check if the tags are expired or stale.
if (
isStale === undefined &&
(cacheData?.value?.kind === CachedRouteKind.APP_PAGE ||
......@@ -570,8 +580,13 @@ export class IncrementalCache implements IncrementalCacheType {
if (typeof tagsHeader === 'string') {
const cacheTags = tagsHeader.split(',')
if (cacheTags.length > 0 && isTagsStale(cacheTags, lastModified)) {
isStale = -1
if (cacheTags.length > 0) {
if (areTagsExpired(cacheTags, lastModified)) {
isStale = -1
} else if (areTagsStale(cacheTags, lastModified)) {
isStale = true
}
}
}
}
......
import type { Timestamp } from '../cache-handlers/types'
export interface TagManifestEntry {
stale?: number
expired?: number
}
// We share the tags manifest between the "use cache" handlers and the previous
// file-system cache.
export const tagsManifest = new Map<string, number>()
export const tagsManifest = new Map<string, TagManifestEntry>()
export const areTagsExpired = (tags: string[], timestamp: Timestamp) => {
for (const tag of tags) {
const entry = tagsManifest.get(tag)
if (entry) {
if (entry.expired && entry.expired >= timestamp) {
return true
}
}
}
return false
}
export const isStale = (tags: string[], timestamp: Timestamp) => {
export const areTagsStale = (tags: string[], timestamp: Timestamp) => {
for (const tag of tags) {
const revalidatedAt = tagsManifest.get(tag)
const entry = tagsManifest.get(tag)
if (typeof revalidatedAt === 'number' && revalidatedAt >= timestamp) {
return true
if (entry) {
if (entry.stale && entry.stale >= timestamp) {
return true
}
}
}
......
......@@ -289,4 +289,8 @@ export interface IncrementalCache extends IncrementalResponseCache {
data: Exclude<IncrementalCacheValue, CachedFetchValue> | null,
ctx: SetIncrementalResponseCacheContext
): Promise<void>
revalidateTag(
tags: string | string[],
durations?: { expire?: number }
): Promise<void>
}
......@@ -48,12 +48,24 @@ function diffRevalidationState(
prev: RevalidationState,
curr: RevalidationState
): RevalidationState {
const prevTags = new Set(prev.pendingRevalidatedTags)
const prevTagsWithProfile = new Set(
prev.pendingRevalidatedTags.map((item) => {
const profileKey =
typeof item.profile === 'object'
? JSON.stringify(item.profile)
: item.profile || ''
return `${item.tag}:${profileKey}`
})
)
const prevRevalidateWrites = new Set(prev.pendingRevalidateWrites)
return {
pendingRevalidatedTags: curr.pendingRevalidatedTags.filter(
(tag) => !prevTags.has(tag)
),
pendingRevalidatedTags: curr.pendingRevalidatedTags.filter((item) => {
const profileKey =
typeof item.profile === 'object'
? JSON.stringify(item.profile)
: item.profile || ''
return !prevTagsWithProfile.has(`${item.tag}:${profileKey}`)
}),
pendingRevalidates: Object.fromEntries(
Object.entries(curr.pendingRevalidates).filter(
([key]) => !(key in prev.pendingRevalidates)
......@@ -66,23 +78,105 @@ function diffRevalidationState(
}
async function revalidateTags(
tags: string[],
incrementalCache: IncrementalCache | undefined
tagsWithProfile: Array<{
tag: string
profile?: string | { expire?: number }
}>,
incrementalCache: IncrementalCache | undefined,
workStore?: WorkStore
): Promise<void> {
if (tags.length === 0) {
if (tagsWithProfile.length === 0) {
return
}
const handlers = getCacheHandlers()
const promises: Promise<void>[] = []
if (incrementalCache) {
promises.push(incrementalCache.revalidateTag(tags))
// Group tags by profile for batch processing
const tagsByProfile = new Map<
| string
| { stale?: number; revalidate?: number; expire?: number }
| undefined,
string[]
>()
for (const item of tagsWithProfile) {
const profile = item.profile
// Find existing profile by comparing values
let existingKey = undefined
for (const [key] of tagsByProfile) {
if (
typeof key === 'string' &&
typeof profile === 'string' &&
key === profile
) {
existingKey = key
break
}
if (
typeof key === 'object' &&
typeof profile === 'object' &&
JSON.stringify(key) === JSON.stringify(profile)
) {
existingKey = key
break
}
if (key === profile) {
existingKey = key
break
}
}
const profileKey = existingKey || profile
if (!tagsByProfile.has(profileKey)) {
tagsByProfile.set(profileKey, [])
}
tagsByProfile.get(profileKey)!.push(item.tag)
}
const handlers = getCacheHandlers()
if (handlers) {
for (const handler of handlers) {
promises.push(handler.expireTags(...tags))
// Process each profile group
for (const [profile, tagsForProfile] of tagsByProfile) {
// Look up the cache profile from workStore if available
let durations: { expire?: number } | undefined
if (profile) {
let cacheLife:
| { stale?: number; revalidate?: number; expire?: number }
| undefined
if (typeof profile === 'object') {
// Profile is already a cacheLife configuration object
cacheLife = profile
} else if (typeof profile === 'string') {
// Profile is a string key, look it up in workStore
cacheLife = workStore?.cacheLifeProfiles?.[profile]
if (!cacheLife) {
throw new Error(
`Invalid profile provided "${profile}" must be configured under cacheLife in next.config or be "max"`
)
}
}
if (cacheLife) {
durations = {
expire: cacheLife.expire,
}
}
}
// If profile is not found and not 'max', durations will be undefined
// which will trigger immediate expiration in the cache handler
for (const handler of handlers || []) {
if (profile) {
promises.push(handler.updateTags?.(tagsForProfile, durations))
} else {
promises.push(handler.updateTags?.(tagsForProfile))
}
}
if (incrementalCache) {
promises.push(incrementalCache.revalidateTag(tagsForProfile, durations))
}
}
......@@ -103,7 +197,11 @@ export async function executeRevalidates(
state?.pendingRevalidateWrites ?? workStore.pendingRevalidateWrites ?? []
return Promise.all([
revalidateTags(pendingRevalidatedTags, workStore.incrementalCache),
revalidateTags(
pendingRevalidatedTags,
workStore.incrementalCache,
workStore
),
...Object.values(pendingRevalidates),
...pendingRevalidateWrites,
])
......
import DefaultCacheHandler from '../lib/cache-handlers/default.external'
import type { CacheHandlerCompat } from '../lib/cache-handlers/types'
import type { CacheHandler } from '../lib/cache-handlers/types'
const debug = process.env.NEXT_PRIVATE_DEBUG_CACHE
? (message: string, ...args: any[]) => {
......@@ -18,11 +18,11 @@ const handlersSetSymbol = Symbol.for('@next/cache-handlers-set')
*/
const reference: typeof globalThis & {
[handlersSymbol]?: {
RemoteCache?: CacheHandlerCompat
DefaultCache?: CacheHandlerCompat
RemoteCache?: CacheHandler
DefaultCache?: CacheHandler
}
[handlersMapSymbol]?: Map<string, CacheHandlerCompat>
[handlersSetSymbol]?: Set<CacheHandlerCompat>
[handlersMapSymbol]?: Map<string, CacheHandler>
[handlersSetSymbol]?: Set<CacheHandler>
} = globalThis
/**
......@@ -37,11 +37,11 @@ export function initializeCacheHandlers(): boolean {
}
debug?.('initializing cache handlers')
reference[handlersMapSymbol] = new Map<string, CacheHandlerCompat>()
reference[handlersMapSymbol] = new Map<string, CacheHandler>()
// Initialize the cache from the symbol contents first.
if (reference[handlersSymbol]) {
let fallback: CacheHandlerCompat
let fallback: CacheHandler
if (reference[handlersSymbol].DefaultCache) {
debug?.('setting "default" cache handler from symbol')
fallback = reference[handlersSymbol].DefaultCache
......@@ -81,7 +81,7 @@ export function initializeCacheHandlers(): boolean {
* @returns The cache handler, or `undefined` if it does not exist.
* @throws If the cache handlers are not initialized.
*/
export function getCacheHandler(kind: string): CacheHandlerCompat | undefined {
export function getCacheHandler(kind: string): CacheHandler | undefined {
// This should never be called before initializeCacheHandlers.
if (!reference[handlersMapSymbol]) {
throw new Error('Cache handlers not initialized')
......@@ -95,9 +95,7 @@ export function getCacheHandler(kind: string): CacheHandlerCompat | undefined {
* @returns An iterator over the cache handlers, or `undefined` if they are not
* initialized.
*/
export function getCacheHandlers():
| SetIterator<CacheHandlerCompat>
| undefined {
export function getCacheHandlers(): SetIterator<CacheHandler> | undefined {
if (!reference[handlersSetSymbol]) {
return undefined
}
......@@ -112,7 +110,7 @@ export function getCacheHandlers():
* @throws If the cache handlers are not initialized.
*/
export function getCacheHandlerEntries():
| MapIterator<[string, CacheHandlerCompat]>
| MapIterator<[string, CacheHandler]>
| undefined {
if (!reference[handlersMapSymbol]) {
return undefined
......@@ -128,7 +126,7 @@ export function getCacheHandlerEntries():
*/
export function setCacheHandler(
kind: string,
cacheHandler: CacheHandlerCompat
cacheHandler: CacheHandler
): void {
// This should never be called before initializeCacheHandlers.
if (!reference[handlersMapSymbol] || !reference[handlersSetSymbol]) {
......
......@@ -1394,7 +1394,7 @@ export function cache(
implicitTagsExpiration
)
) {
debug?.('discarding stale entry', serializedCacheKey)
debug?.('discarding expired entry', serializedCacheKey)
entry = undefined
}
}
......@@ -1755,7 +1755,7 @@ function isRecentlyRevalidatedTag(tag: string, workStore: WorkStore): boolean {
// In this case the revalidation might not have been fully propagated by a
// remote cache handler yet, so we read it from the pending tags in the work
// store.
if (pendingRevalidatedTags?.includes(tag)) {
if (pendingRevalidatedTags?.some((item) => item.tag === tag)) {
debug?.('tag', tag, 'was just revalidated')
return true
......
......@@ -12,47 +12,44 @@ import { workUnitAsyncStorage } from '../../app-render/work-unit-async-storage.e
import { DynamicServerError } from '../../../client/components/hooks-server-context'
import { InvariantError } from '../../../shared/lib/invariant-error'
type CacheLifeConfig = {
expire?: number
}
/**
* This function allows you to purge [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific cache tag.
*
* Read more: [Next.js Docs: `revalidateTag`](https://nextjs.org/docs/app/api-reference/functions/revalidateTag)
*/
export function revalidateTag(tag: string) {
return revalidate([tag], `revalidateTag ${tag}`)
export function revalidateTag(tag: string, profile: string | CacheLifeConfig) {
if (!profile) {
console.warn(
'"revalidateTag" without the second argument is now deprecated, add second argument of "max" or use "updateTag". See more info here: https://nextjs.org/docs/messages/revalidate-tag-single-arg'
)
}
return revalidate([tag], `revalidateTag ${tag}`, profile)
}
/**
* This function allows you to purge [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific path.
* This function allows you to update [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific cache tag.
* This can only be called from within a Server Action to enable read-your-own-writes semantics.
*
* Read more: [Next.js Docs: `unstable_expirePath`](https://nextjs.org/docs/app/api-reference/functions/unstable_expirePath)
* Read more: [Next.js Docs: `updateTag`](https://nextjs.org/docs/app/api-reference/functions/updateTag)
*/
export function unstable_expirePath(
originalPath: string,
type?: 'layout' | 'page'
) {
if (originalPath.length > NEXT_CACHE_SOFT_TAG_MAX_LENGTH) {
console.warn(
`Warning: expirePath received "${originalPath}" which exceeded max length of ${NEXT_CACHE_SOFT_TAG_MAX_LENGTH}. See more info here https://nextjs.org/docs/app/api-reference/functions/unstable_expirePath`
)
return
}
let normalizedPath = `${NEXT_CACHE_IMPLICIT_TAG_ID}${originalPath || '/'}`
export function updateTag(tag: string) {
const workStore = workAsyncStorage.getStore()
if (type) {
normalizedPath += `${normalizedPath.endsWith('/') ? '' : '/'}${type}`
} else if (isDynamicRoute(originalPath)) {
console.warn(
`Warning: a dynamic page path "${originalPath}" was passed to "expirePath", but the "type" parameter is missing. This has no effect by default, see more info here https://nextjs.org/docs/app/api-reference/functions/unstable_expirePath`
// TODO: change this after investigating why phase: 'action' is
// set for route handlers
if (!workStore || workStore.page.endsWith('/route')) {
throw new Error(
'updateTag can only be called from within a Server Action. ' +
'To invalidate cache tags in Route Handlers or other contexts, use revalidateTag instead. ' +
'See more info here: https://nextjs.org/docs/app/api-reference/functions/updateTag'
)
}
const tags = [normalizedPath]
if (normalizedPath === `${NEXT_CACHE_IMPLICIT_TAG_ID}/`) {
tags.push(`${NEXT_CACHE_IMPLICIT_TAG_ID}/index`)
} else if (normalizedPath === `${NEXT_CACHE_IMPLICIT_TAG_ID}/index`) {
tags.push(`${NEXT_CACHE_IMPLICIT_TAG_ID}/`)
}
return revalidate(tags, `unstable_expirePath ${originalPath}`)
// updateTag uses immediate expiration (no profile) without deprecation warning
return revalidate([tag], `updateTag ${tag}`, undefined)
}
/**
......@@ -81,15 +78,6 @@ export function refresh() {
}
}
/**
* This function allows you to purge [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific cache tag.
*
* Read more: [Next.js Docs: `unstable_expireTag`](https://nextjs.org/docs/app/api-reference/functions/unstable_expireTag)
*/
export function unstable_expireTag(...tags: string[]) {
return revalidate(tags, `unstable_expireTag ${tags.join(', ')}`)
}
/**
* This function allows you to purge [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific path.
*
......@@ -123,7 +111,11 @@ export function revalidatePath(originalPath: string, type?: 'layout' | 'page') {
return revalidate(tags, `revalidatePath ${originalPath}`)
}
function revalidate(tags: string[], expression: string) {
function revalidate(
tags: string[],
expression: string,
profile?: string | CacheLifeConfig
) {
const store = workAsyncStorage.getStore()
if (!store || !store.incrementalCache) {
throw new Error(
......@@ -199,11 +191,39 @@ function revalidate(tags: string[], expression: string) {
}
for (const tag of tags) {
if (!store.pendingRevalidatedTags.includes(tag)) {
store.pendingRevalidatedTags.push(tag)
const existingIndex = store.pendingRevalidatedTags.findIndex((item) => {
if (item.tag !== tag) return false
// Compare profiles: both strings, both objects, or both undefined
if (typeof item.profile === 'string' && typeof profile === 'string') {
return item.profile === profile
}
if (typeof item.profile === 'object' && typeof profile === 'object') {
return JSON.stringify(item.profile) === JSON.stringify(profile)
}
return item.profile === profile
})
if (existingIndex === -1) {
store.pendingRevalidatedTags.push({
tag,
profile,
})
}
}
// TODO: only revalidate if the path matches
store.pathWasRevalidated = true
// if profile is provided and this is a stale-while-revalidate
// update we do not mark the path as revalidated so that server
// actions don't pull their own writes
const cacheLife =
profile && typeof profile === 'object'
? profile
: profile &&
typeof profile === 'string' &&
store?.cacheLifeProfiles?.[profile]
? store.cacheLifeProfiles[profile]
: undefined
if (!profile || cacheLife?.expire === 0) {
// TODO: only revalidate if the path matches
store.pathWasRevalidated = true
}
}
......@@ -5,20 +5,20 @@
"failed": [
"app-dir action handling fetch actions should invalidate client cache when path is revalidated",
"app-dir action handling fetch actions should invalidate client cache when tag is revalidated",
"app-dir action handling fetch actions should handle unstable_expireTag"
"app-dir action handling fetch actions should handle revalidateTag"
]
},
"test/e2e/app-dir/actions/app-action-node-middleware.test.ts": {
"failed": [
"app-dir action handling fetch actions should invalidate client cache when path is revalidated",
"app-dir action handling fetch actions should invalidate client cache when tag is revalidated",
"app-dir action handling fetch actions should handle unstable_expireTag"
"app-dir action handling fetch actions should handle revalidateTag"
]
},
"test/e2e/app-dir/app-static/app-static.test.ts": {
"failed": [
"app-dir static/dynamic handling new tags have been specified on subsequent fetch should not fetch from memory cache",
"app-dir static/dynamic handling new tags have been specified on subsequent fetch should not fetch from memory cache after unstable_expireTag is used"
"app-dir static/dynamic handling new tags have been specified on subsequent fetch should not fetch from memory cache after revalidateTag is used"
]
},
"test/e2e/app-dir/metadata/metadata.test.ts": {
......
'use client'
import { unstable_expirePath } from 'next/cache'
console.log({ unstable_expirePath })
export default function Page() {
return null
}
'use client'
import { unstable_expireTag } from 'next/cache'
console.log({ unstable_expireTag })
export default function Page() {
return null
}
......@@ -284,8 +284,6 @@ describe('Error overlay - RSC build errors', () => {
'revalidateTag',
'unstable_cacheLife',
'unstable_cacheTag',
'unstable_expirePath',
'unstable_expireTag',
])('%s is not allowed', async (api) => {
await using sandbox = await createSandbox(
next,
......
......@@ -386,8 +386,8 @@ describe('Error Overlay for server components compiler errors in pages', () => {
'revalidateTag',
'unstable_cacheLife',
'unstable_cacheTag',
'unstable_expirePath',
'unstable_expireTag',
'revalidatePath',
'revalidateTag',
])('%s is not allowed', async (api) => {
await using sandbox = await createSandbox(next, initialFiles)
const { session } = sandbox
......
import {
unstable_expireTag,
revalidateTag,
unstable_cacheLife as cacheLife,
unstable_cacheTag,
} from 'next/cache'
......@@ -13,7 +13,7 @@ function InnerComponent({ children }) {
async function refresh() {
'use server'
unstable_expireTag('hello')
revalidateTag('hello')
}
async function reload() {
......
import React from 'react'
import { unstable_expirePath } from 'next/cache'
import { revalidatePath } from 'next/cache'
export default async function HomePage() {
await new Promise((resolve) => setTimeout(resolve, 200))
......@@ -9,7 +9,7 @@ export default async function HomePage() {
<form
action={async () => {
'use server'
unstable_expirePath('/test')
revalidatePath('/test')
}}
>
<button>Submit</button>
......
......@@ -1301,7 +1301,7 @@ describe('app-dir action handling', () => {
}, 5000)
})
it('should handle unstable_expirePath', async () => {
it('should handle revalidatePath', async () => {
const browser = await next.browser('/revalidate')
const randomNumber = await browser.elementByCss('#random-number').text()
const justPutIt = await browser.elementByCss('#justputit').text()
......@@ -1324,7 +1324,7 @@ describe('app-dir action handling', () => {
})
})
it('should handle unstable_expireTag', async () => {
it('should handle revalidateTag', async () => {
const browser = await next.browser('/revalidate')
const randomNumber = await browser.elementByCss('#random-number').text()
const justPutIt = await browser.elementByCss('#justputit').text()
......@@ -1348,7 +1348,7 @@ describe('app-dir action handling', () => {
})
// TODO: investigate flakey behavior with revalidate
it.skip('should handle unstable_expireTag + redirect', async () => {
it.skip('should handle revalidateTag + redirect', async () => {
const browser = await next.browser('/revalidate')
const randomNumber = await browser.elementByCss('#random-number').text()
const justPutIt = await browser.elementByCss('#justputit').text()
......
'use server'
import { revalidateTag } from 'next/cache'
import { updateTag } from 'next/cache'
export async function slowAction() {
await new Promise((resolve) => setTimeout(resolve, 2000))
......@@ -9,6 +9,6 @@ export async function slowAction() {
export async function slowActionWithRevalidation() {
await new Promise((resolve) => setTimeout(resolve, 2000))
revalidateTag('cached-random')
updateTag('cached-random')
return 'slow action with revalidation completed'
}
'use server'
import { unstable_expirePath } from 'next/cache'
import { revalidatePath } from 'next/cache'
import { redirect } from 'next/navigation'
export const action = async () => {
console.log('revalidating')
unstable_expirePath('/delayed-action', 'page')
revalidatePath('/delayed-action', 'page')
return Math.random()
}
......
'use server'
import { redirect } from 'next/navigation'
import { unstable_expirePath } from 'next/cache'
import { revalidatePath } from 'next/cache'
type State = {
errors: Record<string, string>
......@@ -16,7 +16,7 @@ export async function action(previousState: State, formData: FormData) {
}
if (revalidate === 'on') {
unstable_expirePath('/redirect')
revalidatePath('/redirect')
}
redirect('/redirect/other')
......
import { unstable_expireTag } from 'next/cache'
import { updateTag } from 'next/cache'
import { cookies } from 'next/headers'
import Link from 'next/link'
......@@ -26,7 +26,7 @@ export default async function Page() {
id="revalidate-tag"
formAction={async () => {
'use server'
unstable_expireTag('thankyounext')
updateTag('thankyounext')
}}
>
revalidate thankyounext
......
import { unstable_expireTag } from 'next/cache'
import { updateTag } from 'next/cache'
export default async function Page() {
const data1 = await fetch(
......@@ -29,8 +29,8 @@ export default async function Page() {
id="revalidate"
formAction={async () => {
'use server'
unstable_expireTag('thankyounext')
unstable_expireTag('justputit')
updateTag('thankyounext')
updateTag('justputit')
}}
>
revalidate thankyounext
......
import { unstable_expirePath, unstable_expireTag } from 'next/cache'
import { revalidatePath, updateTag } from 'next/cache'
import { redirect } from 'next/navigation'
import Link from 'next/link'
......@@ -59,7 +59,7 @@ export default async function Page() {
id="revalidate-thankyounext"
formAction={async () => {
'use server'
unstable_expireTag('thankyounext')
updateTag('thankyounext')
}}
>
revalidate thankyounext
......@@ -70,7 +70,7 @@ export default async function Page() {
id="revalidate-justputit"
formAction={async () => {
'use server'
unstable_expireTag('justputit')
updateTag('justputit')
}}
>
revalidate justputit
......@@ -81,7 +81,7 @@ export default async function Page() {
id="revalidate-path"
formAction={async () => {
'use server'
unstable_expirePath('/revalidate')
revalidatePath('/revalidate')
}}
>
revalidate path
......@@ -92,7 +92,7 @@ export default async function Page() {
id="revalidate-path-redirect"
formAction={async () => {
'use server'
unstable_expireTag('justputit')
updateTag('justputit')
redirect('/revalidate')
}}
>
......@@ -115,7 +115,7 @@ export default async function Page() {
id="redirect-revalidate"
formAction={async () => {
'use server'
unstable_expireTag('justputit')
updateTag('justputit')
redirect('/revalidate?foo=bar')
}}
>
......@@ -125,7 +125,7 @@ export default async function Page() {
<RedirectClientComponent
action={async () => {
'use server'
unstable_expireTag('justputit')
updateTag('justputit')
}}
/>
</>
......
'use server'
import { unstable_expirePath } from 'next/cache'
import { revalidatePath } from 'next/cache'
let x = 0
export async function inc() {
++x
unstable_expirePath('/shared')
revalidatePath('/shared')
}
export async function get() {
......
......@@ -169,7 +169,7 @@ describe('app-dir static/dynamic handling', () => {
expect(data1).not.toBe(data2)
})
it('should not fetch from memory cache after unstable_expireTag is used', async () => {
it('should not fetch from memory cache after revalidateTag is used', async () => {
const res1 = await next.fetch('/specify-new-tags/one-tag')
expect(res1.status).toBe(200)
......@@ -1162,6 +1162,12 @@ describe('app-dir static/dynamic handling', () => {
"unstable-cache/fetch/no-store.segments/unstable-cache/fetch.segment.rsc",
"unstable-cache/fetch/no-store.segments/unstable-cache/fetch/no-store.segment.rsc",
"unstable-cache/fetch/no-store.segments/unstable-cache/fetch/no-store/__PAGE__.segment.rsc",
"update-tag-test.html",
"update-tag-test.rsc",
"update-tag-test.segments/_index.segment.rsc",
"update-tag-test.segments/_tree.segment.rsc",
"update-tag-test.segments/update-tag-test.segment.rsc",
"update-tag-test.segments/update-tag-test/__PAGE__.segment.rsc",
"variable-config-revalidate/revalidate-3.html",
"variable-config-revalidate/revalidate-3.rsc",
"variable-config-revalidate/revalidate-3.segments/_index.segment.rsc",
......@@ -2557,6 +2563,31 @@ describe('app-dir static/dynamic handling', () => {
"prefetchDataRoute": null,
"srcRoute": "/unstable-cache/fetch/no-store",
},
"/update-tag-test": {
"allowHeader": [
"host",
"x-matched-path",
"x-prerender-revalidate",
"x-prerender-revalidate-if-generated",
"x-next-revalidated-tags",
"x-next-revalidate-tag-token",
],
"dataRoute": "/update-tag-test.rsc",
"experimentalBypassFor": [
{
"key": "next-action",
"type": "header",
},
{
"key": "content-type",
"type": "header",
"value": "multipart/form-data;.*",
},
],
"initialRevalidateSeconds": false,
"prefetchDataRoute": null,
"srcRoute": "/update-tag-test",
},
"/variable-config-revalidate/revalidate-3": {
"allowHeader": [
"host",
......@@ -4884,4 +4915,72 @@ describe('app-dir static/dynamic handling', () => {
const browser = await next.browser('/dynamic-param-edge/hello')
expect(await browser.elementByCss('#slug').text()).toBe('hello')
})
describe('updateTag', () => {
it('should throw error when updateTag is called in route handler', async () => {
const res = await next.fetch('/api/update-tag-error')
const data = await res.json()
expect(data.error).toContain(
'updateTag can only be called from within a Server Action'
)
})
it('should successfully update tag when called from server action', async () => {
// First fetch to get initial data
const browser = await next.browser('/update-tag-test')
const initialData = JSON.parse(await browser.elementByCss('#data').text())
await retry(async () => {
// Click update button to trigger server action with updateTag
await browser.elementByCss('#update-button').click()
// Refresh the page to see if cache was invalidated
await browser.refresh()
const newData = JSON.parse(await browser.elementByCss('#data').text())
// Data should be different after updateTag (immediate expiration)
expect(newData).not.toEqual(initialData)
})
})
it('should use revalidateTag with max profile in server actions', async () => {
// First fetch to get initial data
const browser = await next.browser('/update-tag-test')
const initialData = JSON.parse(await browser.elementByCss('#data').text())
// Click revalidate button to trigger server action with revalidateTag(..., 'max')
await browser.elementByCss('#revalidate-button').click()
// The behavior with 'max' profile would be stale-while-revalidate
// Initial request after revalidation might still show stale data
await retry(async () => {
await browser.refresh()
const dataAfterRevalidate = JSON.parse(
await browser.elementByCss('#data').text()
)
expect(dataAfterRevalidate).toBeDefined()
expect(dataAfterRevalidate).not.toBe(initialData)
})
})
// Runtime logs aren't queryable in deploy mode
if (!isNextDeploy) {
it('should show deprecation warning for revalidateTag without second argument', async () => {
const cliOutputStart = next.cliOutput.length
const browser = await next.browser('/update-tag-test')
await retry(async () => {
// Click deprecated button to trigger server action with revalidateTag (no second arg)
await browser.elementByCss('#deprecated-button').click()
const output = next.cliOutput.substring(cliOutputStart)
expect(output).toContain(
'"revalidateTag" without the second argument is now deprecated'
)
})
})
}
})
})
import { NextRequest, NextResponse } from 'next/server'
import { unstable_expirePath } from 'next/cache'
import { revalidatePath } from 'next/cache'
export const runtime = 'edge'
......@@ -7,7 +7,7 @@ export async function GET(req: NextRequest) {
const path = req.nextUrl.searchParams.get('path') || '/'
try {
console.log('revalidating path', path)
unstable_expirePath(path)
revalidatePath(path)
return NextResponse.json({ revalidated: true, now: Date.now() })
} catch (err) {
console.error('Failed to revalidate', path, err)
......
import { NextRequest, NextResponse } from 'next/server'
import { unstable_expirePath } from 'next/cache'
import { revalidatePath } from 'next/cache'
export const revalidate = 1
......@@ -7,7 +7,7 @@ export async function GET(req: NextRequest) {
const path = req.nextUrl.searchParams.get('path') || '/'
try {
console.log('revalidating path', path)
unstable_expirePath(path)
revalidatePath(path)
return NextResponse.json({ revalidated: true, now: Date.now() })
} catch (err) {
console.error('Failed to revalidate', path, err)
......
import { NextResponse } from 'next/server'
import { unstable_expireTag } from 'next/cache'
import { revalidateTag } from 'next/cache'
export const revalidate = 0
export const runtime = 'edge'
export async function GET(req) {
const tag = req.nextUrl.searchParams.get('tag')
unstable_expireTag(tag)
revalidateTag(tag, { expire: 0 })
return NextResponse.json({ revalidated: true, now: Date.now() })
}
import { NextResponse } from 'next/server'
import { unstable_expireTag } from 'next/cache'
import { revalidateTag } from 'next/cache'
export const revalidate = 0
export async function GET(req) {
const tag = req.nextUrl.searchParams.get('tag')
unstable_expireTag(tag)
revalidateTag(tag, 'expireNow')
return NextResponse.json({ revalidated: true, now: Date.now() })
}
import { NextResponse } from 'next/server'
import { updateTag } from 'next/cache'
export async function GET() {
try {
// This should throw an error - updateTag cannot be used in route handlers
updateTag('test-tag')
return NextResponse.json({ error: 'Should not reach here' })
} catch (error: unknown) {
return NextResponse.json(
{
error:
(error &&
typeof error === 'object' &&
'message' in error &&
error.message) ||
'unknown error',
expectedError: true,
},
{ status: 500 }
)
}
}
import { unstable_expireTag, unstable_cache } from 'next/cache'
import { updateTag, unstable_cache } from 'next/cache'
import { getUncachedRandomData } from '../no-store-fn'
import { RevalidateButton } from '../revalidate-button'
export default async function Page() {
async function revalidate() {
'use server'
await unstable_expireTag('no-store-fn')
await updateTag('no-store-fn')
}
const cachedData = await unstable_cache(
......
import { unstable_expireTag, unstable_cache } from 'next/cache'
import { updateTag, unstable_cache } from 'next/cache'
import { RevalidateButton } from '../revalidate-button'
export const dynamic = 'force-dynamic'
......@@ -6,7 +6,7 @@ export const dynamic = 'force-dynamic'
export default async function Page() {
async function revalidate() {
'use server'
await unstable_expireTag('undefined-value-data')
await updateTag('undefined-value-data')
}
const cachedData = await unstable_cache(
......
import { draftMode } from 'next/headers'
import { unstable_expireTag, unstable_cache } from 'next/cache'
import { updateTag, unstable_cache } from 'next/cache'
import { RevalidateButton } from '../revalidate-button'
export const dynamic = 'force-dynamic'
......@@ -7,7 +7,7 @@ export const dynamic = 'force-dynamic'
export default async function Page() {
async function revalidate() {
'use server'
await unstable_expireTag('random-value-data')
await updateTag('random-value-data')
}
const cachedData = await unstable_cache(
......
'use server'
import { revalidateTag, updateTag } from 'next/cache'
export async function updateAction() {
// This should work - updateTag in server action
updateTag('test-update-tag')
return { updated: true, timestamp: Date.now() }
}
export async function revalidateAction() {
// This should work with second argument
revalidateTag('test-update-tag', 'max')
return { revalidated: true, timestamp: Date.now() }
}
export async function deprecatedRevalidateAction() {
// @ts-expect-error This should show deprecation warning
revalidateTag('test-update-tag')
return { revalidated: true, timestamp: Date.now() }
}
'use client'
import {
updateAction,
revalidateAction,
deprecatedRevalidateAction,
} from './actions'
export function Buttons() {
return (
<>
<button type="button" id="update-button" onClick={() => updateAction()}>
Update Tag
</button>
<button
type="button"
id="revalidate-button"
onClick={() => revalidateAction()}
>
Revalidate Tag
</button>
<button
type="button"
id="deprecated-button"
onClick={() => deprecatedRevalidateAction()}
>
Deprecated Revalidate
</button>
</>
)
}
import { unstable_cache } from 'next/cache'
import { Buttons } from './buttons'
const getTimestamp = unstable_cache(
async () => {
return {
timestamp: Date.now(),
random: Math.random(),
}
},
['timestamp'],
{
tags: ['test-update-tag'],
}
)
export default async function UpdateTagTest() {
const data = await getTimestamp()
return (
<div>
<h1>Update Tag Test</h1>
<div id="data">{JSON.stringify(data)}</div>
<Buttons />
</div>
)
}
......@@ -3,6 +3,15 @@ module.exports = {
logging: {
fetches: {},
},
experimental: {
cacheLife: {
expireNow: {
stale: 0,
expire: 0,
revalidate: 0,
},
},
},
cacheHandler: process.env.CUSTOM_CACHE_HANDLER
? require.resolve('./cache-handler.js')
: undefined,
......
'use server'
import { unstable_expirePath } from 'next/cache'
import { revalidatePath } from 'next/cache'
export async function doAction() {
unstable_expirePath('/en/photos/1/view')
revalidatePath('/en/photos/1/view')
// sleep 1s
await new Promise((resolve) => setTimeout(resolve, 1000))
return Math.random()
......
import { revalidateTag } from 'next/cache'
import { updateTag } from 'next/cache'
export const fetchCache = 'default-cache'
......@@ -80,7 +80,7 @@ function RevalidateForm() {
<form
action={async () => {
'use server'
revalidateTag('test-tag')
updateTag('test-tag')
}}
>
<button id="revalidate-button">Revalidate</button>
......
'use server'
import { unstable_expirePath } from 'next/cache'
import { revalidatePath } from 'next/cache'
export async function action() {
unstable_expirePath('/', 'layout')
revalidatePath('/', 'layout')
return true
}
import { unstable_expirePath } from 'next/cache'
import { revalidatePath } from 'next/cache'
export async function revalidateTimestampPage(/** @type {string} */ key) {
const path = `/timestamp/key/${encodeURIComponent(key)}`
......@@ -10,7 +10,7 @@ export async function revalidateTimestampPage(/** @type {string} */ key) {
}
console.log('revalidateTimestampPage :: revalidating', path)
unstable_expirePath(path)
revalidatePath(path)
}
const WAIT_BEFORE_REVALIDATING_DEFAULT = 1000
......
import { revalidateTimestampPage } from '../revalidate'
export async function POST(/** @type {Request} */ request) {
// we can't call unstable_expirePath from middleware, so we need to do it from here instead
// we can't call revalidatePath from middleware, so we need to do it from here instead
const path = new URL(request.url).searchParams.get('path')
if (!path) {
return Response.json(
......
......@@ -9,7 +9,7 @@ const WAIT_BEFORE_REVALIDATING = 1000
// If we want to verify that `after()` ran its callback,
// we need it to perform some kind of side effect (because it can't affect the response).
// In other tests, we often use logs for this, but we don't have access to those in deploy tests.
// So instead this test relies on calling `unstable_expirePath` inside `after`
// So instead this test relies on calling `revalidatePath` inside `after`
// to revalidate an ISR page '/timestamp/key/[key]', and then checking if the timestamp changed --
// if it did, we successfully ran the callback (and performed a side effect).
......
......@@ -9,7 +9,7 @@ export function middleware(
if (match) {
const pathPrefix = match.groups.prefix
after(async () => {
// we can't call unstable_expirePath from middleware, so we need to do it via an endpoint instead
// we can't call revalidatePath from middleware, so we need to do it via an endpoint instead
const pathToRevalidate = pathPrefix + `/middleware`
const postUrl = new URL('/timestamp/trigger-revalidate', url.href)
......
import Link from 'next/link'
import { unstable_expirePath } from 'next/cache'
import { revalidatePath } from 'next/cache'
import { addData } from '../../actions'
export default function Page() {
......@@ -9,7 +9,7 @@ export default function Page() {
await addData(new Date().toISOString())
unstable_expirePath('/', 'layout')
revalidatePath('/', 'layout')
}
return (
......
'use server'
import { unstable_expirePath } from 'next/cache'
import { revalidatePath } from 'next/cache'
import { redirect } from 'next/navigation'
let data = []
......@@ -25,5 +25,5 @@ export async function redirectAction() {
export async function clearData() {
data = []
unstable_expirePath('/')
revalidatePath('/')
}
'use server'
import { unstable_expirePath } from 'next/cache'
import { revalidatePath } from 'next/cache'
export async function revalidateAction() {
console.log('revalidate action')
unstable_expirePath('/')
revalidatePath('/')
return {
success: true,
}
......
import { unstable_expirePath } from 'next/cache'
import { revalidatePath } from 'next/cache'
export async function GET(request) {
const url = new URL(request.url)
......@@ -12,7 +12,7 @@ export async function GET(request) {
type = 'page'
}
unstable_expirePath(pathname, type)
revalidatePath(pathname, type)
}
return new Response(
......
import { unstable_expireTag } from 'next/cache'
import { revalidateTag } from 'next/cache'
export const POST = async () => {
unstable_expireTag('unstable-cache-fetch')
revalidateTag('unstable-cache-fetch', 'expireNow')
return new Response('OK', { status: 200 })
}
module.exports = {
experimental: {
cacheLife: {
expireNow: {
stale: 0,
expire: 0,
revalidate: 0,
},
},
cacheComponents: true,
},
}
import { NextResponse } from 'next/server'
import { unstable_expirePath } from 'next/cache'
import { revalidatePath } from 'next/cache'
export async function GET(req) {
unstable_expirePath('/')
revalidatePath('/')
return NextResponse.json({ revalidated: true, now: Date.now() })
}
import { NextResponse } from 'next/server'
import { unstable_expireTag } from 'next/cache'
import { revalidateTag } from 'next/cache'
export async function GET(req) {
unstable_expireTag('thankyounext')
revalidateTag('thankyounext', 'expireNow')
return NextResponse.json({ revalidated: true, now: Date.now() })
}
const nextConfig = {
experimental: {
cacheLife: {
expireNow: {
stale: 0,
expire: 0,
revalidate: 0,
},
},
},
}
export default nextConfig
......@@ -6,7 +6,7 @@ describe('app-dir revalidate-dynamic', () => {
})
if (isNextStart) {
it('should correctly mark a route handler that uses unstable_expireTag as dynamic', async () => {
it('should correctly mark a route handler that uses revalidateTag as dynamic', async () => {
expect(next.cliOutput).toContain('ƒ /api/revalidate-path')
expect(next.cliOutput).toContain('ƒ /api/revalidate-tag')
})
......
'use server'
import { unstable_expireTag } from 'next/cache'
import { updateTag } from 'next/cache'
export const revalidate = async (
tag: string
): Promise<{ revalidated: boolean }> => {
unstable_expireTag(tag)
updateTag(tag)
return { revalidated: true }
}
'use server'
import Link from 'next/link'
import { unstable_expireTag } from 'next/cache'
import { revalidateTag } from 'next/cache'
const RevalidateViaPage = async ({
searchParams,
......@@ -9,7 +9,7 @@ const RevalidateViaPage = async ({
searchParams: Promise<{ tag: string }>
}) => {
const { tag } = await searchParams
unstable_expireTag(tag)
revalidateTag(tag, 'max')
return (
<div className="flex flex-col items-center justify-center h-screen">
......
import { nextTestSetup } from 'e2e-utils'
import { assertHasRedbox, getRedboxHeader, retry } from 'next-test-utils'
describe('unstable_expireTag-rsc', () => {
describe('revalidateTag-rsc', () => {
const { next, isNextDev, isNextDeploy } = nextTestSetup({
files: __dirname,
})
it('should revalidate fetch cache if unstable_expireTag invoked via server action', async () => {
it('should revalidate fetch cache if revalidateTag invoked via server action', async () => {
const browser = await next.browser('/')
const randomNumber = await browser.elementById('data').text()
await browser.refresh()
......@@ -23,14 +23,14 @@ describe('unstable_expireTag-rsc', () => {
if (!isNextDeploy) {
// skipped in deploy because it uses `next.cliOutput`
it('should error if unstable_expireTag is called during render', async () => {
it('should error if revalidateTag is called during render', async () => {
const browser = await next.browser('/')
await browser.elementByCss('#revalidate-via-page').click()
if (isNextDev) {
await assertHasRedbox(browser)
await expect(getRedboxHeader(browser)).resolves.toContain(
'Route /revalidate_via_page used "unstable_expireTag data"'
'Route /revalidate_via_page used "revalidateTag data"'
)
} else {
await retry(async () => {
......@@ -41,7 +41,7 @@ describe('unstable_expireTag-rsc', () => {
}
expect(next.cliOutput).toContain(
'Route /revalidate_via_page used "unstable_expireTag data"'
'Route /revalidate_via_page used "revalidateTag data"'
)
})
}
......
import { revalidatePath, revalidateTag } from 'next/cache'
import { revalidatePath, updateTag } from 'next/cache'
import {
LinkAccordion,
FormAccordion,
......@@ -23,7 +23,7 @@ export default async function Page() {
id="revalidate-by-tag"
formAction={async function () {
'use server'
revalidateTag('random-greeting')
updateTag('random-greeting')
}}
>
Revalidate by tag
......
import { Suspense } from 'react'
import {
unstable_cacheLife as cacheLife,
unstable_cacheTag as cacheTag,
revalidateTag,
} from 'next/cache'
import { redirect } from 'next/navigation'
import { connection } from 'next/server'
import React from 'react'
async function getData() {
'use cache: legacy'
cacheLife({ revalidate: 3 })
cacheTag('legacy')
return new Date().toISOString()
}
async function AsyncComp() {
let data = await getData()
return <p id="data">{data}</p>
}
export default async function Legacy() {
await connection()
return (
<main>
<Suspense fallback={<p>Loading...</p>}>
<AsyncComp />
</Suspense>
<form
action={async () => {
'use server'
revalidateTag('legacy')
redirect('/legacy')
}}
>
<button id="revalidate">Revalidate Tag</button>
</form>
</main>
)
}
......@@ -3,7 +3,7 @@ import {
unstable_cacheLife as cacheLife,
unstable_cacheTag as cacheTag,
revalidatePath,
revalidateTag,
updateTag,
} from 'next/cache'
import { redirect } from 'next/navigation'
import { connection } from 'next/server'
......@@ -38,7 +38,7 @@ export default async function Home() {
formAction={async () => {
'use server'
revalidateTag('modern')
updateTag('modern')
}}
>
Revalidate Tag
......@@ -58,7 +58,7 @@ export default async function Home() {
formAction={async () => {
'use server'
revalidateTag('modern')
updateTag('modern')
redirect('/')
}}
>
......
......@@ -4,7 +4,7 @@ const defaultCacheHandler =
require('next/dist/server/lib/cache-handlers/default.external').default
/**
* @type {import('next/dist/server/lib/cache-handlers/types').CacheHandlerV2}
* @type {import('next/dist/server/lib/cache-handlers/types').CacheHandler}
*/
const cacheHandler = {
async get(cacheKey, softTags) {
......@@ -22,16 +22,16 @@ const cacheHandler = {
return defaultCacheHandler.refreshTags()
},
async getExpiration(...tags) {
async getExpiration(tags) {
console.log('ModernCustomCacheHandler::getExpiration', JSON.stringify(tags))
// Expecting soft tags in `get` to be used by the cache handler for checking
// the expiration of a cache entry, instead of letting Next.js handle it.
return Infinity
},
async expireTags(...tags) {
console.log('ModernCustomCacheHandler::expireTags', JSON.stringify(tags))
return defaultCacheHandler.expireTags(...tags)
async updateTags(tags) {
console.log('ModernCustomCacheHandler::updateTags', JSON.stringify(tags))
return defaultCacheHandler.updateTags(tags)
},
}
......
// @ts-check
const defaultCacheHandler =
require('next/dist/server/lib/cache-handlers/default.external').default
/**
* @type {import('next/dist/server/lib/cache-handlers/types').CacheHandler}
*/
const cacheHandler = {
async get(cacheKey, softTags) {
console.log(
'LegacyCustomCacheHandler::get',
cacheKey,
JSON.stringify(softTags)
)
return defaultCacheHandler.get(cacheKey, softTags)
},
async set(cacheKey, pendingEntry) {
console.log('LegacyCustomCacheHandler::set', cacheKey)
return defaultCacheHandler.set(cacheKey, pendingEntry)
},
async expireTags(...tags) {
console.log('LegacyCustomCacheHandler::expireTags', JSON.stringify(tags))
return defaultCacheHandler.expireTags(...tags)
},
async receiveExpiredTags(...tags) {
console.log(
'LegacyCustomCacheHandler::receiveExpiredTags',
JSON.stringify(tags)
)
},
}
module.exports = cacheHandler
......@@ -6,7 +6,6 @@ const nextConfig = {
cacheComponents: true,
cacheHandlers: {
default: require.resolve('./handler.js'),
legacy: require.resolve('./legacy-handler.js'),
},
},
}
......
......@@ -72,46 +72,6 @@ describe('use-cache-custom-handler', () => {
expect(cliOutput).not.toContain('ModernCustomCacheHandler::refreshTags')
expect(cliOutput).not.toContain(`ModernCustomCacheHandler::getExpiration`)
// We don't optimize for legacy cache handlers though:
expect(cliOutput).toContain(
`LegacyCustomCacheHandler::receiveExpiredTags []`
)
})
it('should use a legacy custom cache handler if provided', async () => {
const browser = await next.browser(`/legacy`)
const initialData = await browser.elementById('data').text()
expect(initialData).toMatch(isoDateRegExp)
expect(next.cliOutput.slice(outputIndex)).toContain(
'LegacyCustomCacheHandler::receiveExpiredTags []'
)
expect(next.cliOutput.slice(outputIndex)).toMatch(
/LegacyCustomCacheHandler::get \["(development|[A-Za-z0-9_-]{21})","([0-9a-f]{2})+",\[\]\] \["_N_T_\/layout","_N_T_\/legacy\/layout","_N_T_\/legacy\/page","_N_T_\/legacy"\]/
)
expect(next.cliOutput.slice(outputIndex)).toMatch(
/LegacyCustomCacheHandler::set \["(development|[A-Za-z0-9_-]{21})","([0-9a-f]{2})+",\[\]\]/
)
// The data should be cached initially.
await browser.refresh()
let data = await browser.elementById('data').text()
expect(data).toMatch(isoDateRegExp)
expect(data).toEqual(initialData)
// Because we use a low `revalidate` value for the "use cache" function, new
// data should be returned eventually.
await retry(async () => {
await browser.refresh()
data = await browser.elementById('data').text()
expect(data).toMatch(isoDateRegExp)
expect(data).not.toEqual(initialData)
}, 5000)
})
it('should revalidate after redirect using a modern custom cache handler', async () => {
......@@ -123,33 +83,7 @@ describe('use-cache-custom-handler', () => {
await retry(async () => {
expect(next.cliOutput.slice(outputIndex)).toContain(
'ModernCustomCacheHandler::expireTags ["modern"]'
)
const data = await browser.elementById('data').text()
expect(data).toMatch(isoDateRegExp)
expect(data).not.toEqual(initialData)
}, 5000)
})
it('should revalidate after redirect using a legacy custom cache handler', async () => {
const browser = await next.browser(`/legacy`)
const initialData = await browser.elementById('data').text()
expect(initialData).toMatch(isoDateRegExp)
expect(next.cliOutput.slice(outputIndex)).toContain(
'LegacyCustomCacheHandler::receiveExpiredTags []'
)
await browser.elementById('revalidate').click()
await retry(async () => {
expect(next.cliOutput.slice(outputIndex)).toContain(
'LegacyCustomCacheHandler::expireTags ["legacy"]'
)
expect(next.cliOutput.slice(outputIndex)).toContain(
'LegacyCustomCacheHandler::receiveExpiredTags ["legacy"]'
'ModernCustomCacheHandler::updateTags ["modern"]'
)
const data = await browser.elementById('data').text()
......@@ -158,13 +92,13 @@ describe('use-cache-custom-handler', () => {
}, 5000)
})
it('should not call expireTags for a normal invocation', async () => {
it('should not call updateTags for a normal invocation', async () => {
await next.fetch(`/`)
await retry(async () => {
const cliOutput = next.cliOutput.slice(outputIndex)
expect(cliOutput).toInclude('ModernCustomCacheHandler::refreshTags')
expect(cliOutput).not.toInclude('ModernCustomCacheHandler::expireTags')
expect(cliOutput).not.toInclude('ModernCustomCacheHandler::updateTags')
})
})
......@@ -179,7 +113,7 @@ describe('use-cache-custom-handler', () => {
const cliOutput = next.cliOutput.slice(outputIndex)
expect(cliOutput).not.toInclude('ModernCustomCacheHandler::getExpiration')
expect(cliOutput).toIncludeRepeated(
`ModernCustomCacheHandler::expireTags`,
`ModernCustomCacheHandler::updateTags`,
1
)
})
......
import { revalidatePath, revalidateTag } from 'next/cache'
import { revalidatePath, updateTag } from 'next/cache'
import { redirect } from 'next/navigation'
export default function Page() {
......@@ -9,7 +9,7 @@ export default function Page() {
formAction={async () => {
'use server'
revalidateTag('revalidate-and-redirect')
updateTag('revalidate-and-redirect')
redirect('/revalidate-and-redirect')
}}
>
......
import { revalidatePath, revalidateTag, unstable_cacheTag } from 'next/cache'
import { revalidatePath, unstable_cacheTag, updateTag } from 'next/cache'
import { Form } from './form'
import { connection } from 'next/server'
......@@ -26,7 +26,7 @@ export default async function Page() {
const initialCachedValue = await getCachedValue()
if (type === 'tag') {
revalidateTag('revalidate-and-use')
updateTag('revalidate-and-use')
} else {
revalidatePath('/revalidate-and-use')
}
......
......@@ -2,6 +2,6 @@ import { revalidateTag } from 'next/cache'
import { redirect } from 'next/navigation'
export async function GET() {
revalidateTag('api')
revalidateTag('api', 'expireNow')
redirect('/api')
}
import React from 'react'
import { unstable_expirePath, unstable_expireTag } from 'next/cache'
import { revalidatePath, updateTag } from 'next/cache'
export function RevalidateButtons() {
return (
......@@ -8,7 +8,7 @@ export function RevalidateButtons() {
id="revalidate-a"
formAction={async () => {
'use server'
unstable_expireTag('a')
updateTag('a')
}}
>
revalidate a
......@@ -17,7 +17,7 @@ export function RevalidateButtons() {
id="revalidate-b"
formAction={async () => {
'use server'
unstable_expireTag('b')
updateTag('b')
}}
>
revalidate b
......@@ -26,7 +26,7 @@ export function RevalidateButtons() {
id="revalidate-c"
formAction={async () => {
'use server'
unstable_expireTag('c')
updateTag('c')
}}
>
revalidate c
......@@ -35,7 +35,7 @@ export function RevalidateButtons() {
id="revalidate-f"
formAction={async () => {
'use server'
unstable_expireTag('f')
updateTag('f')
}}
>
revalidate f
......@@ -44,7 +44,7 @@ export function RevalidateButtons() {
id="revalidate-r"
formAction={async () => {
'use server'
unstable_expireTag('r')
updateTag('r')
}}
>
revalidate r
......@@ -53,7 +53,7 @@ export function RevalidateButtons() {
id="revalidate-path"
formAction={async () => {
'use server'
unstable_expirePath('/cache-tag')
revalidatePath('/cache-tag')
}}
>
revalidate path
......
import { unstable_expireTag, unstable_cacheTag as cacheTag } from 'next/cache'
import { updateTag, unstable_cacheTag as cacheTag } from 'next/cache'
async function refresh() {
'use server'
unstable_expireTag('home')
updateTag('home')
}
export default async function Page() {
......
......@@ -10,6 +10,11 @@ const nextConfig = {
revalidate: 100,
expire: 300,
},
expireNow: {
stale: 0,
expire: 0,
revalidate: 0,
},
},
cacheHandlers: {
custom: require.resolve(
......
......@@ -220,13 +220,13 @@ describe('use-cache', () => {
})
})
it('should update after unstable_expireTag correctly', async () => {
it('should update after revalidateTag correctly', async () => {
const browser = await next.browser('/cache-tag')
const initial = await browser.elementByCss('#a').text()
if (!isNextDev) {
// Bust the ISR cache first, to populate the in-memory cache for the
// subsequent unstable_expireTag calls.
// subsequent revalidateTag calls.
await browser.elementByCss('#revalidate-path').click()
await retry(async () => {
expect(await browser.elementByCss('#a').text()).not.toBe(initial)
......@@ -608,7 +608,7 @@ describe('use-cache', () => {
})
})
it('should be able to revalidate a page using unstable_expireTag', async () => {
it('should be able to revalidate a page using revalidateTag', async () => {
const browser = await next.browser(`/form`)
const time1 = await browser.waitForElementByCss('#t').text()
......
'use server'
import { unstable_expirePath } from 'next/cache'
import { revalidatePath } from 'next/cache'
export async function revalidateSelf() {
unstable_expirePath('/app/self-revalidate')
revalidatePath('/app/self-revalidate')
}
......@@ -4,7 +4,7 @@ import { NextRequest, NextResponse } from 'next/server'
export async function GET(req: NextRequest) {
console.log(req.url.toString())
revalidateTag(req.nextUrl.searchParams.get('tag') || '')
revalidateTag(req.nextUrl.searchParams.get('tag') || '', 'expireNow')
return NextResponse.json({ success: true })
}
......@@ -43,8 +43,8 @@ describe('global-default-cache-handler', () => {
console.log('symbol getExpiration', tags)
},
expireTags(...tags) {
console.log('symbol expireTags', tags)
updateTags(...tags) {
console.log('symbol updateTags', tags)
}
}
}
......@@ -93,12 +93,12 @@ describe('global-default-cache-handler', () => {
})
})
it('should call expireTags on global default cache handler', async () => {
it('should call updateTags on global default cache handler', async () => {
const res = await fetchViaHTTP(appPort, '/revalidate-tag', { tag: 'tag1' })
expect(res.status).toBe(200)
await retry(() => {
expect(output).toContain('symbol expireTags')
expect(output).toContain('symbol updateTags')
expect(output).toContain('tag1')
})
})
......
......@@ -5,6 +5,13 @@ const nextConfig = {
output: 'standalone',
experimental: {
useCache: true,
cacheLife: {
expireNow: {
stale: 0,
expire: 0,
revalidate: 0,
},
},
},
}
......
import { revalidateTag } from 'next/cache'
export function POST() {
revalidateTag('test')
revalidateTag('test', 'expireNow')
return new Response(null, { status: 200 })
}
......@@ -6,6 +6,13 @@ const nextConfig = {
cacheComponents: true,
clientSegmentCache: true,
clientParamParsing: true,
cacheLife: {
expireNow: {
stale: 0,
expire: 0,
revalidate: 0,
},
},
},
}
......
import { NextResponse } from 'next/server'
import { unstable_expirePath } from 'next/cache'
import { revalidatePath } from 'next/cache'
export async function GET() {
unstable_expirePath('/')
revalidatePath('/')
return NextResponse.json({ success: true })
}
......@@ -6,7 +6,7 @@ const defaultCacheHandler =
require('next/dist/server/lib/cache-handlers/default.external').default
/**
* @type {import('next/dist/server/lib/cache-handlers/types').CacheHandlerV2}
* @type {import('next/dist/server/lib/cache-handlers/types').CacheHandler}
*/
const cacheHandler = {
async get(cacheKey) {
......@@ -23,12 +23,12 @@ const cacheHandler = {
return defaultCacheHandler.refreshTags()
},
async getExpiration(...tags) {
return defaultCacheHandler.getExpiration(...tags)
async getExpiration(tags) {
return defaultCacheHandler.getExpiration(tags)
},
async expireTags(...tags) {
return defaultCacheHandler.expireTags(...tags)
async updateTags(tags) {
return defaultCacheHandler.updateTags(tags)
},
}
......
......@@ -165,8 +165,8 @@
"app-dir action handling fetch actions should handle calls to redirect() with a relative URL in a single pass",
"app-dir action handling fetch actions should handle calls to redirect() with external URLs",
"app-dir action handling fetch actions should handle redirects to routes that provide an invalid RSC response",
"app-dir action handling fetch actions should handle unstable_expirePath",
"app-dir action handling fetch actions should handle unstable_expireTag",
"app-dir action handling fetch actions should handle revalidatePath",
"app-dir action handling fetch actions should handle revalidateTag",
"app-dir action handling fetch actions should invalidate client cache on other routes when cookies.set is called",
"app-dir action handling fetch actions should invalidate client cache when path is revalidated",
"app-dir action handling fetch actions should invalidate client cache when tag is revalidated",
......@@ -228,7 +228,7 @@
],
"failed": [],
"pending": [
"app-dir action handling fetch actions should handle unstable_expireTag + redirect",
"app-dir action handling fetch actions should handle revalidateTag + redirect",
"app-dir action handling server actions render client components client component imported action should support importing client components from actions"
],
"flakey": [],
......@@ -299,8 +299,8 @@
"app-dir action handling fetch actions should handle calls to redirect() with a relative URL in a single pass",
"app-dir action handling fetch actions should handle calls to redirect() with external URLs",
"app-dir action handling fetch actions should handle redirects to routes that provide an invalid RSC response",
"app-dir action handling fetch actions should handle unstable_expirePath",
"app-dir action handling fetch actions should handle unstable_expireTag",
"app-dir action handling fetch actions should handle revalidatePath",
"app-dir action handling fetch actions should handle revalidateTag",
"app-dir action handling fetch actions should invalidate client cache on other routes when cookies.set is called",
"app-dir action handling fetch actions should invalidate client cache when path is revalidated",
"app-dir action handling fetch actions should invalidate client cache when tag is revalidated",
......@@ -362,7 +362,7 @@
],
"failed": [],
"pending": [
"app-dir action handling fetch actions should handle unstable_expireTag + redirect",
"app-dir action handling fetch actions should handle revalidateTag + redirect",
"app-dir action handling server actions render client components client component imported action should support importing client components from actions"
],
"flakey": [],
......@@ -5729,7 +5729,7 @@
},
"test/e2e/app-dir/revalidate-dynamic/revalidate-dynamic.test.ts": {
"passed": [
"app-dir revalidate-dynamic should correctly mark a route handler that uses unstable_expireTag as dynamic",
"app-dir revalidate-dynamic should correctly mark a route handler that uses revalidateTag as dynamic",
"app-dir revalidate-dynamic should revalidate the data with /api/revalidate-path",
"app-dir revalidate-dynamic should revalidate the data with /api/revalidate-tag"
],
......@@ -5740,8 +5740,8 @@
},
"test/e2e/app-dir/revalidatetag-rsc/revalidatetag-rsc.test.ts": {
"passed": [
"unstable_expireTag-rsc should error if unstable_expireTag is called during render",
"unstable_expireTag-rsc should revalidate fetch cache if unstable_expireTag invoked via server action"
"revalidateTag-rsc should error if revalidateTag is called during render",
"revalidateTag-rsc should revalidate fetch cache if revalidateTag invoked via server action"
],
"failed": [],
"pending": [],
......@@ -7132,7 +7132,7 @@
"test/e2e/app-dir/use-cache-custom-handler/use-cache-custom-handler.test.ts": {
"passed": [
"use-cache-custom-handler calls neither refreshTags nor getExpiration if \"use cache\" is not used",
"use-cache-custom-handler should not call expireTags for a normal invocation",
"use-cache-custom-handler should not call updateTags for a normal invocation",
"use-cache-custom-handler should not call getExpiration after an action",
"use-cache-custom-handler should revalidate after redirect using a legacy custom cache handler",
"use-cache-custom-handler should revalidate after redirect using a modern custom cache handler",
......@@ -7260,7 +7260,7 @@
"use-cache can reference server actions in \"use cache\" functions",
"use-cache renders the not-found page when `notFound()` is used",
"use-cache shares caches between the page/layout and generateMetadata",
"use-cache should be able to revalidate a page using unstable_expireTag",
"use-cache should be able to revalidate a page using revalidateTag",
"use-cache should cache complex args",
"use-cache should cache fetch without no-store",
"use-cache should cache results",
......@@ -7290,7 +7290,7 @@
"use-cache should revalidate caches nested in unstable_cache",
"use-cache should send an SWR cache-control header based on the revalidate and expire values",
"use-cache should store a fetch response without no-store in the incremental cache handler during build",
"use-cache should update after unstable_expireTag correctly",
"use-cache should update after revalidateTag correctly",
"use-cache should use revalidate config in fetch",
"use-cache usage in node_modules should cache results when using a directive with a handler",
"use-cache usage in node_modules should cache results when using a directive without a handler",
......@@ -19999,7 +19999,7 @@
},
"test/production/app-dir/global-default-cache-handler/global-default-cache-handler.test.ts": {
"passed": [
"global-default-cache-handler should call expireTags on global default cache handler",
"global-default-cache-handler should call updateTags on global default cache handler",
"global-default-cache-handler should call refreshTags on global default cache handler",
"global-default-cache-handler should use global symbol for default cache handler"
],
......@@ -221,8 +221,8 @@
"Error overlay - RSC build errors importing 'next/cache' APIs in a client component unstable_cache is allowed",
"Error overlay - RSC build errors importing 'next/cache' APIs in a client component unstable_cacheLife is not allowed",
"Error overlay - RSC build errors importing 'next/cache' APIs in a client component unstable_cacheTag is not allowed",
"Error overlay - RSC build errors importing 'next/cache' APIs in a client component unstable_expirePath is not allowed",
"Error overlay - RSC build errors importing 'next/cache' APIs in a client component unstable_expireTag is not allowed",
"Error overlay - RSC build errors importing 'next/cache' APIs in a client component revalidatePath is not allowed",
"Error overlay - RSC build errors importing 'next/cache' APIs in a client component revalidateTag is not allowed",
"Error overlay - RSC build errors importing 'next/cache' APIs in a client component unstable_noStore is allowed",
"Error overlay - RSC build errors next/root-params importing 'next/root-params' in a client component",
"Error overlay - RSC build errors next/root-params importing 'next/root-params' in a client component in a way that bypasses import analysis",
......@@ -467,8 +467,8 @@
"Error Overlay for server components compiler errors in pages importing 'next/cache' APIs in pages unstable_cache is allowed",
"Error Overlay for server components compiler errors in pages importing 'next/cache' APIs in pages unstable_cacheLife is not allowed",
"Error Overlay for server components compiler errors in pages importing 'next/cache' APIs in pages unstable_cacheTag is not allowed",
"Error Overlay for server components compiler errors in pages importing 'next/cache' APIs in pages unstable_expirePath is not allowed",
"Error Overlay for server components compiler errors in pages importing 'next/cache' APIs in pages unstable_expireTag is not allowed",
"Error Overlay for server components compiler errors in pages importing 'next/cache' APIs in pages revalidatePath is not allowed",
"Error Overlay for server components compiler errors in pages importing 'next/cache' APIs in pages revalidateTag is not allowed",
"Error Overlay for server components compiler errors in pages importing 'next/cache' APIs in pages unstable_noStore is allowed",
"Error Overlay for server components compiler errors in pages importing 'next/headers' in pages",
"Error Overlay for server components compiler errors in pages importing 'next/root-params' in pages",
......@@ -2613,8 +2613,8 @@
"app-dir action handling fetch actions should handle calls to redirect() with a relative URL in a single pass",
"app-dir action handling fetch actions should handle calls to redirect() with external URLs",
"app-dir action handling fetch actions should handle redirects to routes that provide an invalid RSC response",
"app-dir action handling fetch actions should handle unstable_expirePath",
"app-dir action handling fetch actions should handle unstable_expireTag",
"app-dir action handling fetch actions should handle revalidatePath",
"app-dir action handling fetch actions should handle revalidateTag",
"app-dir action handling fetch actions should invalidate client cache on other routes when cookies.set is called",
"app-dir action handling fetch actions should invalidate client cache when path is revalidated",
"app-dir action handling fetch actions should invalidate client cache when tag is revalidated",
......@@ -2675,7 +2675,7 @@
],
"failed": [],
"pending": [
"app-dir action handling fetch actions should handle unstable_expireTag + redirect",
"app-dir action handling fetch actions should handle revalidateTag + redirect",
"app-dir action handling server actions render client components client component imported action should support importing client components from actions"
],
"flakey": [],
......@@ -2742,8 +2742,8 @@
"app-dir action handling fetch actions should handle calls to redirect() with a relative URL in a single pass",
"app-dir action handling fetch actions should handle calls to redirect() with external URLs",
"app-dir action handling fetch actions should handle redirects to routes that provide an invalid RSC response",
"app-dir action handling fetch actions should handle unstable_expirePath",
"app-dir action handling fetch actions should handle unstable_expireTag",
"app-dir action handling fetch actions should handle revalidatePath",
"app-dir action handling fetch actions should handle revalidateTag",
"app-dir action handling fetch actions should invalidate client cache on other routes when cookies.set is called",
"app-dir action handling fetch actions should invalidate client cache when path is revalidated",
"app-dir action handling fetch actions should invalidate client cache when tag is revalidated",
......@@ -2804,7 +2804,7 @@
],
"failed": [],
"pending": [
"app-dir action handling fetch actions should handle unstable_expireTag + redirect",
"app-dir action handling fetch actions should handle revalidateTag + redirect",
"app-dir action handling server actions render client components client component imported action should support importing client components from actions"
],
"flakey": [],
......@@ -7733,8 +7733,8 @@
},
"test/e2e/app-dir/revalidatetag-rsc/revalidatetag-rsc.test.ts": {
"passed": [
"unstable_expireTag-rsc should error if unstable_expireTag is called during render",
"unstable_expireTag-rsc should revalidate fetch cache if unstable_expireTag invoked via server action"
"revalidateTag-rsc should error if revalidateTag is called during render",
"revalidateTag-rsc should revalidate fetch cache if revalidateTag invoked via server action"
],
"failed": [],
"pending": [],
......@@ -8984,7 +8984,7 @@
"test/e2e/app-dir/use-cache-custom-handler/use-cache-custom-handler.test.ts": {
"passed": [
"use-cache-custom-handler calls neither refreshTags nor getExpiration if \"use cache\" is not used",
"use-cache-custom-handler should not call expireTags for a normal invocation",
"use-cache-custom-handler should not call updateTags for a normal invocation",
"use-cache-custom-handler should not call getExpiration after an action",
"use-cache-custom-handler should revalidate after redirect using a legacy custom cache handler",
"use-cache-custom-handler should revalidate after redirect using a modern custom cache handler",
......@@ -9122,7 +9122,7 @@
"use-cache renders the not-found page when `notFound()` is used",
"use-cache replays logs from \"use cache\" functions",
"use-cache shares caches between the page/layout and generateMetadata",
"use-cache should be able to revalidate a page using unstable_expireTag",
"use-cache should be able to revalidate a page using revalidateTag",
"use-cache should cache complex args",
"use-cache should cache fetch without no-store",
"use-cache should cache results",
......@@ -9145,7 +9145,7 @@
"use-cache should revalidate caches after redirect",
"use-cache should revalidate caches during on-demand revalidation",
"use-cache should revalidate caches nested in unstable_cache",
"use-cache should update after unstable_expireTag correctly",
"use-cache should update after revalidateTag correctly",
"use-cache should use revalidate config in fetch",
"use-cache usage in node_modules should cache results when using a directive with a handler",
"use-cache usage in node_modules should cache results when using a directive without a handler",
......@@ -162,8 +162,8 @@
"app-dir action handling fetch actions should handle calls to redirect() with a relative URL in a single pass",
"app-dir action handling fetch actions should handle calls to redirect() with external URLs",
"app-dir action handling fetch actions should handle redirects to routes that provide an invalid RSC response",
"app-dir action handling fetch actions should handle unstable_expirePath",
"app-dir action handling fetch actions should handle unstable_expireTag",
"app-dir action handling fetch actions should handle revalidatePath",
"app-dir action handling fetch actions should handle revalidateTag",
"app-dir action handling fetch actions should invalidate client cache on other routes when cookies.set is called",
"app-dir action handling fetch actions should invalidate client cache when path is revalidated",
"app-dir action handling fetch actions should invalidate client cache when tag is revalidated",
......@@ -225,7 +225,7 @@
],
"failed": [],
"pending": [
"app-dir action handling fetch actions should handle unstable_expireTag + redirect",
"app-dir action handling fetch actions should handle revalidateTag + redirect",
"app-dir action handling server actions render client components client component imported action should support importing client components from actions"
],
"flakey": [],
......@@ -294,8 +294,8 @@
"app-dir action handling fetch actions should handle calls to redirect() with a relative URL in a single pass",
"app-dir action handling fetch actions should handle calls to redirect() with external URLs",
"app-dir action handling fetch actions should handle redirects to routes that provide an invalid RSC response",
"app-dir action handling fetch actions should handle unstable_expirePath",
"app-dir action handling fetch actions should handle unstable_expireTag",
"app-dir action handling fetch actions should handle revalidatePath",
"app-dir action handling fetch actions should handle revalidateTag",
"app-dir action handling fetch actions should invalidate client cache on other routes when cookies.set is called",
"app-dir action handling fetch actions should invalidate client cache when path is revalidated",
"app-dir action handling fetch actions should invalidate client cache when tag is revalidated",
......@@ -357,7 +357,7 @@
],
"failed": [],
"pending": [
"app-dir action handling fetch actions should handle unstable_expireTag + redirect",
"app-dir action handling fetch actions should handle revalidateTag + redirect",
"app-dir action handling server actions render client components client component imported action should support importing client components from actions"
],
"flakey": [],
......@@ -4776,7 +4776,7 @@
},
"test/e2e/app-dir/revalidate-dynamic/revalidate-dynamic.test.ts": {
"passed": [
"app-dir revalidate-dynamic should correctly mark a route handler that uses unstable_expireTag as dynamic",
"app-dir revalidate-dynamic should correctly mark a route handler that uses revalidateTag as dynamic",
"app-dir revalidate-dynamic should revalidate the data with /api/revalidate-path",
"app-dir revalidate-dynamic should revalidate the data with /api/revalidate-tag"
],
......@@ -4787,8 +4787,8 @@
},
"test/e2e/app-dir/revalidatetag-rsc/revalidatetag-rsc.test.ts": {
"passed": [
"unstable_expireTag-rsc should error if unstable_expireTag is called during render",
"unstable_expireTag-rsc should revalidate fetch cache if unstable_expireTag invoked via server action"
"revalidateTag-rsc should error if revalidateTag is called during render",
"revalidateTag-rsc should revalidate fetch cache if revalidateTag invoked via server action"
],
"failed": [],
"pending": [],
......@@ -5950,7 +5950,7 @@
"test/e2e/app-dir/use-cache-custom-handler/use-cache-custom-handler.test.ts": {
"passed": [
"use-cache-custom-handler calls neither refreshTags nor getExpiration if \"use cache\" is not used",
"use-cache-custom-handler should not call expireTags for a normal invocation",
"use-cache-custom-handler should not call updateTags for a normal invocation",
"use-cache-custom-handler should not call getExpiration after an action",
"use-cache-custom-handler should revalidate after redirect using a legacy custom cache handler",
"use-cache-custom-handler should revalidate after redirect using a modern custom cache handler",
......@@ -6052,7 +6052,7 @@
"use-cache can reference server actions in \"use cache\" functions",
"use-cache renders the not-found page when `notFound()` is used",
"use-cache shares caches between the page/layout and generateMetadata",
"use-cache should be able to revalidate a page using unstable_expireTag",
"use-cache should be able to revalidate a page using revalidateTag",
"use-cache should cache complex args",
"use-cache should cache fetch without no-store",
"use-cache should cache results",
......@@ -6079,7 +6079,7 @@
"use-cache should revalidate caches nested in unstable_cache",
"use-cache should send an SWR cache-control header based on the revalidate and expire values",
"use-cache should store a fetch response without no-store in the incremental cache handler during build",
"use-cache should update after unstable_expireTag correctly",
"use-cache should update after revalidateTag correctly",
"use-cache should use revalidate config in fetch",
"use-cache usage in node_modules should cache results when using a directive with a handler",
"use-cache usage in node_modules should cache results when using a directive without a handler",
......@@ -18427,7 +18427,7 @@
},
"test/production/app-dir/global-default-cache-handler/global-default-cache-handler.test.ts": {
"passed": [
"global-default-cache-handler should call expireTags on global default cache handler",
"global-default-cache-handler should call updateTags on global default cache handler",
"global-default-cache-handler should call refreshTags on global default cache handler",
"global-default-cache-handler should use global symbol for default cache handler"
],
......@@ -2020,8 +2020,8 @@
"Error overlay - RSC build errors importing 'next/cache' APIs in a client component unstable_cache is allowed",
"Error overlay - RSC build errors importing 'next/cache' APIs in a client component unstable_cacheLife is not allowed",
"Error overlay - RSC build errors importing 'next/cache' APIs in a client component unstable_cacheTag is not allowed",
"Error overlay - RSC build errors importing 'next/cache' APIs in a client component unstable_expirePath is not allowed",
"Error overlay - RSC build errors importing 'next/cache' APIs in a client component unstable_expireTag is not allowed",
"Error overlay - RSC build errors importing 'next/cache' APIs in a client component revalidatePath is not allowed",
"Error overlay - RSC build errors importing 'next/cache' APIs in a client component revalidateTag is not allowed",
"Error overlay - RSC build errors importing 'next/cache' APIs in a client component unstable_noStore is allowed",
"Error overlay - RSC build errors should allow to use and handle rsc poisoning client-only",
"Error overlay - RSC build errors should allow to use and handle rsc poisoning server-only",
......@@ -2275,8 +2275,8 @@
"Error Overlay for server components compiler errors in pages importing 'next/cache' APIs in pages unstable_cache is allowed",
"Error Overlay for server components compiler errors in pages importing 'next/cache' APIs in pages unstable_cacheLife is not allowed",
"Error Overlay for server components compiler errors in pages importing 'next/cache' APIs in pages unstable_cacheTag is not allowed",
"Error Overlay for server components compiler errors in pages importing 'next/cache' APIs in pages unstable_expirePath is not allowed",
"Error Overlay for server components compiler errors in pages importing 'next/cache' APIs in pages unstable_expireTag is not allowed",
"Error Overlay for server components compiler errors in pages importing 'next/cache' APIs in pages revalidatePath is not allowed",
"Error Overlay for server components compiler errors in pages importing 'next/cache' APIs in pages revalidateTag is not allowed",
"Error Overlay for server components compiler errors in pages importing 'next/cache' APIs in pages unstable_noStore is allowed",
"Error Overlay for server components compiler errors in pages importing 'next/headers' in pages",
"Error Overlay for server components compiler errors in pages importing 'server-only' in pages",
......@@ -4216,8 +4216,8 @@
"app-dir action handling fetch actions should handle calls to redirect() with a relative URL in a single pass",
"app-dir action handling fetch actions should handle calls to redirect() with external URLs",
"app-dir action handling fetch actions should handle redirects to routes that provide an invalid RSC response",
"app-dir action handling fetch actions should handle unstable_expirePath",
"app-dir action handling fetch actions should handle unstable_expireTag",
"app-dir action handling fetch actions should handle revalidatePath",
"app-dir action handling fetch actions should handle revalidateTag",
"app-dir action handling fetch actions should invalidate client cache on other routes when cookies.set is called",
"app-dir action handling fetch actions should invalidate client cache when path is revalidated",
"app-dir action handling fetch actions should invalidate client cache when tag is revalidated",
......@@ -4279,7 +4279,7 @@
],
"failed": [],
"pending": [
"app-dir action handling fetch actions should handle unstable_expireTag + redirect",
"app-dir action handling fetch actions should handle revalidateTag + redirect",
"app-dir action handling server actions render client components client component imported action should support importing client components from actions"
],
"flakey": [],
......@@ -4344,8 +4344,8 @@
"app-dir action handling fetch actions should handle calls to redirect() with a relative URL in a single pass",
"app-dir action handling fetch actions should handle calls to redirect() with external URLs",
"app-dir action handling fetch actions should handle redirects to routes that provide an invalid RSC response",
"app-dir action handling fetch actions should handle unstable_expirePath",
"app-dir action handling fetch actions should handle unstable_expireTag",
"app-dir action handling fetch actions should handle revalidatePath",
"app-dir action handling fetch actions should handle revalidateTag",
"app-dir action handling fetch actions should invalidate client cache on other routes when cookies.set is called",
"app-dir action handling fetch actions should invalidate client cache when path is revalidated",
"app-dir action handling fetch actions should invalidate client cache when tag is revalidated",
......@@ -4407,7 +4407,7 @@
],
"failed": [],
"pending": [
"app-dir action handling fetch actions should handle unstable_expireTag + redirect",
"app-dir action handling fetch actions should handle revalidateTag + redirect",
"app-dir action handling server actions render client components client component imported action should support importing client components from actions"
],
"flakey": [],
......@@ -8399,8 +8399,8 @@
},
"test/e2e/app-dir/revalidatetag-rsc/revalidatetag-rsc.test.ts": {
"passed": [
"unstable_expireTag-rsc should error if unstable_expireTag is called during render",
"unstable_expireTag-rsc should revalidate fetch cache if unstable_expireTag invoked via server action"
"revalidateTag-rsc should error if revalidateTag is called during render",
"revalidateTag-rsc should revalidate fetch cache if revalidateTag invoked via server action"
],
"failed": [],
"pending": [],
......@@ -9502,7 +9502,7 @@
"test/e2e/app-dir/use-cache-custom-handler/use-cache-custom-handler.test.ts": {
"passed": [
"use-cache-custom-handler calls neither refreshTags nor getExpiration if \"use cache\" is not used",
"use-cache-custom-handler should not call expireTags for a normal invocation",
"use-cache-custom-handler should not call updateTags for a normal invocation",
"use-cache-custom-handler should not call getExpiration after an action",
"use-cache-custom-handler should revalidate after redirect using a legacy custom cache handler",
"use-cache-custom-handler should revalidate after redirect using a modern custom cache handler",
......@@ -9619,7 +9619,7 @@
"use-cache renders the not-found page when `notFound()` is used",
"use-cache replays logs from \"use cache\" functions",
"use-cache shares caches between the page/layout and generateMetadata",
"use-cache should be able to revalidate a page using unstable_expireTag",
"use-cache should be able to revalidate a page using revalidateTag",
"use-cache should cache complex args",
"use-cache should cache fetch without no-store",
"use-cache should cache results",
......@@ -9641,7 +9641,7 @@
"use-cache should revalidate caches after redirect",
"use-cache should revalidate caches during on-demand revalidation",
"use-cache should revalidate caches nested in unstable_cache",
"use-cache should update after unstable_expireTag correctly",
"use-cache should update after revalidateTag correctly",
"use-cache should use revalidate config in fetch",
"use-cache usage in node_modules should cache results when using a directive with a handler",
"use-cache usage in node_modules should cache results when using a directive without a handler",
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