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 = {
fetchCache?: 'force-cache' | 'only-cache'
preferredRegion?: string
}
type GenerateParams = Array<{
export type GenerateParams = Array<{
config?: AppConfig
segmentPath: string
getStaticPaths?: GetStaticPaths
......@@ -1330,7 +1330,21 @@ export async function isPageStatic({
if (pageType === 'app') {
isClientComponent = isClientReference(componentsResult.ComponentMod)
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(
(builtConfig: AppConfig, curGenParams): AppConfig => {
......
......@@ -416,8 +416,8 @@ export default async function exportPage({
if (isValidStatus) {
const body = await response.blob()
const revalidate =
(staticContext as any as { revalidate?: number }).revalidate ||
false
((staticContext as any).store as any as { revalidate?: number })
.revalidate || false
results.fromBuildExportRevalidate = revalidate
const headers = Object.fromEntries(response.headers)
......
......@@ -1469,7 +1469,8 @@ export default abstract class Server<ServerOptions extends Options = Options> {
headers,
},
revalidate:
(context as any as { revalidate?: number }).revalidate || false,
((context as any).store as any as { revalidate?: number })
.revalidate || false,
}
return cacheEntry
}
......
......@@ -5,6 +5,7 @@ import {
buildAppStaticPaths,
buildStaticPaths,
collectGenerateParams,
GenerateParams,
} from '../../build/utils'
import { loadComponents } from '../load-components'
import { setHttpClientAndAgentOptions } from '../config'
......@@ -84,9 +85,21 @@ export async function loadStaticPaths({
workerWasUsed = true
if (isAppPath) {
const generateParams = await collectGenerateParams(
components.ComponentMod.tree
)
const handlers = components.ComponentMod.handlers
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({
page: pathname,
generateParams,
......
......@@ -71,6 +71,8 @@ export default class FetchCache implements CacheHandler {
{
method: 'GET',
headers: this.headers,
// @ts-expect-error
next: { internal: true },
}
)
......@@ -155,6 +157,8 @@ export default class FetchCache implements CacheHandler {
method: 'POST',
headers: this.headers,
body: body,
// @ts-expect-error
next: { internal: true },
}
)
......
......@@ -267,6 +267,14 @@ export class IncrementalCache {
fetchCache?: boolean
) {
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)
try {
......
......@@ -33,7 +33,7 @@ export function patchFetch({
// If the staticGenerationStore is not available, we can't do any
// special treatment of fetch, therefore fallback to the original
// fetch implementation.
if (!staticGenerationStore) {
if (!staticGenerationStore || (init?.next as any)?.internal) {
return originFetch(input, init)
}
......@@ -109,19 +109,23 @@ export function patchFetch({
)
}
await staticGenerationStore.incrementalCache.set(
cacheKey,
{
kind: 'FETCH',
data: {
headers: Object.fromEntries(clonedRes.headers.entries()),
body: base64Body,
try {
await staticGenerationStore.incrementalCache.set(
cacheKey,
{
kind: 'FETCH',
data: {
headers: Object.fromEntries(clonedRes.headers.entries()),
body: base64Body,
},
revalidate,
},
revalidate,
},
revalidate,
true
)
true
)
} catch (err) {
console.warn(`Failed to set fetch cache`, input, err)
}
}
return res
})
......
......@@ -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.each(['GET', 'POST', 'PUT', 'DELETE', 'PATCH'])(
'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')
......@@ -14,7 +14,11 @@ createNextDescribe(
files: __dirname,
env: {
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 }) => {
......
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