Unverified Commit 864f0653 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Add updated app dir cache handling (#48516)

This adds the discussed updated cache handling for app dir for more fine
grained control over the cached values. Also adds initial
`revalidateTag` and `revalidatePath` exports from `next/server` although
export location may change.

Continuation of https://github.com/vercel/next.js/pull/47720

x-ref: [slack
thread](https://vercel.slack.com/archives/C042LHPJ1NX/p1681404363048459)
parent 33586b60
......@@ -13,3 +13,6 @@ export { userAgent } from 'next/dist/server/web/spec-extension/user-agent'
export { URLPattern } from 'next/dist/compiled/@edge-runtime/primitives/url'
export { ImageResponse } from 'next/dist/server/web/spec-extension/image-response'
export type { ImageResponseOptions } from 'next/dist/compiled/@vercel/og/types'
export { unstable_cache } from 'next/dist/server/web/spec-extension/unstable-cache'
export { unstable_revalidatePath } from 'next/dist/server/web/spec-extension/unstable-revalidate-path'
export { unstable_revalidateTag } from 'next/dist/server/web/spec-extension/unstable-revalidate-tag'
......@@ -5,6 +5,14 @@ const serverExports = {
.NextResponse,
ImageResponse: require('next/dist/server/web/spec-extension/image-response')
.ImageResponse,
unstable_cache: require('next/dist/server/web/spec-extension/unstable-cache')
.unstable_cache,
unstable_revalidateTag:
require('next/dist/server/web/spec-extension/unstable-revalidate-tag')
.unstable_revalidateTag,
unstable_revalidatePath:
require('next/dist/server/web/spec-extension/unstable-revalidate-path')
.unstable_revalidatePath,
userAgentFromString: require('next/dist/server/web/spec-extension/user-agent')
.userAgentFromString,
userAgent: require('next/dist/server/web/spec-extension/user-agent')
......@@ -24,6 +32,9 @@ module.exports = serverExports
exports.NextRequest = serverExports.NextRequest
exports.NextResponse = serverExports.NextResponse
exports.ImageResponse = serverExports.ImageResponse
exports.unstable_cache = serverExports.unstable_cache
exports.unstable_revalidatePath = serverExports.unstable_revalidatePath
exports.unstable_revalidateTag = serverExports.unstable_revalidateTag
exports.userAgentFromString = serverExports.userAgentFromString
exports.userAgent = serverExports.userAgent
exports.URLPattern = serverExports.URLPattern
......@@ -100,4 +100,7 @@ export const NextBuildContext: Partial<{
clientRouterFilters: Parameters<
typeof getBaseWebpackConfig
>[1]['clientRouterFilters']
previewModeId: string
fetchCacheKeyPrefix?: string
allowedRevalidateHeaderKeys?: string[]
}> = {}
......@@ -2796,6 +2796,11 @@ export default async function build(
notFoundRoutes: ssgNotFoundPaths,
preview: previewProps,
}
NextBuildContext.previewModeId = previewProps.previewModeId
NextBuildContext.fetchCacheKeyPrefix =
config.experimental.fetchCacheKeyPrefix
NextBuildContext.allowedRevalidateHeaderKeys =
config.experimental.allowedRevalidateHeaderKeys
await promises.writeFile(
path.join(distDir, PRERENDER_MANIFEST),
......
......@@ -107,6 +107,9 @@ export async function webpackBuildImpl(
reactProductionProfiling: NextBuildContext.reactProductionProfiling!,
noMangling: NextBuildContext.noMangling!,
clientRouterFilters: NextBuildContext.clientRouterFilters!,
previewModeId: NextBuildContext.previewModeId!,
allowedRevalidateHeaderKeys: NextBuildContext.allowedRevalidateHeaderKeys!,
fetchCacheKeyPrefix: NextBuildContext.fetchCacheKeyPrefix!,
}
const configs = await runWebpackSpan
......
......@@ -186,6 +186,9 @@ export function getDefineEnv({
isEdgeServer,
middlewareMatchers,
clientRouterFilters,
previewModeId,
fetchCacheKeyPrefix,
allowedRevalidateHeaderKeys,
}: {
dev?: boolean
distDir: string
......@@ -198,6 +201,9 @@ export function getDefineEnv({
clientRouterFilters: Parameters<
typeof getBaseWebpackConfig
>[1]['clientRouterFilters']
previewModeId?: string
fetchCacheKeyPrefix?: string
allowedRevalidateHeaderKeys?: string[]
}) {
return {
// internal field to identify the plugin config
......@@ -237,6 +243,12 @@ export function getDefineEnv({
'process.env.NEXT_RUNTIME': JSON.stringify(
isEdgeServer ? 'edge' : isNodeServer ? 'nodejs' : undefined
),
'process.env.__NEXT_FETCH_CACHE_KEY_PREFIX':
JSON.stringify(fetchCacheKeyPrefix),
'process.env.__NEXT_PREVIEW_MODE_ID': JSON.stringify(previewModeId),
'process.env.__NEXT_ALLOWED_REVALIDATE_HEADERS': JSON.stringify(
allowedRevalidateHeaderKeys
),
'process.env.__NEXT_MIDDLEWARE_MATCHERS': JSON.stringify(
middlewareMatchers || []
),
......@@ -643,6 +655,9 @@ export default async function getBaseWebpackConfig(
resolvedBaseUrl,
supportedBrowsers,
clientRouterFilters,
previewModeId,
fetchCacheKeyPrefix,
allowedRevalidateHeaderKeys,
}: {
buildId: string
config: NextConfigComplete
......@@ -670,6 +685,9 @@ export default async function getBaseWebpackConfig(
import('../shared/lib/bloom-filter').BloomFilter['export']
>
}
previewModeId?: string
fetchCacheKeyPrefix?: string
allowedRevalidateHeaderKeys?: string[]
}
): Promise<webpack.Configuration> {
const isClient = compilerType === COMPILER_NAMES.client
......@@ -2125,6 +2143,9 @@ export default async function getBaseWebpackConfig(
isEdgeServer,
middlewareMatchers,
clientRouterFilters,
previewModeId,
fetchCacheKeyPrefix,
allowedRevalidateHeaderKeys,
})
),
isClient &&
......
......@@ -19,6 +19,7 @@ export default function middlewareLoader(this: any) {
return `
import { adapter, enhanceGlobals } from 'next/dist/esm/server/web/adapter'
import {IncrementalCache} from 'next/dist/esm/server/lib/incremental-cache'
enhanceGlobals()
......@@ -32,6 +33,7 @@ export default function middlewareLoader(this: any) {
export default function (opts) {
return adapter({
...opts,
IncrementalCache,
page: ${JSON.stringify(page)},
handler,
})
......
......@@ -90,6 +90,7 @@ export default async function edgeSSRLoader(this: any) {
const transformed = `
import { adapter, enhanceGlobals } from 'next/dist/esm/server/web/adapter'
import { getRender } from 'next/dist/esm/build/webpack/loaders/next-edge-ssr-loader/render'
import {IncrementalCache} from 'next/dist/esm/server/lib/incremental-cache'
enhanceGlobals()
......@@ -164,6 +165,7 @@ export default async function edgeSSRLoader(this: any) {
export default function(opts) {
return adapter({
...opts,
IncrementalCache,
handler: render
})
}`
......
......@@ -717,6 +717,7 @@ export default async function exportApp(
debugOutput: options.debugOutput,
isrMemoryCacheSize: nextConfig.experimental.isrMemoryCacheSize,
fetchCache: nextConfig.experimental.appDir,
fetchCacheKeyPrefix: nextConfig.experimental.fetchCacheKeyPrefix,
incrementalCacheHandlerPath:
nextConfig.experimental.incrementalCacheHandlerPath,
})
......
......@@ -93,6 +93,7 @@ interface ExportPageInput {
isrMemoryCacheSize?: NextConfigComplete['experimental']['isrMemoryCacheSize']
fetchCache?: boolean
incrementalCacheHandlerPath?: string
fetchCacheKeyPrefix?: string
nextConfigOutput?: NextConfigComplete['output']
}
......@@ -152,6 +153,7 @@ export default async function exportPage({
debugOutput,
isrMemoryCacheSize,
fetchCache,
fetchCacheKeyPrefix,
incrementalCacheHandlerPath,
}: ExportPageInput): Promise<ExportPageResults> {
setHttpClientAndAgentOptions({
......@@ -350,12 +352,13 @@ export default async function exportPage({
CacheHandler = require(incrementalCacheHandlerPath)
CacheHandler = CacheHandler.default || CacheHandler
}
curRenderOpts.incrementalCache = new IncrementalCache({
const incrementalCache = new IncrementalCache({
dev: false,
requestHeaders: {},
flushToDisk: true,
fetchCache: true,
maxMemoryCacheSize: isrMemoryCacheSize,
fetchCacheKeyPrefix,
getPrerenderManifest: () => ({
version: 4,
routes: {},
......@@ -377,6 +380,8 @@ export default async function exportPage({
serverDistDir: join(distDir, 'server'),
CurCacheHandler: CacheHandler,
})
;(globalThis as any).__incrementalCache = incrementalCache
curRenderOpts.incrementalCache = incrementalCache
}
const isDynamicUsageError = (err: any) =>
......
......@@ -2,6 +2,10 @@ import type { ServerRuntime } from '../../types'
export const NEXT_QUERY_PARAM_PREFIX = 'nxtP'
export const PRERENDER_REVALIDATE_HEADER = 'x-prerender-revalidate'
export const PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER =
'x-prerender-revalidate-if-generated'
// in seconds
export const CACHE_ONE_YEAR = 31536000
......
......@@ -4,6 +4,10 @@ import type { CookieSerializeOptions } from 'next/dist/compiled/cookie'
import type { NextApiRequest, NextApiResponse } from '../../shared/lib/utils'
import { HeadersAdapter } from '../web/spec-extension/adapters/headers'
import {
PRERENDER_REVALIDATE_HEADER,
PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER,
} from '../../lib/constants'
export type NextApiRequestCookies = Partial<{ [key: string]: string }>
export type NextApiRequestQuery = Partial<{ [key: string]: string | string[] }>
......@@ -72,10 +76,6 @@ export function redirect(
return res
}
export const PRERENDER_REVALIDATE_HEADER = 'x-prerender-revalidate'
export const PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER =
'x-prerender-revalidate-if-generated'
export function checkIsOnDemandRevalidate(
req: Request | IncomingMessage | BaseNextRequest,
previewProps: __ApiPreviewProps
......
import type { IncomingMessage, ServerResponse } from 'http'
import type { NextApiRequest, NextApiResponse } from '../../shared/lib/utils'
import type { PageConfig, ResponseLimit, SizeLimit } from 'next/types'
import {
checkIsOnDemandRevalidate,
PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER,
__ApiPreviewProps,
} from '.'
import { checkIsOnDemandRevalidate, __ApiPreviewProps } from '.'
import type { BaseNextRequest, BaseNextResponse } from '../base-http'
import type { CookieSerializeOptions } from 'next/dist/compiled/cookie'
import type { PreviewData } from 'next/types'
......@@ -26,7 +22,6 @@ import {
clearPreviewData,
sendError,
ApiError,
PRERENDER_REVALIDATE_HEADER,
COOKIE_NAME_PRERENDER_BYPASS,
COOKIE_NAME_PRERENDER_DATA,
SYMBOL_PREVIEW_DATA,
......@@ -37,6 +32,10 @@ import { getTracer } from '../lib/trace/tracer'
import { NodeSpan } from '../lib/trace/constants'
import { RequestCookies } from '../web/spec-extension/cookies'
import { HeadersAdapter } from '../web/spec-extension/adapters/headers'
import {
PRERENDER_REVALIDATE_HEADER,
PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER,
} from '../../lib/constants'
export function tryGetPreviewData(
req: IncomingMessage | BaseNextRequest | Request,
......
......@@ -54,7 +54,10 @@ export const StaticGenerationAsyncStorageWrapper: AsyncStorageWrapper<
const store: StaticGenerationStore = {
isStaticGeneration,
pathname,
incrementalCache: renderOpts.incrementalCache,
incrementalCache:
// we fallback to a global incremental cache for edge-runtime locally
// so that it can access the fs cache without mocks
renderOpts.incrementalCache || (globalThis as any).__incrementalCache,
isRevalidate: renderOpts.isRevalidate,
isPrerendering: renderOpts.nextExport,
fetchCache: renderOpts.fetchCache,
......
......@@ -328,6 +328,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
protected abstract getIncrementalCache(options: {
requestHeaders: Record<string, undefined | string | string[]>
requestProtocol: 'http' | 'https'
}): import('./lib/incremental-cache').IncrementalCache
protected abstract getResponseCache(options: {
......@@ -1056,8 +1057,21 @@ export default abstract class Server<ServerOptions extends Options = Options> {
!(globalThis as any).__incrementalCache &&
!getRequestMeta(req, '_nextIncrementalCache')
) {
let protocol: 'http:' | 'https:' = 'https:'
try {
const parsedFullUrl = new URL(
getRequestMeta(req, '__NEXT_INIT_URL') || '/',
'http://n'
)
protocol = parsedFullUrl.protocol as 'https:' | 'http:'
} catch (_) {}
const incrementalCache = this.getIncrementalCache({
requestHeaders: Object.assign({}, req.headers),
requestProtocol: protocol.substring(0, protocol.length - 1) as
| 'http'
| 'https',
})
addRequestMeta(req, '_nextIncrementalCache', incrementalCache)
}
......@@ -1556,12 +1570,24 @@ export default abstract class Server<ServerOptions extends Options = Options> {
ssgCacheKey =
ssgCacheKey === '/index' && pathname === '/' ? '/' : ssgCacheKey
}
let protocol: 'http:' | 'https:' = 'https:'
try {
const parsedFullUrl = new URL(
getRequestMeta(req, '__NEXT_INIT_URL') || '/',
'http://n'
)
protocol = parsedFullUrl.protocol as 'https:' | 'http:'
} catch (_) {}
// use existing incrementalCache instance if available
const incrementalCache =
(globalThis as any).__incrementalCache ||
this.getIncrementalCache({
requestHeaders: Object.assign({}, req.headers),
requestProtocol: protocol.substring(0, protocol.length - 1) as
| 'http'
| 'https',
})
let isRevalidate = false
......@@ -1991,6 +2017,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
body: isDataReq
? RenderResult.fromStatic(cachedData.pageData as string)
: cachedData.html,
revalidateOptions,
}
}
......
......@@ -163,12 +163,6 @@ export class AppRouteRouteModule extends RouteModule<
// If we've already setup, then return.
if (this.hasSetup) return
// Patch the global fetch.
patchFetch({
serverHooks: this.serverHooks,
staticGenerationAsyncStorage: this.staticGenerationAsyncStorage,
})
// Mark the module as setup. The following warnings about the userland
// module will run if we're in development. If the module files are modified
// when in development, then the require cache will be busted for it and
......@@ -324,10 +318,22 @@ export class AppRouteRouteModule extends RouteModule<
'next.route': route,
},
},
() =>
handler(wrappedRequest, {
async () => {
// Patch the global fetch.
patchFetch({
serverHooks: this.serverHooks,
staticGenerationAsyncStorage:
this.staticGenerationAsyncStorage,
})
const res = await handler(wrappedRequest, {
params: context.params,
})
await Promise.all(
staticGenerationStore.pendingRevalidates || []
)
return res
}
)
}
)
......
......@@ -73,6 +73,29 @@ export default class FetchCache implements CacheHandler {
}
}
public async revalidateTag(tag: string) {
if (this.debug) {
console.log('revalidateTag', tag)
}
try {
const res = await fetch(
`${this.cacheEndpoint}/v1/suspense-cache/revalidate?tags=${tag}`,
{
method: 'POST',
headers: this.headers,
// @ts-expect-error
next: { internal: true },
}
)
if (!res.ok) {
throw new Error(`Request failed with status ${res.status}.`)
}
} catch (err) {
console.warn(`Failed to revalidate tag ${tag}`, err)
}
}
public async get(
key: string,
fetchCache?: boolean,
......@@ -103,7 +126,10 @@ export default class FetchCache implements CacheHandler {
`${this.cacheEndpoint}/v1/suspense-cache/${key}`,
{
method: 'GET',
headers: this.headers,
headers: {
...this.headers,
'X-Vercel-Cache-Item-Name': fetchUrl,
} as any,
next: fetchParams as NextFetchRequestConfig,
}
)
......@@ -139,7 +165,7 @@ export default class FetchCache implements CacheHandler {
// if it's already stale set it to a time in the past
// if not derive last modified from age
lastModified:
cacheState === 'stale'
cacheState !== 'fresh'
? Date.now() - CACHE_ONE_YEAR
: Date.now() - parseInt(age || '0', 10) * 1000,
}
......@@ -147,7 +173,9 @@ export default class FetchCache implements CacheHandler {
console.log(
`got fetch cache entry for ${key}, duration: ${
Date.now() - start
}ms, size: ${Object.keys(cached).length}`
}ms, size: ${
Object.keys(cached).length
}, cache-state: ${cacheState}`
)
}
......@@ -193,6 +221,16 @@ export default class FetchCache implements CacheHandler {
data.data.headers['cache-control']
}
const body = JSON.stringify(data)
const headers = { ...this.headers }
if (data !== null && 'data' in data && data.data.tags) {
headers['x-vercel-cache-tags'] = data.data.tags.join(',')
}
if (this.debug) {
console.log('set cache', key, {
tags: headers['x-vercel-cache-tags'],
})
}
const fetchParams: NextFetchCacheParams = {
internal: true,
fetchType: 'fetch-set',
......@@ -203,7 +241,10 @@ export default class FetchCache implements CacheHandler {
`${this.cacheEndpoint}/v1/suspense-cache/${key}`,
{
method: 'POST',
headers: this.headers,
headers: {
...headers,
'X-Vercel-Cache-Item-Name': fetchUrl || '',
},
body: body,
next: fetchParams as NextFetchRequestConfig,
}
......
import LRUCache from 'next/dist/compiled/lru-cache'
import path from '../../../shared/lib/isomorphic/path'
import { CachedFetchValue } from '../../response-cache'
import { CacheFs } from '../../../shared/lib/utils'
import type { CacheHandler, CacheHandlerContext, CacheHandlerValue } from './'
import { CACHE_ONE_YEAR } from '../../../lib/constants'
type FileSystemCacheContext = Omit<
CacheHandlerContext,
......@@ -11,13 +13,19 @@ type FileSystemCacheContext = Omit<
serverDistDir: string
}
type TagsManifest = {
version: 1
items: { [tag: string]: { keys: string[]; revalidatedAt: number } }
}
let memoryCache: LRUCache<string, CacheHandlerValue> | undefined
let tagsManifest: TagsManifest | undefined
export default class FileSystemCache implements CacheHandler {
private fs: FileSystemCacheContext['fs']
private flushToDisk?: FileSystemCacheContext['flushToDisk']
private serverDistDir: FileSystemCacheContext['serverDistDir']
private appDir: boolean
private tagsManifestPath?: string
constructor(ctx: FileSystemCacheContext) {
this.fs = ctx.fs
......@@ -47,6 +55,76 @@ export default class FileSystemCache implements CacheHandler {
},
})
}
if (this.serverDistDir && this.fs) {
this.tagsManifestPath = path.join(
this.serverDistDir,
'..',
'cache',
'fetch-cache',
'tags-manifest.json'
)
this.loadTagsManifest()
}
}
private loadTagsManifest() {
if (!this.tagsManifestPath || !this.fs) return
try {
tagsManifest = JSON.parse(
this.fs.readFileSync(this.tagsManifestPath).toString('utf8')
)
} catch (err: any) {
tagsManifest = { version: 1, items: {} }
}
}
async setTags(key: string, tags: string[]) {
this.loadTagsManifest()
if (!tagsManifest || !this.tagsManifestPath) {
return
}
for (const tag of tags) {
const data = tagsManifest.items[tag] || { keys: [] }
if (!data.keys.includes(key)) {
data.keys.push(key)
}
tagsManifest.items[tag] = data
}
try {
await this.fs.mkdir(path.dirname(this.tagsManifestPath))
await this.fs.writeFile(
this.tagsManifestPath,
JSON.stringify(tagsManifest || {})
)
} catch (err: any) {
console.warn('Failed to update tags manifest.', err)
}
}
public async revalidateTag(tag: string) {
// we need to ensure the tagsManifest is refreshed
// since separate workers can be updating it at the same
// time and we can't flush out of sync data
this.loadTagsManifest()
if (!tagsManifest || !this.tagsManifestPath) {
return
}
const data = tagsManifest.items[tag] || { keys: [] }
data.revalidatedAt = Date.now()
tagsManifest.items[tag] = data
try {
await this.fs.mkdir(path.dirname(this.tagsManifestPath))
await this.fs.writeFile(
this.tagsManifestPath,
JSON.stringify(tagsManifest || {})
)
} catch (err: any) {
console.warn('Failed to update tags manifest.', err)
}
}
public async get(key: string, fetchCache?: boolean) {
......@@ -87,14 +165,15 @@ export default class FileSystemCache implements CacheHandler {
pathname: fetchCache ? key : `${key}.html`,
fetchCache,
})
const fileData = await this.fs.readFile(filePath)
const fileData = (await this.fs.readFile(filePath)).toString('utf-8')
const { mtime } = await this.fs.stat(filePath)
if (fetchCache) {
const lastModified = mtime.getTime()
const parsedData: CachedFetchValue = JSON.parse(fileData)
data = {
lastModified,
value: JSON.parse(fileData.toString('utf8')),
value: parsedData,
}
} else {
const pageData = isAppPath
......@@ -124,7 +203,7 @@ export default class FileSystemCache implements CacheHandler {
lastModified: mtime.getTime(),
value: {
kind: 'PAGE',
html: fileData.toString('utf8'),
html: fileData,
pageData,
},
}
......@@ -137,6 +216,22 @@ export default class FileSystemCache implements CacheHandler {
// unable to get data from disk
}
}
if (data && data?.value?.kind === 'FETCH') {
this.loadTagsManifest()
const innerData = data.value.data
const isStale = innerData.tags?.some((tag) => {
return (
tagsManifest?.items[tag]?.revalidatedAt &&
tagsManifest?.items[tag].revalidatedAt >=
(data?.lastModified || Date.now())
)
})
if (isStale) {
data.lastModified = Date.now() - CACHE_ONE_YEAR
}
}
return data || null
}
......@@ -186,6 +281,7 @@ export default class FileSystemCache implements CacheHandler {
})
await this.fs.mkdir(path.dirname(filePath))
await this.fs.writeFile(filePath, JSON.stringify(data))
await this.setTags(key, data.data.tags || [])
}
}
......
......@@ -53,6 +53,8 @@ export class CacheHandler {
_fetchUrl?: string,
_fetchIdx?: number
): Promise<void> {}
public async revalidateTag(_tag: string): Promise<void> {}
}
export class IncrementalCache {
......@@ -60,6 +62,8 @@ export class IncrementalCache {
cacheHandler?: CacheHandler
prerenderManifest: PrerenderManifest
requestHeaders: Record<string, undefined | string | string[]>
requestProtocol?: 'http' | 'https'
allowedRevalidateHeaderKeys?: string[]
minimalMode?: boolean
fetchCacheKeyPrefix?: string
......@@ -72,10 +76,12 @@ export class IncrementalCache {
minimalMode,
serverDistDir,
requestHeaders,
requestProtocol,
maxMemoryCacheSize,
getPrerenderManifest,
fetchCacheKeyPrefix,
CurCacheHandler,
allowedRevalidateHeaderKeys,
}: {
fs?: CacheFs
dev: boolean
......@@ -84,6 +90,8 @@ export class IncrementalCache {
minimalMode?: boolean
serverDistDir?: string
flushToDisk?: boolean
requestProtocol?: 'http' | 'https'
allowedRevalidateHeaderKeys?: string[]
requestHeaders: IncrementalCache['requestHeaders']
maxMemoryCacheSize?: number
getPrerenderManifest: () => PrerenderManifest
......@@ -94,7 +102,6 @@ export class IncrementalCache {
if (fs && serverDistDir) {
CurCacheHandler = FileSystemCache
}
if (minimalMode && fetchCache) {
CurCacheHandler = FetchCache
}
......@@ -107,6 +114,8 @@ export class IncrementalCache {
this.dev = dev
this.minimalMode = minimalMode
this.requestHeaders = requestHeaders
this.requestProtocol = requestProtocol
this.allowedRevalidateHeaderKeys = allowedRevalidateHeaderKeys
this.prerenderManifest = getPrerenderManifest()
this.fetchCacheKeyPrefix = fetchCacheKeyPrefix
......@@ -152,6 +161,10 @@ export class IncrementalCache {
return fetchCache ? pathname : normalizePagePath(pathname)
}
async revalidateTag(tag: string) {
return this.cacheHandler?.revalidateTag?.(tag)
}
// x-ref: https://github.com/facebook/react/blob/2655c9354d8e1c54ba888444220f63e836925caa/packages/react/src/ReactFetch.js#L23
async fetchCacheKey(
url: string,
......@@ -159,7 +172,7 @@ export class IncrementalCache {
): Promise<string> {
// this should be bumped anytime a fix is made to cache entries
// that should bust the cache
const MAIN_KEY_PREFIX = 'v2'
const MAIN_KEY_PREFIX = 'v3'
let cacheKey: string
const bodyChunks: string[] = []
......
......@@ -71,14 +71,17 @@ export function patchFetch({
}
let revalidate: number | undefined | false = undefined
// RequestInit doesn't keep extra fields e.g. next so it's
// only available if init is used separate
let curRevalidate =
typeof init?.next?.revalidate !== 'undefined'
? init?.next?.revalidate
const getNextField = (field: 'revalidate' | 'tags') => {
return typeof init?.next?.[field] !== 'undefined'
? init?.next?.[field]
: isRequestInput
? (input as any).next?.revalidate
? (input as any).next?.[field]
: undefined
}
// RequestInit doesn't keep extra fields e.g. next so it's
// only available if init is used separate
let curRevalidate = getNextField('revalidate')
const tags: undefined | string[] = getNextField('tags')
const isOnlyCache = staticGenerationStore.fetchCache === 'only-cache'
const isForceCache = staticGenerationStore.fetchCache === 'force-cache'
......@@ -129,6 +132,15 @@ export function patchFetch({
revalidate = 0
}
if (isOnlyNoStore) {
if (_cache === 'force-cache' || revalidate === 0) {
throw new Error(
`cache: 'force-cache' used on fetch for ${input.toString()} with 'export const fetchCache = 'only-no-store'`
)
}
revalidate = 0
}
if (typeof revalidate === 'undefined') {
if (isOnlyCache && _cache === 'no-store') {
throw new Error(
......@@ -136,15 +148,7 @@ export function patchFetch({
)
}
if (isOnlyNoStore) {
revalidate = 0
if (_cache === 'force-cache') {
throw new Error(
`cache: 'force-cache' used on fetch for ${input.toString()} with 'export const fetchCache = 'only-no-store'`
)
}
} else if (autoNoCache) {
if (autoNoCache) {
revalidate = 0
} else if (isDefaultNoStore) {
revalidate = 0
......@@ -253,6 +257,7 @@ export function patchFetch({
headers: Object.fromEntries(res.headers.entries()),
body: bodyBuffer.toString('base64'),
status: res.status,
tags,
},
revalidate,
},
......@@ -286,9 +291,10 @@ export function patchFetch({
)
if (entry?.value && entry.value.kind === 'FETCH') {
const currentTags = entry.value.data.tags
// when stale and is revalidating we wait for fresh data
// so the revalidated entry has the updated data
if (!staticGenerationStore.isRevalidate || !entry.isStale) {
if (!(staticGenerationStore.isRevalidate && entry.isStale)) {
if (entry.isStale) {
if (!staticGenerationStore.pendingRevalidates) {
staticGenerationStore.pendingRevalidates = []
......@@ -296,6 +302,29 @@ export function patchFetch({
staticGenerationStore.pendingRevalidates.push(
doOriginalFetch().catch(console.error)
)
} else if (
tags &&
!tags.every((tag) => currentTags?.includes(tag))
) {
// if new tags are being added we need to set even if
// the data isn't stale
if (!entry.value.data.tags) {
entry.value.data.tags = []
}
for (const tag of tags) {
if (!entry.value.data.tags.includes(tag)) {
entry.value.data.tags.push(tag)
}
}
staticGenerationStore.incrementalCache?.set(
cacheKey,
entry.value,
revalidate,
true,
fetchUrl,
fetchIdx
)
}
const resData = entry.value.data
......@@ -377,5 +406,8 @@ export function patchFetch({
}
)
}
;(fetch as any).__nextGetStaticStore = () => {
return staticGenerationAsyncStorage
}
;(fetch as any).__nextPatched = true
}
......@@ -370,8 +370,10 @@ export default class NextNodeServer extends BaseServer {
protected getIncrementalCache({
requestHeaders,
requestProtocol,
}: {
requestHeaders: IncrementalCache['requestHeaders']
requestProtocol: 'http' | 'https'
}) {
const dev = !!this.renderOpts.dev
let CacheHandler: any
......@@ -383,6 +385,7 @@ export default class NextNodeServer extends BaseServer {
: incrementalCacheHandlerPath)
CacheHandler = CacheHandler.default || CacheHandler
}
// incremental-cache is request specific with a shared
// although can have shared caches in module scope
// per-cache handler
......@@ -390,7 +393,10 @@ export default class NextNodeServer extends BaseServer {
fs: this.getCacheFilesystem(),
dev,
requestHeaders,
requestProtocol,
appDir: this.hasAppDir,
allowedRevalidateHeaderKeys:
this.nextConfig.experimental.allowedRevalidateHeaderKeys,
minimalMode: this.minimalMode,
serverDistDir: this.serverDistDir,
fetchCache: this.nextConfig.experimental.appDir,
......@@ -405,7 +411,9 @@ export default class NextNodeServer extends BaseServer {
routes: {},
dynamicRoutes: {},
notFoundRoutes: [],
preview: null as any, // `preview` is special case read in next-dev-server
preview: {
previewModeId: 'development-id',
} as any, // `preview` is special case read in next-dev-server
}
} else {
return this.getPrerenderManifest()
......
......@@ -19,6 +19,7 @@ export interface CachedFetchValue {
headers: { [k: string]: string }
body: string
status?: number
tags?: string[]
}
revalidate: number
}
......
......@@ -62,7 +62,10 @@ export default class NextWebServer extends BaseServer<WebServerOptions> {
return new IncrementalCache({
dev,
requestHeaders,
requestProtocol: 'https',
appDir: this.hasAppDir,
allowedRevalidateHeaderKeys:
this.nextConfig.experimental.allowedRevalidateHeaderKeys,
minimalMode: this.minimalMode,
fetchCache: this.nextConfig.experimental.appDir,
fetchCacheKeyPrefix: this.nextConfig.experimental.fetchCacheKeyPrefix,
......@@ -77,7 +80,9 @@ export default class NextWebServer extends BaseServer<WebServerOptions> {
routes: {},
dynamicRoutes: {},
notFoundRoutes: [],
preview: null as any, // `preview` is special case read in next-dev-server
preview: {
previewModeId: 'development-id',
} as any, // `preview` is special case read in next-dev-server
}
} else {
return this.getPrerenderManifest()
......
......@@ -56,6 +56,7 @@ export type AdapterOptions = {
handler: NextMiddleware
page: string
request: RequestData
IncrementalCache?: typeof import('../lib/incremental-cache').IncrementalCache
}
export async function adapter(
......@@ -142,6 +143,34 @@ export async function adapter(
})
}
if (
!(globalThis as any).__incrementalCache &&
(params as any).IncrementalCache
) {
;(globalThis as any).__incrementalCache = new (
params as any
).IncrementalCache({
appDir: true,
fetchCache: true,
minimalMode: true,
fetchCacheKeyPrefix: process.env.__NEXT_FETCH_CACHE_KEY_PREFIX,
dev: process.env.NODE_ENV === 'development',
requestHeaders: params.request.headers as any,
requestProtocol: 'https',
getPrerenderManifest: () => {
return {
version: -1 as any, // letting us know this doesn't conform to spec
routes: {},
dynamicRoutes: {},
notFoundRoutes: [],
preview: {
previewModeId: 'development-id',
} as any, // `preview` is special case read in next-dev-server
}
},
})
}
const event = new NextFetchEvent({ request, page: params.page })
let response = await params.handler(request, event)
......
......@@ -4,7 +4,7 @@ import type { RouteModule } from '../future/route-modules/route-module'
import type { NextRequest } from './spec-extension/request'
import { adapter, enhanceGlobals, type AdapterOptions } from './adapter'
import { IncrementalCache } from '../lib/incremental-cache'
enhanceGlobals()
import { removeTrailingSlash } from '../../shared/lib/router/utils/remove-trailing-slash'
......@@ -54,6 +54,7 @@ export class EdgeRouteModuleWrapper {
return adapter({
...opts,
...options,
IncrementalCache,
// Bind the handler method to the wrapper so it still has context.
handler: wrapper.handler.bind(wrapper),
})
......
// This file is for modularized imports for next/server to get fully-treeshaking.
export { unstable_cache as default } from '../spec-extension/unstable-cache'
// This file is for modularized imports for next/server to get fully-treeshaking.
export { unstable_revalidatePath as default } from '../spec-extension/unstable-revalidate-path'
// This file is for modularized imports for next/server to get fully-treeshaking.
export { unstable_revalidateTag as default } from '../spec-extension/unstable-revalidate-tag'
import {
StaticGenerationAsyncStorage,
StaticGenerationStore,
} from '../../../client/components/static-generation-async-storage'
type Callback = (...args: any[]) => Promise<any>
// TODO: generic callback type?
export function unstable_cache(
cb: Callback,
keyParts: string[],
options: {
revalidate: number | false
tags?: string[]
}
): Callback {
const joinedKey = cb.toString() + '-' + keyParts.join(', ')
const staticGenerationAsyncStorage = (
fetch as any
).__nextGetStaticStore?.() as undefined | StaticGenerationAsyncStorage
const store: undefined | StaticGenerationStore =
staticGenerationAsyncStorage?.getStore()
if (!store || !store.incrementalCache) {
throw new Error(
`Invariant: static generation store missing in unstable_cache ${joinedKey}`
)
}
if (options.revalidate === 0) {
throw new Error(
`Invariant revalidate: 0 can not be passed to unstable_cache(), must be "false" or "> 0" ${joinedKey}`
)
}
return async (...args: any[]) => {
// We override the default fetch cache handling inside of the
// cache callback so that we only cache the specific values returned
// from the callback instead of also caching any fetches done inside
// of the callback as well
return staticGenerationAsyncStorage?.run(
{
...store,
fetchCache: 'only-no-store',
},
async () => {
const cacheKey = await store.incrementalCache?.fetchCacheKey(joinedKey)
const cacheEntry =
cacheKey &&
!store.isOnDemandRevalidate &&
(await store.incrementalCache?.get(
cacheKey,
true,
options.revalidate as number
))
const invokeCallback = async () => {
const result = await cb(...args)
if (cacheKey && store.incrementalCache) {
await store.incrementalCache.set(
cacheKey,
{
kind: 'FETCH',
data: {
headers: {},
// TODO: handle non-JSON values?
body: JSON.stringify(result),
status: 200,
tags: options.tags,
},
revalidate: options.revalidate as number,
},
options.revalidate,
true
)
}
return result
}
if (!cacheEntry || !cacheEntry.value) {
return invokeCallback()
}
if (cacheEntry.value.kind !== 'FETCH') {
console.error(
`Invariant invalid cacheEntry returned for ${joinedKey}`
)
return invokeCallback()
}
let cachedValue: any
const isStale = cacheEntry.isStale
if (cacheEntry) {
const resData = cacheEntry.value.data
cachedValue = JSON.parse(resData.body)
}
const currentTags = cacheEntry.value.data.tags
if (isStale) {
if (!store.pendingRevalidates) {
store.pendingRevalidates = []
}
store.pendingRevalidates.push(
invokeCallback().catch((err) =>
console.error(`revalidating cache with key: ${joinedKey}`, err)
)
)
} else if (
options.tags &&
!options.tags.every((tag) => currentTags?.includes(tag))
) {
if (!cacheEntry.value.data.tags) {
cacheEntry.value.data.tags = []
}
for (const tag of options.tags) {
if (!cacheEntry.value.data.tags.includes(tag)) {
cacheEntry.value.data.tags.push(tag)
}
}
store.incrementalCache?.set(
cacheKey,
cacheEntry.value,
options.revalidate,
true
)
}
return cachedValue
}
)
}
}
import type {
StaticGenerationAsyncStorage,
StaticGenerationStore,
} from '../../../client/components/static-generation-async-storage'
import { headers } from '../../../client/components/headers'
import {
PRERENDER_REVALIDATE_HEADER,
PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER,
} from '../../../lib/constants'
export function unstable_revalidatePath(
path: string,
ctx: {
unstable_onlyGenerated?: boolean
} = {}
) {
const staticGenerationAsyncStorage = (
fetch as any
).__nextGetStaticStore?.() as undefined | StaticGenerationAsyncStorage
const store: undefined | StaticGenerationStore =
staticGenerationAsyncStorage?.getStore()
if (!store) {
throw new Error(
`Invariant: static generation store missing in unstable_revalidatePath ${path}`
)
}
if (!store.pendingRevalidates) {
store.pendingRevalidates = []
}
const previewModeId =
store.incrementalCache?.prerenderManifest?.preview?.previewModeId ||
process.env.__NEXT_PREVIEW_MODE_ID
const reqHeaders: Record<string, undefined | string | string[]> =
store.incrementalCache?.requestHeaders || Object.fromEntries(headers())
const host = reqHeaders['host']
const proto = store.incrementalCache?.requestProtocol || 'https'
// TODO: glob handling + blocking/soft revalidate
const revalidateURL = `${proto}://${host}${path}`
const revalidateHeaders: typeof reqHeaders = {
[PRERENDER_REVALIDATE_HEADER]: previewModeId,
...(ctx.unstable_onlyGenerated
? {
[PRERENDER_REVALIDATE_ONLY_GENERATED_HEADER]: '1',
}
: {}),
}
const curAllowedRevalidateHeaderKeys =
store.incrementalCache?.allowedRevalidateHeaderKeys ||
process.env.__NEXT_ALLOWED_REVALIDATE_HEADERS
const allowedRevalidateHeaderKeys = [
...(curAllowedRevalidateHeaderKeys || []),
...(!store.incrementalCache
? ['cookie', 'x-vercel-protection-bypass']
: []),
]
for (const key of Object.keys(reqHeaders)) {
if (allowedRevalidateHeaderKeys.includes(key)) {
revalidateHeaders[key] = reqHeaders[key] as string
}
}
const fetchIPv4v6 = (v6 = false): Promise<any> => {
const curUrl = new URL(revalidateURL)
const hostname = curUrl.hostname
if (!v6 && hostname === 'localhost') {
curUrl.hostname = '127.0.0.1'
}
return fetch(curUrl, {
method: 'HEAD',
headers: revalidateHeaders as HeadersInit,
})
.then((res) => {
const cacheHeader =
res.headers.get('x-vercel-cache') || res.headers.get('x-nextjs-cache')
if (cacheHeader?.toLowerCase() !== 'revalidated') {
throw new Error(
`received invalid response ${res.status} ${cacheHeader}`
)
}
})
.catch((err) => {
if (err.code === 'ECONNREFUSED' && !v6) {
return fetchIPv4v6(true)
}
console.error(`revalidatePath failed for ${revalidateURL}`, err)
})
}
store.pendingRevalidates.push(fetchIPv4v6())
}
import {
StaticGenerationAsyncStorage,
StaticGenerationStore,
} from '../../../client/components/static-generation-async-storage'
export function unstable_revalidateTag(tag: string) {
const staticGenerationAsyncStorage = (
fetch as any
).__nextGetStaticStore?.() as undefined | StaticGenerationAsyncStorage
const store: undefined | StaticGenerationStore =
staticGenerationAsyncStorage?.getStore()
if (!store || !store.incrementalCache) {
throw new Error(
`Invariant: static generation store missing in unstable_revalidateTag ${tag}`
)
}
if (!store.pendingRevalidates) {
store.pendingRevalidates = []
}
store.pendingRevalidates.push(
store.incrementalCache.revalidateTag?.(tag).catch((err) => {
console.error(`revalidateTag failed for ${tag}`, err)
})
)
}
......@@ -3,10 +3,12 @@
* It will use native path module for nodejs runtime.
* It will use path-browserify polyfill for edge runtime.
*/
let path
const path =
process.env.NEXT_RUNTIME === 'edge'
? require('next/dist/compiled/path-browserify')
: require('path')
if (process.env.NEXT_RUNTIME === 'edge') {
path = require('next/dist/compiled/path-browserify')
} else {
path = require('path')
}
export default path as typeof import('path')
module.exports = path
......@@ -40,6 +40,7 @@ interface Window {
interface NextFetchRequestConfig {
revalidate?: number | false
tags?: string[]
}
interface RequestInit {
......
......@@ -80,6 +80,128 @@ createNextDescribe(
}
})
if (!process.env.CUSTOM_CACHE_HANDLER) {
it.each([
{
type: 'edge route handler',
revalidateApi: '/api/revalidate-tag-edge',
},
{
type: 'node route handler',
revalidateApi: '/api/revalidate-tag-node',
},
])(
'it should revalidate tag correctly with $type',
async ({ revalidateApi }) => {
const initRes = await next.fetch(
'/variable-revalidate/revalidate-360'
)
const html = await initRes.text()
const $ = cheerio.load(html)
const initLayoutData = $('#layout-data').text()
const initPageData = $('#page-data').text()
const routeHandlerRes = await next.fetch(
'/route-handler/revalidate-360'
)
const initRouteHandlerData = await routeHandlerRes.json()
const edgeRouteHandlerRes = await next.fetch(
'/route-handler-edge/revalidate-360'
)
const initEdgeRouteHandlerRes = await edgeRouteHandlerRes.json()
expect(initLayoutData).toBeTruthy()
expect(initPageData).toBeTruthy()
await check(async () => {
const revalidateRes = await next.fetch(
`${revalidateApi}?tag=thankyounext`
)
expect((await revalidateRes.json()).revalidated).toBe(true)
const newRes = await next.fetch(
'/variable-revalidate/revalidate-360'
)
const newHtml = await newRes.text()
const new$ = cheerio.load(newHtml)
const newLayoutData = new$('#layout-data').text()
const newPageData = new$('#page-data').text()
const newRouteHandlerRes = await next.fetch(
'/route-handler/revalidate-360'
)
const newRouteHandlerData = await newRouteHandlerRes.json()
const newEdgeRouteHandlerRes = await next.fetch(
'/route-handler-edge/revalidate-360'
)
const newEdgeRouteHandlerData = await newEdgeRouteHandlerRes.json()
expect(newLayoutData).toBeTruthy()
expect(newPageData).toBeTruthy()
expect(newRouteHandlerData).toBeTruthy()
expect(newEdgeRouteHandlerData).toBeTruthy()
expect(newLayoutData).not.toBe(initLayoutData)
expect(newPageData).not.toBe(initPageData)
expect(newRouteHandlerData).not.toEqual(initRouteHandlerData)
expect(newEdgeRouteHandlerData).not.toEqual(initEdgeRouteHandlerRes)
return 'success'
}, 'success')
}
)
}
// On-Demand Revalidate has not effect in dev since app routes
// aren't considered static until prerendering
if (!(global as any).isNextDev) {
it.each([
{
type: 'edge route handler',
revalidateApi: '/api/revalidate-path-edge',
},
{
type: 'node route handler',
revalidateApi: '/api/revalidate-path-node',
},
])(
'it should revalidate correctly with $type',
async ({ revalidateApi }) => {
const initRes = await next.fetch(
'/variable-revalidate/revalidate-360-isr'
)
const html = await initRes.text()
const $ = cheerio.load(html)
const initLayoutData = $('#layout-data').text()
const initPageData = $('#page-data').text()
expect(initLayoutData).toBeTruthy()
expect(initPageData).toBeTruthy()
await check(async () => {
const revalidateRes = await next.fetch(
`${revalidateApi}?path=/variable-revalidate/revalidate-360-isr`
)
expect((await revalidateRes.json()).revalidated).toBe(true)
const newRes = await next.fetch(
'/variable-revalidate/revalidate-360-isr'
)
const newHtml = await newRes.text()
const new$ = cheerio.load(newHtml)
const newLayoutData = new$('#layout-data').text()
const newPageData = new$('#page-data').text()
expect(newLayoutData).toBeTruthy()
expect(newPageData).toBeTruthy()
expect(newLayoutData).not.toBe(initLayoutData)
expect(newPageData).not.toBe(initPageData)
return 'success'
}, 'success')
}
)
}
// On-Demand Revalidate has not effect in dev
if (!(global as any).isNextDev && !process.env.CUSTOM_CACHE_HANDLER) {
it('should revalidate all fetches during on-demand revalidate', async () => {
......@@ -92,13 +214,15 @@ createNextDescribe(
expect(initLayoutData).toBeTruthy()
expect(initPageData).toBeTruthy()
const revalidateRes = await next.fetch(
'/api/revalidate?path=/variable-revalidate/revalidate-360'
)
expect((await revalidateRes.json()).revalidated).toBe(true)
await check(async () => {
const newRes = await next.fetch('/variable-revalidate/revalidate-360')
const revalidateRes = await next.fetch(
'/api/revalidate-path-node?path=/variable-revalidate/revalidate-360-isr'
)
expect((await revalidateRes.json()).revalidated).toBe(true)
const newRes = await next.fetch(
'/variable-revalidate/revalidate-360-isr'
)
const newHtml = await newRes.text()
const new$ = cheerio.load(newHtml)
const newLayoutData = new$('#layout-data').text()
......@@ -166,10 +290,10 @@ createNextDescribe(
const curRandomData = $('#random-data').text()
expect(curDate).not.toBe(prevInitialDate)
expect(curRandomData).toBe(prevInitialRandomData)
expect(curRandomData).not.toBe(prevInitialRandomData)
prevInitialDate = $('#date').text()
prevInitialRandomData = $('#random-data').text()
prevInitialDate = curDate
prevInitialRandomData = curRandomData
return 'success'
}, 'success')
})
......@@ -207,6 +331,10 @@ createNextDescribe(
expect(files).toEqual([
'(new)/custom/page.js',
'api/revalidate-path-edge/route.js',
'api/revalidate-path-node/route.js',
'api/revalidate-tag-edge/route.js',
'api/revalidate-tag-node/route.js',
'blog/[author]/[slug]/page.js',
'blog/[author]/page.js',
'blog/seb.html',
......@@ -280,7 +408,9 @@ createNextDescribe(
'partial-gen-params-no-additional-slug/fr/second.html',
'partial-gen-params-no-additional-slug/fr/second.rsc',
'partial-gen-params/[lang]/[slug]/page.js',
'route-handler-edge/revalidate-360/route.js',
'route-handler/post/route.js',
'route-handler/revalidate-360/route.js',
'ssg-preview.html',
'ssg-preview.rsc',
'ssg-preview/[[...route]]/page.js',
......@@ -319,8 +449,9 @@ createNextDescribe(
'variable-revalidate/revalidate-3.html',
'variable-revalidate/revalidate-3.rsc',
'variable-revalidate/revalidate-3/page.js',
'variable-revalidate/revalidate-360.html',
'variable-revalidate/revalidate-360.rsc',
'variable-revalidate/revalidate-360-isr.html',
'variable-revalidate/revalidate-360-isr.rsc',
'variable-revalidate/revalidate-360-isr/page.js',
'variable-revalidate/revalidate-360/page.js',
'variable-revalidate/status-code/page.js',
])
......@@ -532,10 +663,10 @@ createNextDescribe(
initialRevalidateSeconds: 3,
srcRoute: '/variable-revalidate/revalidate-3',
},
'/variable-revalidate/revalidate-360': {
dataRoute: '/variable-revalidate/revalidate-360.rsc',
'/variable-revalidate/revalidate-360-isr': {
dataRoute: '/variable-revalidate/revalidate-360-isr.rsc',
initialRevalidateSeconds: 10,
srcRoute: '/variable-revalidate/revalidate-360',
srcRoute: '/variable-revalidate/revalidate-360-isr',
},
})
expect(curManifest.dynamicRoutes).toEqual({
......
import { NextRequest, NextResponse, unstable_revalidatePath } from 'next/server'
export const runtime = 'edge'
export async function GET(req: NextRequest) {
const path = req.nextUrl.searchParams.get('path') || '/'
try {
console.log('revalidating path', path)
unstable_revalidatePath(path)
return NextResponse.json({ revalidated: true, now: Date.now() })
} catch (err) {
console.error('Failed to revalidate', path, err)
return NextResponse.json({ revalidated: false, now: Date.now() })
}
}
import { NextRequest, NextResponse, unstable_revalidatePath } from 'next/server'
export async function GET(req: NextRequest) {
const path = req.nextUrl.searchParams.get('path') || '/'
try {
console.log('revalidating path', path)
unstable_revalidatePath(path)
return NextResponse.json({ revalidated: true, now: Date.now() })
} catch (err) {
console.error('Failed to revalidate', path, err)
return NextResponse.json({ revalidated: false, now: Date.now() })
}
}
import { NextResponse, unstable_revalidateTag } from 'next/server'
export const revalidate = 0
export async function GET(req) {
const tag = req.nextUrl.searchParams.get('tag')
unstable_revalidateTag(tag)
return NextResponse.json({ revalidated: true, now: Date.now() })
}
import { NextResponse, unstable_revalidateTag } from 'next/server'
export const revalidate = 0
export const runtime = 'edge'
export async function GET(req) {
const tag = req.nextUrl.searchParams.get('tag')
unstable_revalidateTag(tag)
return NextResponse.json({ revalidated: true, now: Date.now() })
}
import { NextResponse } from 'next/server'
export const runtime = 'edge'
export const revalidate = 0
export async function GET() {
const data360 = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random',
{
next: {
revalidate: 360,
tags: ['thankyounext'],
},
}
).then((res) => res.text())
const data10 = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random?a=10',
{
next: {
revalidate: 10,
tags: ['thankyounext'],
},
}
).then((res) => res.text())
return NextResponse.json({ data360, data10 })
}
import { NextResponse } from 'next/server'
export const revalidate = 0
export async function GET() {
const data360 = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random',
{
next: {
revalidate: 360,
tags: ['thankyounext'],
},
}
).then((res) => res.text())
const data10 = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random?a=10',
{
next: {
revalidate: 10,
tags: ['thankyounext'],
},
}
).then((res) => res.text())
return NextResponse.json({ data360, data10 })
}
......@@ -3,7 +3,7 @@ import { cache, use } from 'react'
export default function Layout({ children }) {
const getData = cache(() =>
fetch('https://next-data-api-endpoint.vercel.app/api/random?layout', {
next: { revalidate: 10 },
next: { revalidate: 10, tags: ['thankyounext'] },
}).then((res) => res.text())
)
const dataPromise = getData()
......
import { unstable_cache } from 'next/server'
export default async function Page() {
const data = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random?page',
{
next: { revalidate: 360, tags: ['thankyounext'] },
}
).then((res) => res.text())
const data2 = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random?a=b',
{
next: { revalidate: 360, tags: ['thankyounext', 'justputit'] },
}
).then((res) => res.text())
const cachedData = await unstable_cache(
async () => {
const fetchedRandom = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random'
).then((res) => res.json())
return {
now: Date.now(),
random: Math.random(),
fetchedRandom,
}
},
['random'],
{
tags: ['thankyounext'],
revalidate: 10,
}
)()
return (
<>
<p id="page">/variable-revalidate/revalidate-360</p>
<p id="page-data">revalidate 360 (tags: thankyounext): {data}</p>
<p id="page-data2">
revalidate 360 (tags: thankyounext, justputit): {data2}
</p>
<p id="page-data3">
revalidate 10 (tags: thankyounext): {JSON.stringify(cachedData)}
</p>
<p id="now">{Date.now()}</p>
</>
)
}
import { cache, use } from 'react'
import { unstable_cache } from 'next/server'
export default function Page() {
const getData = cache(() =>
fetch('https://next-data-api-endpoint.vercel.app/api/random?page', {
next: { revalidate: 360 },
}).then((res) => res.text())
)
const dataPromise = getData()
const data = use(dataPromise)
export const revalidate = 0
export default async function Page() {
const data = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random?page',
{
next: { revalidate: 360, tags: ['thankyounext'] },
}
).then((res) => res.text())
const data2 = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random?a=b',
{
next: { revalidate: 360, tags: ['thankyounext', 'justputit'] },
}
).then((res) => res.text())
const cachedData = await unstable_cache(
async () => {
const fetchedRandom = await fetch(
'https://next-data-api-endpoint.vercel.app/api/random'
).then((res) => res.json())
return {
now: Date.now(),
random: Math.random(),
fetchedRandom,
}
},
['random'],
{
tags: ['thankyounext'],
revalidate: 10,
}
)()
return (
<>
<p id="page">/variable-revalidate/revalidate-360</p>
<p id="page-data">revalidate 360: {data}</p>
<p id="page-data">revalidate 360 (tags: thankyounext): {data}</p>
<p id="page-data2">
revalidate 360 (tags: thankyounext, justputit): {data2}
</p>
<p id="page-data3">
revalidate 10 (tags: thankyounext): {JSON.stringify(cachedData)}
</p>
<p id="now">{Date.now()}</p>
</>
)
......
/**@type import('next').NextConfig */
module.exports = {
experimental: {
appDir: true,
......
......@@ -138,11 +138,11 @@ describe('Middleware Runtime', () => {
)
expect(manifest.middleware).toEqual({
'/': {
env: [
env: expect.arrayContaining([
'MIDDLEWARE_TEST',
'ANOTHER_MIDDLEWARE_TEST',
'STRING_ENV_VAR',
],
]),
files: expect.arrayContaining([
'server/edge-runtime-webpack.js',
'server/middleware.js',
......
......@@ -113,7 +113,7 @@ describe('Middleware Runtime trailing slash', () => {
'/': {
files: ['server/edge-runtime-webpack.js', 'server/middleware.js'],
name: 'middleware',
env: [],
env: expect.arrayContaining([]),
page: '/',
matchers: [{ regexp: '^/.*$', originalSource: '/:path*' }],
wasm: [],
......
......@@ -187,7 +187,7 @@ describe('Switchable runtime', () => {
expect(manifest).toMatchObject({
functions: {
'/api/hello': {
env: [],
env: expect.arrayContaining([]),
files: [
'server/edge-runtime-webpack.js',
'server/pages/api/hello.js',
......@@ -200,7 +200,7 @@ describe('Switchable runtime', () => {
wasm: [],
},
'/api/edge': {
env: [],
env: expect.arrayContaining([]),
files: [
'server/edge-runtime-webpack.js',
'server/pages/api/edge.js',
......@@ -623,7 +623,7 @@ describe('Switchable runtime', () => {
expect(manifest).toMatchObject({
functions: {
'/api/hello': {
env: [],
env: expect.arrayContaining([]),
files: [
'server/edge-runtime-webpack.js',
'server/pages/api/hello.js',
......@@ -636,7 +636,7 @@ describe('Switchable runtime', () => {
wasm: [],
},
'/api/edge': {
env: [],
env: expect.arrayContaining([]),
files: [
'server/edge-runtime-webpack.js',
'server/pages/api/edge.js',
......
......@@ -64,7 +64,6 @@ describe('dependencies can use env vars in middlewares', () => {
const manifest = await readJson(manifestPath)
const envVars = manifest?.middleware?.['/']?.env
expect(envVars).toHaveLength(2)
expect(envVars).toContain('ENV_VAR_USED_IN_MIDDLEWARE')
expect(envVars).toContain('MY_CUSTOM_PACKAGE_ENV_VAR')
})
......
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