Unverified Commit 0bc4086d authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Add expireTag and expirePath APIs (#72485)

This adds `expireTag()` and `expirePath` APIs which are replacing
`revalidateTag` and `revalidatePath`. As such this also marks
`revalidatePath` and `revalidateTag` as deprecated and marked for
removal.

The arguments passed to these methods match `revalidateTag` and
`revalidatePath` with the exception that `expireTag` can receive
multiple tags now as separate arguments which matches our new
`unstable_cacheTag()` API.

We are wanting to update these APIs as `revalidateTag` naming has caused
some confusion as to when the affected items will be updated. The
underlying behavior of `expireTag` is to mark an entry as out of date
and for it to no longer be used so we are expiring it.

If you call `expirePath('/blog/first'`) the next time that item is
requested it is considered expired so the cache will not be used for it
and a fresh entry will be generated. Similarly for `expireTag('posts',
'blog')` the next time any cache with that tag is requested it's
respective cache will not be leveraged and new cache will be populated.

---------
Co-authored-by: 's avatarZack Tanner <1939140+ztanner@users.noreply.github.com>
Co-authored-by: 's avatarDelba de Oliveira <32464864+delbaoliveira@users.noreply.github.com>
parent 82ef14c8
---
title: expirePath
description: API Reference for the expirePath function.
---
`expirePath` allows you to purge [cached data](/docs/app/building-your-application/caching) on-demand for a specific path.
> **Good to know**:
>
> - `expirePath` is available in both [Node.js and Edge runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes).
> - `expirePath` only invalidates the cache when the included path is next visited. This means calling `expirePath` with a dynamic route segment will not immediately trigger many expirations at once. The invalidation only happens when the path is next visited.
> - Currently, `expirePath` invalidates all the routes in the [client-side Router Cache](/docs/app/building-your-application/caching#client-side-router-cache) when used in a server action. This behavior is temporary and will be updated in the future to apply only to the specific path.
> - Using `expirePath` invalidates **only the specific path** in the [server-side Route Cache](/docs/app/building-your-application/caching#full-route-cache).
## Reference
### Parameters
```tsx
expirePath(path: string, type?: 'page' | 'layout'): void;
```
- `path`: Either a string representing the filesystem path associated with the data you want to expire (for example, `/product/[slug]/page`), or the literal route segment (for example, `/product/123`). Must be less than 1024 characters. This value is case-sensitive.
- `type`: (optional) `'page'` or `'layout'` string to change the type of path to expire. If `path` contains a dynamic segment (for example, `/product/[slug]/page`), this parameter is required. If path refers to the literal route segment, e.g., `/product/1` for a dynamic page (e.g., `/product/[slug]/page`), you should not provide `type`.
### Returns
`expirePath` does not return a value.
## Examples
### Expiring a specific URL
```ts
import { expirePath } from 'next/cache'
expirePath('/blog/post-1')
```
This will purge the cache for one specific URL on the next page visit.
### Expiring a page path
```ts
import { expirePath } from 'next/cache'
expirePath('/blog/[slug]', 'page')
// or with route groups
expirePath('/(main)/blog/[slug]', 'page')
```
This will purge the cache any URL that matches the provided `page` file on the next page visit. This will _not_ invalidate pages beneath the specific page. For example, `/blog/[slug]` won't invalidate `/blog/[slug]/[author]`.
### Expiring a layout path
```ts
import { expirePath } from 'next/cache'
expirePath('/blog/[slug]', 'layout')
// or with route groups
expirePath('/(main)/post/[slug]', 'layout')
```
This will purge the cache on any URL that matches the provided `layout` file on the next page visit. This will cause pages beneath with the same layout to revalidate on the next visit. For example, in the above case, `/blog/[slug]/[another]` would also revalidate on the next visit.
### Expiring all data
```ts
import { expirePath } from 'next/cache'
expirePath('/', 'layout')
```
This will purge the Data Cache on the next page visit.
### Server Action
You can call `expirePath` in a Server Action:
```ts filename="app/actions.ts" switcher
'use server'
import { expirePath } from 'next/cache'
export default async function submit() {
await submitForm()
expirePath('/')
}
```
### Route Handler
You can call `expirePath` in a Route Handler:
```ts filename="app/api/expire/route.ts" switcher
import { expirePath } from 'next/cache'
import type { NextRequest } from 'next/server'
export async function GET(request: NextRequest) {
const path = request.nextUrl.searchParams.get('path')
if (path) {
expirePath(path)
return Response.json({ revalidated: true, now: Date.now() })
}
return Response.json({
expired: false,
now: Date.now(),
message: 'Missing path to expire',
})
}
```
```js filename="app/api/expire/route.js" switcher
import { expirePath } from 'next/cache'
export async function GET(request) {
const path = request.nextUrl.searchParams.get('path')
if (path) {
expirePath(path)
return Response.json({ expired: true, now: Date.now() })
}
return Response.json({
expired: false,
now: Date.now(),
message: 'Missing path to expire',
})
}
```
---
title: expireTag
description: API Reference for the expireTag function.
---
`expireTag` allows you to purge [cached data](/docs/app/building-your-application/caching) on-demand for a specific cache tag.
> **Good to know**:
>
> - `expireTag` is available in both [Node.js and Edge runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes).
> - `expireTag` only invalidates the cache when the path is next visited. This means calling `expireTag` with a dynamic route segment will not immediately trigger many expirations at once. The invalidation only happens when the path is next visited.
## Reference
### Parameters
```tsx
expireTag(...tags: string[]): void;
```
- `tags`: String arguments representing the cache tags associated with the data you want to revalidate. Must be less than or equal to 256 characters each. This value is case-sensitive.
You can add tags to `fetch` as follows:
```tsx
fetch(url, { next: { tags: [...] } });
```
### Returns
`expireTag` does not return a value.
## Examples
### Server Action
You can invoke `expireTag` in a Server Action:
```ts filename="app/actions.ts" switcher
'use server'
import { expireTag } from 'next/cache'
export default async function submit() {
await addPost()
expireTag('posts', 'blog')
}
```
```js filename="app/actions.js" switcher
'use server'
import { expireTag } from 'next/cache'
export default async function submit() {
await addPost()
expireTag('posts', 'blog')
}
```
### Route Handler
You can invoke `expireTag` in a Route Handler:
```ts filename="app/api/revalidate/route.ts" switcher
import type { NextRequest } from 'next/server'
import { expireTag } from 'next/cache'
export async function GET(request: NextRequest) {
const tag = request.nextUrl.searchParams.get('tag')
expireTag(tag)
return Response.json({ revalidated: true, now: Date.now() })
}
```
```js filename="app/api/revalidate/route.js" switcher
import { expireTag } from 'next/cache'
export async function GET(request) {
const tag = request.nextUrl.searchParams.get('tag')
expireTag(tag)
return Response.json({ revalidated: true, now: Date.now() })
}
```
......@@ -3,13 +3,15 @@ title: revalidatePath
description: API Reference for the revalidatePath function.
---
**Warning**: `revalidatePath` has been deprecated in favor of `expirePath` and will be removed in a future version.
`revalidatePath` allows you to purge [cached data](/docs/app/building-your-application/caching) on-demand for a specific path.
> **Good to know**:
>
> - `revalidatePath` is available in both [Node.js and Edge runtimes](/docs/app/building-your-application/rendering/edge-and-nodejs-runtimes).
> - `revalidatePath` only invalidates the cache when the included path is next visited. This means calling `revalidatePath` with a dynamic route segment will not immediately trigger many revalidations at once. The invalidation only happens when the path is next visited.
> - Currently, `revalidatePath` invalidates all the routes in the [client-side Router Cache](/docs/app/building-your-application/caching#client-side-router-cache). This behavior is temporary and will be updated in the future to apply only to the specific path.
> - Currently, `revalidatePath` invalidates all the routes in the [client-side Router Cache](/docs/app/building-your-application/caching#client-side-router-cache) when used in a server action. This behavior is temporary and will be updated in the future to apply only to the specific path.
> - Using `revalidatePath` invalidates **only the specific path** in the [server-side Route Cache](/docs/app/building-your-application/caching#full-route-cache).
## Parameters
......
......@@ -3,6 +3,8 @@ title: revalidateTag
description: API Reference for the revalidateTag function.
---
**Warning**: `revalidateTag` has been deprecated in favor of `expireTag` and will be removed in a future version.
`revalidateTag` allows you to purge [cached data](/docs/app/building-your-application/caching) on-demand for a specific cache tag.
> **Good to know**:
......
export { unstable_cache } from 'next/dist/server/web/spec-extension/unstable-cache'
export {
revalidateTag,
revalidatePath,
revalidateTag,
expirePath,
expireTag,
} from 'next/dist/server/web/spec-extension/revalidate'
export { unstable_noStore } from 'next/dist/server/web/spec-extension/unstable-no-store'
export { cacheTag as unstable_cacheTag } from 'next/dist/server/use-cache/cache-tag'
/**
......
const cacheExports = {
unstable_cache: require('next/dist/server/web/spec-extension/unstable-cache')
.unstable_cache,
revalidateTag: require('next/dist/server/web/spec-extension/revalidate')
.revalidateTag,
revalidatePath: require('next/dist/server/web/spec-extension/revalidate')
.revalidatePath,
expireTag: require('next/dist/server/web/spec-extension/revalidate')
.expireTag,
expirePath: require('next/dist/server/web/spec-extension/revalidate')
.expirePath,
unstable_noStore:
require('next/dist/server/web/spec-extension/unstable-no-store')
.unstable_noStore,
......@@ -21,6 +28,8 @@ module.exports = cacheExports
exports.unstable_cache = cacheExports.unstable_cache
exports.revalidatePath = cacheExports.revalidatePath
exports.revalidateTag = cacheExports.revalidateTag
exports.expireTag = cacheExports.expireTag
exports.expirePath = cacheExports.expirePath
exports.unstable_noStore = cacheExports.unstable_noStore
exports.unstable_cacheLife = cacheExports.unstable_cacheLife
exports.unstable_cacheTag = cacheExports.unstable_cacheTag
......@@ -689,6 +689,8 @@ declare module 'next/cache' {
export {
revalidateTag,
revalidatePath,
expireTag,
expirePath,
} from 'next/dist/server/web/spec-extension/revalidate'
export { unstable_noStore } from 'next/dist/server/web/spec-extension/unstable-no-store'
......
......@@ -12,20 +12,40 @@ import { workUnitAsyncStorage } from '../../app-render/work-unit-async-storage.e
import { DynamicServerError } from '../../../client/components/hooks-server-context'
/**
* @deprecated this function has been deprecated in favor of expireTag()
* 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}`)
return revalidate([tag], `revalidateTag ${tag}`)
}
/**
* @deprecated this function has been deprecated in favor of expirePath()
* This function allows you to purge [cached data](https://nextjs.org/docs/app/building-your-application/caching) on-demand for a specific path.
*
* Read more: [Next.js Docs: `revalidatePath`](https://nextjs.org/docs/app/api-reference/functions/revalidatePath)
*/
export function revalidatePath(originalPath: string, type?: 'layout' | 'page') {
return expirePath(originalPath, type)
}
/**
* 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: `expireTag`](https://nextjs.org/docs/app/api-reference/functions/expireTag)
*/
export function expireTag(...tags: string[]) {
return revalidate(tags, `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.
*
* Read more: [Next.js Docs: `expirePath`](https://nextjs.org/docs/app/api-reference/functions/expirePath)
*/
export function expirePath(originalPath: string, type?: 'layout' | 'page') {
if (originalPath.length > NEXT_CACHE_SOFT_TAG_MAX_LENGTH) {
console.warn(
`Warning: revalidatePath 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/revalidatePath`
......@@ -42,10 +62,10 @@ export function revalidatePath(originalPath: string, type?: 'layout' | 'page') {
`Warning: a dynamic page path "${originalPath}" was passed to "revalidatePath", but the "type" parameter is missing. This has no effect by default, see more info here https://nextjs.org/docs/app/api-reference/functions/revalidatePath`
)
}
return revalidate(normalizedPath, `revalidatePath ${originalPath}`)
return revalidate([normalizedPath], `revalidatePath ${originalPath}`)
}
function revalidate(tag: string, expression: string) {
function revalidate(tags: string[], expression: string) {
const store = workAsyncStorage.getStore()
if (!store || !store.incrementalCache) {
throw new Error(
......@@ -111,8 +131,11 @@ function revalidate(tag: string, expression: string) {
if (!store.revalidatedTags) {
store.revalidatedTags = []
}
if (!store.revalidatedTags.includes(tag)) {
store.revalidatedTags.push(tag)
for (const tag of tags) {
if (!store.revalidatedTags.includes(tag)) {
store.revalidatedTags.push(tag)
}
}
// TODO: only revalidate if the path matches
......
......@@ -4,13 +4,13 @@
"test/e2e/app-dir/actions/app-action.test.ts": {
"failed": [
"app-dir action handling fetch actions should invalidate client cache when path is revalidated",
"app-dir action handling fetch actions should handle revalidateTag"
"app-dir action handling fetch actions should handle expireTag"
]
},
"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 revalidateTag is used"
"app-dir static/dynamic handling new tags have been specified on subsequent fetch should not fetch from memory cache after expireTag is used"
]
},
"test/e2e/app-dir/metadata/metadata.test.ts": {
......
import {
revalidateTag,
expireTag,
unstable_cacheLife as cacheLife,
unstable_cacheTag,
} from 'next/cache'
......@@ -13,7 +13,7 @@ function InnerComponent({ children }) {
async function refresh() {
'use server'
revalidateTag('hello')
expireTag('hello')
}
async function reload() {
......
import React from 'react'
import { revalidatePath } from 'next/cache'
import { expirePath } 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'
revalidatePath('/test')
expirePath('/test')
}}
>
<button>Submit</button>
......
......@@ -1276,7 +1276,7 @@ describe('app-dir action handling', () => {
}, 5000)
})
it('should handle revalidatePath', async () => {
it('should handle expirePath', async () => {
const browser = await next.browser('/revalidate')
const randomNumber = await browser.elementByCss('#random-number').text()
const justPutIt = await browser.elementByCss('#justputit').text()
......@@ -1299,7 +1299,7 @@ describe('app-dir action handling', () => {
})
})
it('should handle revalidateTag', async () => {
it('should handle expireTag', async () => {
const browser = await next.browser('/revalidate')
const randomNumber = await browser.elementByCss('#random-number').text()
const justPutIt = await browser.elementByCss('#justputit').text()
......@@ -1323,7 +1323,7 @@ describe('app-dir action handling', () => {
})
// TODO: investigate flakey behavior with revalidate
it.skip('should handle revalidateTag + redirect', async () => {
it.skip('should handle expireTag + 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 { revalidatePath } from 'next/cache'
import { expirePath } from 'next/cache'
import { redirect } from 'next/navigation'
export const action = async () => {
console.log('revalidating')
revalidatePath('/delayed-action', 'page')
expirePath('/delayed-action', 'page')
return Math.random()
}
......
'use server'
import { redirect } from 'next/navigation'
import { revalidatePath } from 'next/cache'
import { expirePath } from 'next/cache'
type State = {
errors: Record<string, string>
......@@ -16,7 +16,7 @@ export async function action(previousState: State, formData: FormData) {
}
if (revalidate === 'on') {
revalidatePath('/redirect')
expirePath('/redirect')
}
redirect('/redirect/other')
......
import { revalidateTag } from 'next/cache'
import { expireTag } from 'next/cache'
import { cookies } from 'next/headers'
import Link from 'next/link'
......@@ -25,7 +25,7 @@ export default async function Page() {
id="revalidate-tag"
formAction={async () => {
'use server'
revalidateTag('thankyounext')
expireTag('thankyounext')
}}
>
revalidate thankyounext
......
import { revalidateTag } from 'next/cache'
import { expireTag } 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'
revalidateTag('thankyounext')
revalidateTag('justputit')
expireTag('thankyounext')
expireTag('justputit')
}}
>
revalidate thankyounext
......
import { revalidatePath, revalidateTag } from 'next/cache'
import { expirePath, expireTag } from 'next/cache'
import { redirect } from 'next/navigation'
import Link from 'next/link'
......@@ -60,7 +60,7 @@ export default async function Page() {
id="revalidate-thankyounext"
formAction={async () => {
'use server'
revalidateTag('thankyounext')
expireTag('thankyounext')
}}
>
revalidate thankyounext
......@@ -71,7 +71,7 @@ export default async function Page() {
id="revalidate-justputit"
formAction={async () => {
'use server'
revalidateTag('justputit')
expireTag('justputit')
}}
>
revalidate justputit
......@@ -82,7 +82,7 @@ export default async function Page() {
id="revalidate-path"
formAction={async () => {
'use server'
revalidatePath('/revalidate')
expirePath('/revalidate')
}}
>
revalidate path
......@@ -93,7 +93,7 @@ export default async function Page() {
id="revalidate-path-redirect"
formAction={async () => {
'use server'
revalidateTag('justputit')
expireTag('justputit')
redirect('/revalidate')
}}
>
......@@ -116,7 +116,7 @@ export default async function Page() {
id="redirect-revalidate"
formAction={async () => {
'use server'
revalidateTag('justputit')
expireTag('justputit')
redirect('/revalidate?foo=bar')
}}
>
......@@ -126,7 +126,7 @@ export default async function Page() {
<RedirectClientComponent
action={async () => {
'use server'
revalidateTag('justputit')
expireTag('justputit')
}}
/>
</>
......
'use server'
import { revalidatePath } from 'next/cache'
import { expirePath } from 'next/cache'
let x = 0
export async function inc() {
++x
revalidatePath('/shared')
expirePath('/shared')
}
export async function get() {
......
......@@ -152,7 +152,7 @@ describe('app-dir static/dynamic handling', () => {
expect(data1).not.toBe(data2)
})
it('should not fetch from memory cache after revalidateTag is used', async () => {
it('should not fetch from memory cache after expireTag is used', async () => {
const res1 = await next.fetch('/specify-new-tags/one-tag')
expect(res1.status).toBe(200)
......
import { NextRequest, NextResponse } from 'next/server'
import { revalidatePath } from 'next/cache'
import { expirePath } 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)
revalidatePath(path)
expirePath(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 { revalidatePath } from 'next/cache'
import { expirePath } 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)
revalidatePath(path)
expirePath(path)
return NextResponse.json({ revalidated: true, now: Date.now() })
} catch (err) {
console.error('Failed to revalidate', path, err)
......
import { NextResponse } from 'next/server'
import { revalidateTag } from 'next/cache'
import { expireTag } from 'next/cache'
export const revalidate = 0
export const runtime = 'edge'
export async function GET(req) {
const tag = req.nextUrl.searchParams.get('tag')
revalidateTag(tag)
expireTag(tag)
return NextResponse.json({ revalidated: true, now: Date.now() })
}
import { NextResponse } from 'next/server'
import { revalidateTag } from 'next/cache'
import { expireTag } from 'next/cache'
export const revalidate = 0
export async function GET(req) {
const tag = req.nextUrl.searchParams.get('tag')
revalidateTag(tag)
expireTag(tag)
return NextResponse.json({ revalidated: true, now: Date.now() })
}
import { revalidateTag, unstable_cache } from 'next/cache'
import { expireTag, 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 revalidateTag('no-store-fn')
await expireTag('no-store-fn')
}
const cachedData = await unstable_cache(
......
import { revalidateTag, unstable_cache } from 'next/cache'
import { expireTag, 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 revalidateTag('undefined-value-data')
await expireTag('undefined-value-data')
}
const cachedData = await unstable_cache(
......
import { revalidateTag, unstable_cache } from 'next/cache'
import { expireTag, 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 revalidateTag('random-value-data')
await expireTag('random-value-data')
}
const cachedData = await unstable_cache(
......
'use server'
import { revalidatePath } from 'next/cache'
import { expirePath } from 'next/cache'
export async function doAction() {
revalidatePath('/en/photos/1/view')
expirePath('/en/photos/1/view')
// sleep 1s
await new Promise((resolve) => setTimeout(resolve, 1000))
return Math.random()
......
'use server'
import { revalidatePath } from 'next/cache'
import { expirePath } from 'next/cache'
export async function action() {
revalidatePath('/', 'layout')
expirePath('/', 'layout')
return true
}
import { revalidatePath } from 'next/cache'
import { expirePath } 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)
revalidatePath(path)
expirePath(path)
}
const WAIT_BEFORE_REVALIDATING_DEFAULT = 1000
......
import { revalidateTimestampPage } from '../revalidate'
export async function POST(/** @type {Request} */ request) {
// we can't call revalidatePath from middleware, so we need to do it from here instead
// we can't call expirePath 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 `unstable_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 `revalidatePath` inside `unstable_after`
// So instead this test relies on calling `expirePath` inside `unstable_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 revalidatePath from middleware, so we need to do it via an endpoint instead
// we can't call expirePath 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 { revalidatePath } from 'next/cache'
import { expirePath } from 'next/cache'
import { addData } from '../../actions'
export default function Page() {
......@@ -9,7 +9,7 @@ export default function Page() {
await addData(new Date().toISOString())
revalidatePath('/', 'layout')
expirePath('/', 'layout')
}
return (
......
'use server'
import { revalidatePath } from 'next/cache'
import { expirePath } from 'next/cache'
import { redirect } from 'next/navigation'
let data = []
......@@ -25,5 +25,5 @@ export async function redirectAction() {
export async function clearData() {
data = []
revalidatePath('/')
expirePath('/')
}
'use server'
import { revalidatePath } from 'next/cache'
import { expirePath } from 'next/cache'
export async function revalidateAction() {
console.log('revalidate action')
revalidatePath('/')
expirePath('/')
return {
success: true,
}
......
import { revalidatePath } from 'next/cache'
import { expirePath } 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'
}
revalidatePath(pathname, type)
expirePath(pathname, type)
}
return new Response(
......
import { revalidateTag } from 'next/cache'
import { expireTag } from 'next/cache'
export const POST = async () => {
revalidateTag('unstable-cache-fetch')
expireTag('unstable-cache-fetch')
return new Response('OK', { status: 200 })
}
import { NextResponse } from 'next/server'
import { revalidatePath } from 'next/cache'
import { expirePath } from 'next/cache'
export async function GET(req) {
revalidatePath('/')
expirePath('/')
return NextResponse.json({ revalidated: true, now: Date.now() })
}
import { NextResponse } from 'next/server'
import { revalidateTag } from 'next/cache'
import { expireTag } from 'next/cache'
export async function GET(req) {
revalidateTag('thankyounext')
expireTag('thankyounext')
return NextResponse.json({ revalidated: true, now: Date.now() })
}
......@@ -6,7 +6,7 @@ describe('app-dir revalidate-dynamic', () => {
})
if (isNextStart) {
it('should correctly mark a route handler that uses revalidateTag as dynamic', async () => {
it('should correctly mark a route handler that uses expireTag as dynamic', async () => {
expect(next.cliOutput).toContain('ƒ /api/revalidate-path')
expect(next.cliOutput).toContain('ƒ /api/revalidate-tag')
})
......
'use server'
import { revalidateTag } from 'next/cache'
import { expireTag } from 'next/cache'
export const revalidate = async (
tag: string
): Promise<{ revalidated: boolean }> => {
revalidateTag(tag)
expireTag(tag)
return { revalidated: true }
}
'use server'
import Link from 'next/link'
import { revalidateTag } from 'next/cache'
import { expireTag } from 'next/cache'
const RevalidateViaPage = async ({
searchParams,
......@@ -9,7 +9,7 @@ const RevalidateViaPage = async ({
searchParams: Promise<{ tag: string }>
}) => {
const { tag } = await searchParams
revalidateTag(tag)
expireTag(tag)
return (
<div className="flex flex-col items-center justify-center h-screen">
......
import { nextTestSetup } from 'e2e-utils'
import { getRedboxHeader, retry } from 'next-test-utils'
describe('revalidateTag-rsc', () => {
describe('expireTag-rsc', () => {
const { next, isNextDev, isNextDeploy } = nextTestSetup({
files: __dirname,
})
it('should revalidate fetch cache if revalidateTag invoked via server action', async () => {
it('should revalidate fetch cache if expireTag 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('revalidateTag-rsc', () => {
if (!isNextDeploy) {
// skipped in deploy because it uses `next.cliOutput`
it('should error if revalidateTag is called during render', async () => {
it('should error if expireTag is called during render', async () => {
const browser = await next.browser('/')
await browser.elementByCss('#revalidate-via-page').click()
if (isNextDev) {
await retry(async () => {
expect(await getRedboxHeader(browser)).toContain(
'Route /revalidate_via_page used "revalidateTag data"'
'Route /revalidate_via_page used "expireTag data"'
)
})
} else {
......@@ -42,7 +42,7 @@ describe('revalidateTag-rsc', () => {
}
expect(next.cliOutput).toContain(
'Route /revalidate_via_page used "revalidateTag data"'
'Route /revalidate_via_page used "expireTag data"'
)
})
}
......
import React from 'react'
import { revalidatePath, revalidateTag } from 'next/cache'
import { expirePath, expireTag } from 'next/cache'
export function RevalidateButtons() {
return (
......@@ -8,7 +8,7 @@ export function RevalidateButtons() {
id="revalidate-a"
formAction={async () => {
'use server'
revalidateTag('a')
expireTag('a')
}}
>
revalidate a
......@@ -17,7 +17,7 @@ export function RevalidateButtons() {
id="revalidate-b"
formAction={async () => {
'use server'
revalidateTag('b')
expireTag('b')
}}
>
revalidate b
......@@ -26,7 +26,7 @@ export function RevalidateButtons() {
id="revalidate-c"
formAction={async () => {
'use server'
revalidateTag('c')
expireTag('c')
}}
>
revalidate c
......@@ -35,7 +35,7 @@ export function RevalidateButtons() {
id="revalidate-f"
formAction={async () => {
'use server'
revalidateTag('f')
expireTag('f')
}}
>
revalidate f
......@@ -44,7 +44,7 @@ export function RevalidateButtons() {
id="revalidate-r"
formAction={async () => {
'use server'
revalidateTag('r')
expireTag('r')
}}
>
revalidate r
......@@ -53,7 +53,7 @@ export function RevalidateButtons() {
id="revalidate-path"
formAction={async () => {
'use server'
revalidatePath('/cache-tag')
expirePath('/cache-tag')
}}
>
revalidate path
......
import { revalidateTag, unstable_cacheTag as cacheTag } from 'next/cache'
import { expireTag, unstable_cacheTag as cacheTag } from 'next/cache'
async function refresh() {
'use server'
revalidateTag('home')
expireTag('home')
}
export default async function Page() {
......
......@@ -177,12 +177,12 @@ describe('use-cache', () => {
// TODO: pending tags handling on deploy
if (!isNextDeploy) {
it('should update after revalidateTag correctly', async () => {
it('should update after expireTag correctly', async () => {
const browser = await next.browser('/cache-tag')
const initial = await browser.elementByCss('#a').text()
// Bust the ISR cache first, to populate the in-memory cache for the
// subsequent revalidateTag calls.
// subsequent expireTag calls.
await browser.elementByCss('#revalidate-path').click()
await retry(async () => {
expect(await browser.elementByCss('#a').text()).not.toBe(initial)
......@@ -313,7 +313,7 @@ describe('use-cache', () => {
})
})
it('should be able to revalidate a page using revalidateTag', async () => {
it('should be able to revalidate a page using expireTag', async () => {
const browser = await next.browser(`/form`)
const time1 = await browser.waitForElementByCss('#t').text()
......
'use server'
import { revalidatePath } from 'next/cache'
import { expirePath } from 'next/cache'
export async function revalidateSelf() {
revalidatePath('/app/self-revalidate')
expirePath('/app/self-revalidate')
}
import { revalidateTag } from 'next/cache'
import { expireTag } from 'next/cache'
import { NextRequest, NextResponse } from 'next/server'
export const dynamic = 'force-dynamic'
export function GET(req: NextRequest) {
for (let i = 0; i < 130; i++) {
revalidateTag(`thankyounext-${i}`)
expireTag(`thankyounext-${i}`)
}
return NextResponse.json({ done: true })
}
import { revalidateTag } from 'next/cache'
import { expireTag } from 'next/cache'
import { NextRequest, NextResponse } from 'next/server'
export const dynamic = 'force-dynamic'
export function GET(req: NextRequest) {
revalidateTag('thankyounext')
expireTag('thankyounext')
return NextResponse.json({ done: true })
}
import { NextResponse } from 'next/server'
import { revalidatePath } from 'next/cache'
import { expirePath } from 'next/cache'
export async function GET() {
revalidatePath('/')
expirePath('/')
return NextResponse.json({ success: true })
}
......@@ -153,8 +153,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 revalidatePath",
"app-dir action handling fetch actions should handle revalidateTag",
"app-dir action handling fetch actions should handle expirePath",
"app-dir action handling fetch actions should handle expireTag",
"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",
......@@ -210,7 +210,7 @@
"app-dir action handling should not expose action content in sourcemaps"
],
"pending": [
"app-dir action handling fetch actions should handle revalidateTag + redirect",
"app-dir action handling fetch actions should handle expireTag + redirect",
"app-dir action handling server actions render client components client component imported action should support importing client components from actions"
],
"flakey": [],
......@@ -3448,7 +3448,7 @@
},
"test/e2e/app-dir/revalidate-dynamic/revalidate-dynamic.test.ts": {
"passed": [
"app-dir revalidate-dynamic should correctly mark a route handler that uses revalidateTag as dynamic",
"app-dir revalidate-dynamic should correctly mark a route handler that uses expireTag 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"
],
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