Unverified Commit 99a7a34f authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Ensure generateStaticParams works in route (#46310)

x-ref: [slack
thread](https://vercel.slack.com/archives/C04DUD7EB1B/p1677165000745519)

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have a helpful link attached, see
[`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

---------
Co-authored-by: 's avatarJimmy Lai <laijimmy0@gmail.com>
parent 53006b25
...@@ -1061,7 +1061,7 @@ export type AppConfig = { ...@@ -1061,7 +1061,7 @@ export type AppConfig = {
fetchCache?: 'force-cache' | 'only-cache' fetchCache?: 'force-cache' | 'only-cache'
preferredRegion?: string preferredRegion?: string
} }
type GenerateParams = Array<{ export type GenerateParams = Array<{
config?: AppConfig config?: AppConfig
segmentPath: string segmentPath: string
getStaticPaths?: GetStaticPaths getStaticPaths?: GetStaticPaths
...@@ -1330,7 +1330,21 @@ export async function isPageStatic({ ...@@ -1330,7 +1330,21 @@ export async function isPageStatic({
if (pageType === 'app') { if (pageType === 'app') {
isClientComponent = isClientReference(componentsResult.ComponentMod) isClientComponent = isClientReference(componentsResult.ComponentMod)
const tree = componentsResult.ComponentMod.tree const tree = componentsResult.ComponentMod.tree
const generateParams = await collectGenerateParams(tree) const handlers = componentsResult.ComponentMod.handlers
const generateParams: GenerateParams = handlers
? [
{
config: {
revalidate: handlers.revalidate,
dynamic: handlers.dynamic,
dynamicParams: handlers.dynamicParams,
},
generateStaticParams: handlers.generateStaticParams,
segmentPath: page,
},
]
: await collectGenerateParams(tree)
appConfig = generateParams.reduce( appConfig = generateParams.reduce(
(builtConfig: AppConfig, curGenParams): AppConfig => { (builtConfig: AppConfig, curGenParams): AppConfig => {
......
...@@ -416,8 +416,8 @@ export default async function exportPage({ ...@@ -416,8 +416,8 @@ export default async function exportPage({
if (isValidStatus) { if (isValidStatus) {
const body = await response.blob() const body = await response.blob()
const revalidate = const revalidate =
(staticContext as any as { revalidate?: number }).revalidate || ((staticContext as any).store as any as { revalidate?: number })
false .revalidate || false
results.fromBuildExportRevalidate = revalidate results.fromBuildExportRevalidate = revalidate
const headers = Object.fromEntries(response.headers) const headers = Object.fromEntries(response.headers)
......
...@@ -1469,7 +1469,8 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1469,7 +1469,8 @@ export default abstract class Server<ServerOptions extends Options = Options> {
headers, headers,
}, },
revalidate: revalidate:
(context as any as { revalidate?: number }).revalidate || false, ((context as any).store as any as { revalidate?: number })
.revalidate || false,
} }
return cacheEntry return cacheEntry
} }
......
...@@ -5,6 +5,7 @@ import { ...@@ -5,6 +5,7 @@ import {
buildAppStaticPaths, buildAppStaticPaths,
buildStaticPaths, buildStaticPaths,
collectGenerateParams, collectGenerateParams,
GenerateParams,
} from '../../build/utils' } from '../../build/utils'
import { loadComponents } from '../load-components' import { loadComponents } from '../load-components'
import { setHttpClientAndAgentOptions } from '../config' import { setHttpClientAndAgentOptions } from '../config'
...@@ -84,9 +85,21 @@ export async function loadStaticPaths({ ...@@ -84,9 +85,21 @@ export async function loadStaticPaths({
workerWasUsed = true workerWasUsed = true
if (isAppPath) { if (isAppPath) {
const generateParams = await collectGenerateParams( const handlers = components.ComponentMod.handlers
components.ComponentMod.tree const generateParams: GenerateParams = handlers
) ? [
{
config: {
revalidate: handlers.revalidate,
dynamic: handlers.dynamic,
dynamicParams: handlers.dynamicParams,
},
generateStaticParams: handlers.generateStaticParams,
segmentPath: pathname,
},
]
: await collectGenerateParams(components.ComponentMod.tree)
console.log('idk', generateParams)
return buildAppStaticPaths({ return buildAppStaticPaths({
page: pathname, page: pathname,
generateParams, generateParams,
......
...@@ -71,6 +71,8 @@ export default class FetchCache implements CacheHandler { ...@@ -71,6 +71,8 @@ export default class FetchCache implements CacheHandler {
{ {
method: 'GET', method: 'GET',
headers: this.headers, headers: this.headers,
// @ts-expect-error
next: { internal: true },
} }
) )
...@@ -155,6 +157,8 @@ export default class FetchCache implements CacheHandler { ...@@ -155,6 +157,8 @@ export default class FetchCache implements CacheHandler {
method: 'POST', method: 'POST',
headers: this.headers, headers: this.headers,
body: body, body: body,
// @ts-expect-error
next: { internal: true },
} }
) )
......
...@@ -267,6 +267,14 @@ export class IncrementalCache { ...@@ -267,6 +267,14 @@ export class IncrementalCache {
fetchCache?: boolean fetchCache?: boolean
) { ) {
if (this.dev && !fetchCache) return if (this.dev && !fetchCache) return
// fetchCache has upper limit of 1MB per-entry currently
if (fetchCache && JSON.stringify(data).length > 1024 * 1024) {
if (this.dev) {
throw new Error(`fetch for over 1MB of data can not be cached`)
}
return
}
pathname = this._getPathname(pathname, fetchCache) pathname = this._getPathname(pathname, fetchCache)
try { try {
......
...@@ -33,7 +33,7 @@ export function patchFetch({ ...@@ -33,7 +33,7 @@ export function patchFetch({
// If the staticGenerationStore is not available, we can't do any // If the staticGenerationStore is not available, we can't do any
// special treatment of fetch, therefore fallback to the original // special treatment of fetch, therefore fallback to the original
// fetch implementation. // fetch implementation.
if (!staticGenerationStore) { if (!staticGenerationStore || (init?.next as any)?.internal) {
return originFetch(input, init) return originFetch(input, init)
} }
...@@ -109,19 +109,23 @@ export function patchFetch({ ...@@ -109,19 +109,23 @@ export function patchFetch({
) )
} }
await staticGenerationStore.incrementalCache.set( try {
cacheKey, await staticGenerationStore.incrementalCache.set(
{ cacheKey,
kind: 'FETCH', {
data: { kind: 'FETCH',
headers: Object.fromEntries(clonedRes.headers.entries()), data: {
body: base64Body, headers: Object.fromEntries(clonedRes.headers.entries()),
body: base64Body,
},
revalidate,
}, },
revalidate, revalidate,
}, true
revalidate, )
true } catch (err) {
) console.warn(`Failed to set fetch cache`, input, err)
}
} }
return res return res
}) })
......
...@@ -48,6 +48,59 @@ createNextDescribe( ...@@ -48,6 +48,59 @@ createNextDescribe(
}) })
}) })
describe('works with generateStaticParams correctly', () => {
it.each([
'/static/first/data.json',
'/static/second/data.json',
'/static/three/data.json',
])('responds correctly on %s', async (path) => {
expect(JSON.parse(await next.render(path))).toEqual({
params: { slug: path.split('/')[2] },
now: expect.any(Number),
})
if (isNextStart) {
await check(async () => {
expect(
await next.readFile(`.next/server/app/${path}.body`)
).toBeTruthy()
expect(
await next.readFile(`.next/server/app/${path}.meta`)
).toBeTruthy()
return 'success'
}, 'success')
}
})
it.each([
'/revalidate-1/first/data.json',
'/revalidate-1/second/data.json',
'/revalidate-1/three/data.json',
])('revalidates correctly on %s', async (path) => {
const data = JSON.parse(await next.render(path))
expect(data).toEqual({
params: { slug: path.split('/')[2] },
now: expect.any(Number),
})
await check(async () => {
expect(data).not.toEqual(JSON.parse(await next.render(path)))
return 'success'
}, 'success')
if (isNextStart) {
await check(async () => {
expect(
await next.readFile(`.next/server/app/${path}.body`)
).toBeTruthy()
expect(
await next.readFile(`.next/server/app/${path}.meta`)
).toBeTruthy()
return 'success'
}, 'success')
}
})
})
describe('basic fetch request with a response', () => { describe('basic fetch request with a response', () => {
describe.each(['GET', 'POST', 'PUT', 'DELETE', 'PATCH'])( describe.each(['GET', 'POST', 'PUT', 'DELETE', 'PATCH'])(
'made via a %s request', 'made via a %s request',
......
import { NextRequest, NextResponse } from 'next/server'
export const revalidate = 1
export function generateStaticParams() {
console.log('generateStaticParams static/[slug]')
return [{ slug: 'first' }, { slug: 'second' }]
}
export const GET = (req: NextRequest, { params }) => {
return NextResponse.json({ params, now: Date.now() })
}
import { NextRequest, NextResponse } from 'next/server'
export function generateStaticParams() {
console.log('generateStaticParams static/[slug]')
return [{ slug: 'first' }, { slug: 'second' }]
}
export const GET = (req: NextRequest, { params }) => {
return NextResponse.json({ params, now: Date.now() })
}
process.env.CUSTOM_CACHE_HANDLER = '1' beforeAll(async () => {
process.env.CUSTOM_CACHE_HANDLER = '1'
})
require('./app-static.test') require('./app-static.test')
...@@ -14,7 +14,11 @@ createNextDescribe( ...@@ -14,7 +14,11 @@ createNextDescribe(
files: __dirname, files: __dirname,
env: { env: {
NEXT_DEBUG_BUILD: '1', NEXT_DEBUG_BUILD: '1',
CUSTOM_CACHE_HANDLER: process.env.CUSTOM_CACHE_HANDLER, ...(process.env.CUSTOM_CACHE_HANDLER
? {
CUSTOM_CACHE_HANDLER: process.env.CUSTOM_CACHE_HANDLER,
}
: {}),
}, },
}, },
({ next, isNextDev: isDev, isNextStart, isNextDeploy }) => { ({ next, isNextDev: isDev, isNextStart, isNextDeploy }) => {
......
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