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