Unverified Commit 12d2a6f3 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Ensure we validate revalidate configs properly (#59822)

If a user accidentally configures a non-valid `revalidate` value this
ensures we show a proper error message instead of silently tolerating
it.

Closes: NEXT-1896

Closes NEXT-1915
parent 4402428c
......@@ -54,6 +54,7 @@ import { isAppPageRoute } from '../lib/is-app-page-route'
import isError from '../lib/is-error'
import { needsExperimentalReact } from '../lib/needs-experimental-react'
import { formatManifest } from '../build/manifests/formatter/format-manifest'
import { validateRevalidate } from '../server/lib/patch-fetch'
function divideSegments(number: number, segments: number): number[] {
const result = []
......@@ -741,7 +742,7 @@ export async function exportAppImpl(
// Update path info by path.
const info = collector.byPath.get(path) ?? {}
if (typeof result.revalidate !== 'undefined') {
info.revalidate = result.revalidate
info.revalidate = validateRevalidate(result.revalidate, path)
}
if (typeof result.metadata !== 'undefined') {
info.metadata = result.metadata
......
......@@ -9,6 +9,7 @@ import type { CreateSegmentPath, AppRenderContext } from './app-render'
import { createComponentStylesAndScripts } from './create-component-styles-and-scripts'
import { getLayerAssets } from './get-layer-assets'
import { hasLoadingComponentInTree } from './has-loading-component-in-tree'
import { validateRevalidate } from '../lib/patch-fetch'
type ComponentTree = {
seedData: CacheNodeSeedData
......@@ -189,6 +190,13 @@ export async function createComponentTree({
staticGenerationStore.fetchCache = layoutOrPageMod?.fetchCache
}
if (typeof layoutOrPageMod?.revalidate !== 'undefined') {
validateRevalidate(
layoutOrPageMod?.revalidate,
staticGenerationStore.urlPathname
)
}
if (typeof layoutOrPageMod?.revalidate === 'number') {
ctx.defaultRevalidate = layoutOrPageMod.revalidate as number
......
......@@ -15,6 +15,40 @@ import * as Log from '../../build/output/log'
const isEdgeRuntime = process.env.NEXT_RUNTIME === 'edge'
export function validateRevalidate(
revalidateVal: unknown,
pathname: string
): undefined | number | false {
try {
let normalizedRevalidate: false | number | undefined = undefined
if (revalidateVal === false) {
normalizedRevalidate = revalidateVal
} else if (
typeof revalidateVal === 'number' &&
!isNaN(revalidateVal) &&
revalidateVal > -1
) {
normalizedRevalidate = revalidateVal
} else if (typeof revalidateVal !== 'undefined') {
throw new Error(
`Invalid revalidate value "${revalidateVal}" on "${pathname}", must be a non-negative number or "false"`
)
}
return normalizedRevalidate
} catch (err: any) {
// handle client component error from attempting to check revalidate value
if (
err &&
typeof err === 'object' &&
err.message?.includes('Invalid revalidate')
) {
throw err
}
return undefined
}
}
export function validateTags(tags: any[], description: string) {
const validTags: string[] = []
const invalidTags: Array<{
......@@ -290,9 +324,10 @@ export function patchFetch({
cacheReason = `cache: ${_cache}`
}
if (typeof curRevalidate === 'number' || curRevalidate === false) {
revalidate = curRevalidate
}
revalidate = validateRevalidate(
curRevalidate,
staticGenerationStore.urlPathname
)
const _headers = getRequestMeta('headers')
const initHeaders: Headers =
......
......@@ -5,7 +5,11 @@ import type {
import { staticGenerationAsyncStorage as _staticGenerationAsyncStorage } from '../../../client/components/static-generation-async-storage.external'
import { CACHE_ONE_YEAR } from '../../../lib/constants'
import { addImplicitTags, validateTags } from '../../lib/patch-fetch'
import {
addImplicitTags,
validateRevalidate,
validateTags,
} from '../../lib/patch-fetch'
type Callback = (...args: any[]) => Promise<any>
......@@ -30,7 +34,11 @@ export function unstable_cache<T extends Callback>(
const store: undefined | StaticGenerationStore =
staticGenerationAsyncStorage?.getStore()
if (store && typeof options.revalidate === 'number') {
if (store && typeof options.revalidate !== 'undefined') {
validateRevalidate(
options.revalidate,
`unstable_cache ${cb.name || cb.toString()}`
)
// Revalidate 0 is a special case, it means opt-out of static generation.
if (options.revalidate === 0) {
// If postpone is supported we should postpone the render.
......@@ -39,7 +47,10 @@ export function unstable_cache<T extends Callback>(
// Set during dynamic rendering
store.revalidate = 0
// If revalidate was already set in the store before we should check if the new value is lower, set it to the lowest of the two.
} else if (typeof store.revalidate === 'number') {
} else if (
typeof store.revalidate === 'number' &&
typeof options.revalidate === 'number'
) {
if (store.revalidate > options.revalidate) {
store.revalidate = options.revalidate
}
......
import { createNextDescribe } from 'e2e-utils'
import { check } from 'next-test-utils'
createNextDescribe(
'app-invalid-revalidate',
{
files: __dirname,
skipStart: true,
skipDeployment: true,
},
({ next, isNextDev }) => {
it('should error properly for invalid revalidate at layout', async () => {
await next.stop().catch(() => {})
const origText = await next.readFile('app/layout.tsx')
try {
await next.patchFile(
'app/layout.tsx',
origText.replace('// export', 'export')
)
await next.start().catch(() => {})
await check(async () => {
if (isNextDev) {
await next.fetch('/')
}
return next.cliOutput
}, /Invalid revalidate value "1" on "\/", must be a non-negative number or "false"/)
} finally {
await next.patchFile('app/layout.tsx', origText)
}
})
it('should error properly for invalid revalidate at page', async () => {
await next.stop().catch(() => {})
const origText = await next.readFile('app/page.tsx')
try {
await next.patchFile(
'app/page.tsx',
origText.replace('// export', 'export')
)
await next.start().catch(() => {})
await check(async () => {
if (isNextDev) {
await next.fetch('/')
}
return next.cliOutput
}, /Invalid revalidate value "1" on "\/", must be a non-negative number or "false"/)
} finally {
await next.patchFile('app/page.tsx', origText)
}
})
it('should error properly for invalid revalidate on fetch', async () => {
await next.stop().catch(() => {})
const origText = await next.readFile('app/page.tsx')
try {
await next.patchFile(
'app/page.tsx',
origText.replace('// await', 'await')
)
await next.start().catch(() => {})
await check(async () => {
if (isNextDev) {
await next.fetch('/')
}
return next.cliOutput
}, /Invalid revalidate value "1" on "\/", must be a non-negative number or "false"/)
} finally {
await next.patchFile('app/page.tsx', origText)
}
})
}
)
// export const revalidate = '1'
export default function Root({ children }: { children: React.ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
// export const revalidate = '1'
export default async function Page() {
// await fetch('https://example.vercel.sh', { next: { revalidate: '1' } })
return <p>hello world</p>
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
typescript: {
ignoreBuildErrors: true,
},
}
module.exports = nextConfig
import { notFound } from 'next/navigation'
export const revalidate = null
export const dynamicParams = true
export default function Page({ params }) {
......
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