Unverified Commit aff987d5 authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

backport: feat: implement LRU cache with invocation ID scoping for minimal mode…

backport: feat: implement LRU cache with invocation ID scoping for minimal mode response cache (#89129)

Backports:
- #88509
- #89123

---------
Co-authored-by: 's avatarWyatt Johnson <accounts+github@wyattjoh.ca>
parent 330089bd
......@@ -226,4 +226,75 @@ describe('LRUCache', () => {
expect(cache.has('key149')).toBe(true) // recent keys retained
})
})
describe('onEvict Callback', () => {
it('should call onEvict when an entry is evicted', () => {
const evicted: Array<{ key: string; value: string }> = []
const cache = new LRUCache<string>(2, undefined, (key, value) => {
evicted.push({ key, value })
})
cache.set('a', 'value-a')
cache.set('b', 'value-b')
expect(evicted.length).toBe(0)
cache.set('c', 'value-c') // should evict 'a'
expect(evicted.length).toBe(1)
expect(evicted[0]).toEqual({ key: 'a', value: 'value-a' })
})
it('should not call onEvict when updating existing entry', () => {
const evicted: string[] = []
const cache = new LRUCache<string>(2, undefined, (key) => {
evicted.push(key)
})
cache.set('a', 'value-a')
cache.set('a', 'new-value-a')
expect(evicted.length).toBe(0)
})
it('should call onEvict for each evicted entry when multiple are evicted', () => {
const evicted: string[] = []
const cache = new LRUCache<string>(
10,
(value) => value.length,
(key) => {
evicted.push(key)
}
)
cache.set('key1', 'ab') // size 2
cache.set('key2', 'cd') // size 2
cache.set('key3', 'ef') // size 2, total = 6
cache.set('key4', 'ghijklmno') // size 9, should evict key1, key2, key3
expect(evicted).toEqual(['key1', 'key2', 'key3'])
})
it('should work without onEvict callback', () => {
const cache = new LRUCache<string>(2)
cache.set('a', 'value-a')
cache.set('b', 'value-b')
cache.set('c', 'value-c') // should evict without error
expect(cache.has('a')).toBe(false)
})
it('should pass the evicted value to the callback', () => {
const evicted: Array<{ id: number }> = []
const cache = new LRUCache<{ id: number }>(
1,
undefined,
(_key, value) => {
evicted.push(value)
}
)
cache.set('obj1', { id: 1 })
cache.set('obj2', { id: 2 }) // should evict obj1
expect(evicted.length).toBe(1)
expect(evicted[0]).toEqual({ id: 1 })
})
})
})
......@@ -50,10 +50,16 @@ export class LRUCache<T> {
private totalSize: number = 0
private readonly maxSize: number
private readonly calculateSize: ((value: T) => number) | undefined
private readonly onEvict: ((key: string, value: T) => void) | undefined
constructor(maxSize: number, calculateSize?: (value: T) => number) {
constructor(
maxSize: number,
calculateSize?: (value: T) => number,
onEvict?: (key: string, value: T) => void
) {
this.maxSize = maxSize
this.calculateSize = calculateSize
this.onEvict = onEvict
// Create sentinel nodes to simplify doubly-linked list operations
// HEAD <-> TAIL (empty list)
......@@ -144,6 +150,7 @@ export class LRUCache<T> {
const tail = this.removeTail()
this.cache.delete(tail.key)
this.totalSize -= tail.size
this.onEvict?.(tail.key, tail.data)
}
}
......@@ -191,6 +198,10 @@ export class LRUCache<T> {
* Removes a specific key from the cache.
* Updates both the hash map and doubly-linked list.
*
* Note: This is an explicit removal and does NOT trigger the `onEvict`
* callback. Use this for intentional deletions where eviction tracking
* is not needed.
*
* Time Complexity: O(1)
*/
public remove(key: string): void {
......
......@@ -7,6 +7,8 @@ import type {
} from './types'
import { Batcher } from '../../lib/batcher'
import { LRUCache } from '../lib/lru-cache'
import { warnOnce } from '../../build/output/log'
import { scheduleOnNextTick } from '../../lib/scheduler'
import {
fromResponseCacheEntry,
......@@ -15,6 +17,91 @@ import {
} from './utils'
import type { RouteKind } from '../route-kind'
/**
* Parses an environment variable as a positive integer, returning the fallback
* if the value is missing, not a number, or not positive.
*/
function parsePositiveInt(
envValue: string | undefined,
fallback: number
): number {
if (!envValue) return fallback
const parsed = parseInt(envValue, 10)
return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback
}
/**
* Default TTL (in milliseconds) for minimal mode response cache entries.
* Used for cache hit validation as a fallback for providers that don't
* send the x-invocation-id header yet.
*
* 10 seconds chosen because:
* - Long enough to dedupe rapid successive requests (e.g., page + data)
* - Short enough to not serve stale data across unrelated requests
*
* Can be configured via `NEXT_PRIVATE_RESPONSE_CACHE_TTL` environment variable.
*/
const DEFAULT_TTL_MS = parsePositiveInt(
process.env.NEXT_PRIVATE_RESPONSE_CACHE_TTL,
10_000
)
/**
* Default maximum number of entries in the response cache.
* Can be configured via `NEXT_PRIVATE_RESPONSE_CACHE_MAX_SIZE` environment variable.
*/
const DEFAULT_MAX_SIZE = parsePositiveInt(
process.env.NEXT_PRIVATE_RESPONSE_CACHE_MAX_SIZE,
150
)
/**
* Separator used in compound cache keys to join pathname and invocationID.
* Using null byte (\0) since it cannot appear in valid URL paths or UUIDs.
*/
const KEY_SEPARATOR = '\0'
/**
* Sentinel value used for TTL-based cache entries (when invocationID is undefined).
* Chosen to be a clearly reserved marker for internal cache keys.
*/
const TTL_SENTINEL = '__ttl_sentinel__'
/**
* Entry stored in the LRU cache.
*/
type CacheEntry = {
entry: IncrementalResponseCacheEntry | null
/**
* TTL expiration timestamp in milliseconds. Used as a fallback for
* cache hit validation when providers don't send x-invocation-id.
* Memory pressure is managed by LRU eviction rather than timers.
*/
expiresAt: number
}
/**
* Creates a compound cache key from pathname and invocationID.
*/
function createCacheKey(
pathname: string,
invocationID: string | undefined
): string {
return `${pathname}${KEY_SEPARATOR}${invocationID ?? TTL_SENTINEL}`
}
/**
* Extracts the invocationID from a compound cache key.
* Returns undefined if the key used TTL_SENTINEL.
*/
function extractInvocationID(compoundKey: string): string | undefined {
const separatorIndex = compoundKey.lastIndexOf(KEY_SEPARATOR)
if (separatorIndex === -1) return undefined
const invocationID = compoundKey.slice(separatorIndex + 1)
return invocationID === TTL_SENTINEL ? undefined : invocationID
}
export * from './types'
export default class ResponseCache implements ResponseCacheBase {
......@@ -33,19 +120,73 @@ export default class ResponseCache implements ResponseCacheBase {
schedulerFn: scheduleOnNextTick,
})
private previousCacheItem?: {
key: string
entry: IncrementalResponseCacheEntry | null
expiresAt: number
}
private readonly revalidateBatcher = Batcher.create<
string,
IncrementalResponseCacheEntry | null
>({
// We wait to do any async work until after we've added our promise to
// `pendingResponses` to ensure that any any other calls will reuse the
// same promise until we've fully finished our work.
schedulerFn: scheduleOnNextTick,
})
/**
* LRU cache for minimal mode using compound keys (pathname + invocationID).
* This allows multiple invocations to cache the same pathname without
* overwriting each other's entries.
*/
private readonly cache: LRUCache<CacheEntry>
/**
* Set of invocation IDs that have had cache entries evicted.
* Used to detect when the cache size may be too small.
* Bounded to prevent memory growth.
*/
private readonly evictedInvocationIDs: Set<string> = new Set()
/**
* The configured max size, stored for logging.
*/
private readonly maxSize: number
/**
* The configured TTL for cache entries in milliseconds.
*/
private readonly ttl: number
// we don't use minimal_mode name here as this.minimal_mode is
// statically replace for server runtimes but we need it to
// be dynamic here
private minimal_mode?: boolean
constructor(minimal_mode: boolean) {
constructor(
minimal_mode: boolean,
maxSize: number = DEFAULT_MAX_SIZE,
ttl: number = DEFAULT_TTL_MS
) {
this.minimal_mode = minimal_mode
this.maxSize = maxSize
this.ttl = ttl
// Create the LRU cache with eviction tracking
this.cache = new LRUCache(maxSize, undefined, (compoundKey) => {
const invocationID = extractInvocationID(compoundKey)
if (invocationID) {
// Bound to 100 entries to prevent unbounded memory growth.
// FIFO eviction is acceptable here because:
// 1. Invocations are short-lived (single request lifecycle), so older
// invocations are unlikely to still be active after 100 newer ones
// 2. This warning mechanism is best-effort for developer guidance—
// missing occasional eviction warnings doesn't affect correctness
// 3. If a long-running invocation is somehow evicted and then has
// another cache entry evicted, it will simply be re-added
if (this.evictedInvocationIDs.size >= 100) {
const first = this.evictedInvocationIDs.values().next().value
if (first) this.evictedInvocationIDs.delete(first)
}
this.evictedInvocationIDs.add(invocationID)
}
})
}
public async get(
......@@ -59,12 +200,55 @@ export default class ResponseCache implements ResponseCacheBase {
isRoutePPREnabled?: boolean
isFallback?: boolean
waitUntil?: (prom: Promise<any>) => void
/**
* The invocation ID from the infrastructure. Used to scope the
* in-memory cache to a single revalidation request in minimal mode.
*/
invocationID?: string
}
): Promise<ResponseCacheEntry | null> {
// If there is no key for the cache, we can't possibly look this up in the
// cache so just return the result of the response generator.
if (!key) {
return responseGenerator({ hasResolved: false, previousCacheEntry: null })
return responseGenerator({
hasResolved: false,
previousCacheEntry: null,
})
}
// Check minimal mode cache before doing any other work.
if (this.minimal_mode) {
const cacheKey = createCacheKey(key, context.invocationID)
const cachedItem = this.cache.get(cacheKey)
if (cachedItem) {
// With invocationID: exact match found - always a hit
// With TTL mode: must check expiration
if (context.invocationID !== undefined) {
return toResponseCacheEntry(cachedItem.entry)
}
// TTL mode: check expiration
const now = Date.now()
if (cachedItem.expiresAt > now) {
return toResponseCacheEntry(cachedItem.entry)
}
// TTL expired - clean up
this.cache.remove(cacheKey)
}
// Warn if this invocation had entries evicted - indicates cache may be too small.
if (
context.invocationID &&
this.evictedInvocationIDs.has(context.invocationID)
) {
warnOnce(
`Response cache entry was evicted for invocation ${context.invocationID}. ` +
`Consider increasing NEXT_PRIVATE_RESPONSE_CACHE_MAX_SIZE (current: ${this.maxSize}).`
)
}
}
const {
......@@ -72,143 +256,251 @@ export default class ResponseCache implements ResponseCacheBase {
isOnDemandRevalidate = false,
isFallback = false,
isRoutePPREnabled = false,
isPrefetch = false,
waitUntil,
routeKind,
invocationID,
} = context
const response = await this.batcher.batch(
{ key, isOnDemandRevalidate },
(cacheKey, resolve) => {
const prom = (async () => {
// We keep the previous cache entry around to leverage when the
// incremental cache is disabled in minimal mode.
if (
this.minimal_mode &&
this.previousCacheItem?.key === cacheKey &&
this.previousCacheItem.expiresAt > Date.now()
) {
return this.previousCacheItem.entry
(_cacheKey, resolve) => {
const promise = this.handleGet(
key,
responseGenerator,
{
incrementalCache,
isOnDemandRevalidate,
isFallback,
isRoutePPREnabled,
isPrefetch,
routeKind,
invocationID,
},
resolve
)
// we need to ensure background revalidates are
// passed to waitUntil
if (waitUntil) {
waitUntil(promise)
}
return promise
}
)
// Coerce the kindHint into a given kind for the incremental cache.
const kind = routeKindToIncrementalCacheKind(context.routeKind)
return toResponseCacheEntry(response)
}
/**
* Handles the get request for the response cache.
*
* @param key - The key to get the response cache entry for.
* @param responseGenerator - The response generator to use to generate the response cache entry.
* @param context - The context for the get request.
* @param resolve - The resolve function to use to resolve the response cache entry.
* @returns The response cache entry.
*/
private async handleGet(
key: string,
responseGenerator: ResponseGenerator,
context: {
incrementalCache: IncrementalResponseCache
isOnDemandRevalidate: boolean
isFallback: boolean
isRoutePPREnabled: boolean
isPrefetch: boolean
routeKind: RouteKind
invocationID: string | undefined
},
resolve: (value: IncrementalResponseCacheEntry | null) => void
): Promise<IncrementalResponseCacheEntry | null> {
let previousIncrementalCacheEntry: IncrementalResponseCacheEntry | null =
null
let resolved = false
let cachedResponse: IncrementalResponseCacheEntry | null = null
try {
cachedResponse = !this.minimal_mode
? await incrementalCache.get(key, {
kind,
// Get the previous cache entry if not in minimal mode
previousIncrementalCacheEntry = !this.minimal_mode
? await context.incrementalCache.get(key, {
kind: routeKindToIncrementalCacheKind(context.routeKind),
isRoutePPREnabled: context.isRoutePPREnabled,
isFallback,
isFallback: context.isFallback,
})
: null
if (cachedResponse && !isOnDemandRevalidate) {
resolve(cachedResponse)
if (previousIncrementalCacheEntry && !context.isOnDemandRevalidate) {
resolve(previousIncrementalCacheEntry)
resolved = true
if (!cachedResponse.isStale || context.isPrefetch) {
// The cached value is still valid, so we don't need
// to update it yet.
return null
if (!previousIncrementalCacheEntry.isStale || context.isPrefetch) {
// The cached value is still valid, so we don't need to update it yet.
return previousIncrementalCacheEntry
}
}
const cacheEntry = await responseGenerator({
hasResolved: resolved,
previousCacheEntry: cachedResponse,
isRevalidating: true,
})
// Revalidate the cache entry
const incrementalResponseCacheEntry = await this.revalidate(
key,
context.incrementalCache,
context.isRoutePPREnabled,
context.isFallback,
responseGenerator,
previousIncrementalCacheEntry,
previousIncrementalCacheEntry !== null && !context.isOnDemandRevalidate,
undefined,
context.invocationID
)
// If the cache entry couldn't be generated, we don't want to cache
// the result.
if (!cacheEntry) {
// Unset the previous cache item if it was set.
if (this.minimal_mode) this.previousCacheItem = undefined
// Handle null response
if (!incrementalResponseCacheEntry) {
// Remove the cache item if it was set so we don't use it again.
if (this.minimal_mode) {
const cacheKey = createCacheKey(key, context.invocationID)
this.cache.remove(cacheKey)
}
return null
}
const resolveValue = await fromResponseCacheEntry({
...cacheEntry,
isMiss: !cachedResponse,
})
if (!resolveValue) {
// Unset the previous cache item if it was set.
if (this.minimal_mode) this.previousCacheItem = undefined
// Resolve for on-demand revalidation or if not already resolved
if (context.isOnDemandRevalidate && !resolved) {
return incrementalResponseCacheEntry
}
return incrementalResponseCacheEntry
} catch (err) {
// If we've already resolved the cache entry, we can't reject as we
// already resolved the cache entry so log the error here.
if (resolved) {
console.error(err)
return null
}
// For on-demand revalidate wait to resolve until cache is set.
// Otherwise resolve now.
if (!isOnDemandRevalidate && !resolved) {
resolve(resolveValue)
resolved = true
throw err
}
}
/**
* Revalidates the cache entry for the given key.
*
* @param key - The key to revalidate the cache entry for.
* @param incrementalCache - The incremental cache to use to revalidate the cache entry.
* @param isRoutePPREnabled - Whether the route is PPR enabled.
* @param isFallback - Whether the route is a fallback.
* @param responseGenerator - The response generator to use to generate the response cache entry.
* @param previousIncrementalCacheEntry - The previous cache entry to use to revalidate the cache entry.
* @param hasResolved - Whether the response has been resolved.
* @param waitUntil - Optional function to register background work.
* @param invocationID - The invocation ID for cache key scoping.
* @returns The revalidated cache entry.
*/
public async revalidate(
key: string,
incrementalCache: IncrementalResponseCache,
isRoutePPREnabled: boolean,
isFallback: boolean,
responseGenerator: ResponseGenerator,
previousIncrementalCacheEntry: IncrementalResponseCacheEntry | null,
hasResolved: boolean,
waitUntil?: (prom: Promise<any>) => void,
invocationID?: string
) {
return this.revalidateBatcher.batch(key, () => {
const promise = this.handleRevalidate(
key,
incrementalCache,
isRoutePPREnabled,
isFallback,
responseGenerator,
previousIncrementalCacheEntry,
hasResolved,
invocationID
)
// We need to ensure background revalidates are passed to waitUntil.
if (waitUntil) waitUntil(promise)
return promise
})
}
private async handleRevalidate(
key: string,
incrementalCache: IncrementalResponseCache,
isRoutePPREnabled: boolean,
isFallback: boolean,
responseGenerator: ResponseGenerator,
previousIncrementalCacheEntry: IncrementalResponseCacheEntry | null,
hasResolved: boolean,
invocationID: string | undefined
) {
try {
// Generate the response cache entry using the response generator.
const responseCacheEntry = await responseGenerator({
hasResolved,
previousCacheEntry: previousIncrementalCacheEntry,
isRevalidating: true,
})
if (!responseCacheEntry) {
return null
}
// Convert the response cache entry to an incremental response cache entry.
const incrementalResponseCacheEntry = await fromResponseCacheEntry({
...responseCacheEntry,
isMiss: !previousIncrementalCacheEntry,
})
// We want to persist the result only if it has a cache control value
// defined.
if (resolveValue.cacheControl) {
if (incrementalResponseCacheEntry.cacheControl) {
if (this.minimal_mode) {
this.previousCacheItem = {
key: cacheKey,
entry: resolveValue,
expiresAt: Date.now() + 1000,
}
// Set TTL expiration for cache hit validation. Entries are validated
// by invocationID when available, with TTL as a fallback for providers
// that don't send x-invocation-id. Memory is managed by LRU eviction.
const cacheKey = createCacheKey(key, invocationID)
this.cache.set(cacheKey, {
entry: incrementalResponseCacheEntry,
expiresAt: Date.now() + this.ttl,
})
} else {
await incrementalCache.set(key, resolveValue.value, {
cacheControl: resolveValue.cacheControl,
await incrementalCache.set(key, incrementalResponseCacheEntry.value, {
cacheControl: incrementalResponseCacheEntry.cacheControl,
isRoutePPREnabled,
isFallback,
})
}
}
return resolveValue
return incrementalResponseCacheEntry
} catch (err) {
// When a path is erroring we automatically re-set the existing cache
// with new revalidate and expire times to prevent non-stop retrying.
if (cachedResponse?.cacheControl) {
const newRevalidate = Math.min(
Math.max(cachedResponse.cacheControl.revalidate || 3, 3),
if (previousIncrementalCacheEntry?.cacheControl) {
const revalidate = Math.min(
Math.max(
previousIncrementalCacheEntry.cacheControl.revalidate || 3,
3
),
30
)
const newExpire =
cachedResponse.cacheControl.expire === undefined
const expire =
previousIncrementalCacheEntry.cacheControl.expire === undefined
? undefined
: Math.max(
newRevalidate + 3,
cachedResponse.cacheControl.expire
revalidate + 3,
previousIncrementalCacheEntry.cacheControl.expire
)
await incrementalCache.set(key, cachedResponse.value, {
cacheControl: { revalidate: newRevalidate, expire: newExpire },
await incrementalCache.set(key, previousIncrementalCacheEntry.value, {
cacheControl: { revalidate: revalidate, expire: expire },
isRoutePPREnabled,
isFallback,
})
}
// While revalidating in the background we can't reject as we already
// resolved the cache entry so log the error here.
if (resolved) {
console.error(err)
return null
}
// We haven't resolved yet, so let's throw to indicate an error.
throw err
}
})()
// we need to ensure background revalidates are
// passed to waitUntil
if (waitUntil) {
waitUntil(prom)
}
return prom
}
)
return toResponseCacheEntry(response)
}
}
......@@ -879,6 +879,9 @@ export abstract class RouteModule<
isRoutePPREnabled,
isOnDemandRevalidate,
isPrefetch: req.headers.purpose === 'prefetch',
// Use x-invocation-id header to scope the in-memory cache to a single
// revalidation request in minimal mode.
invocationID: req.headers['x-invocation-id'] as string | undefined,
incrementalCache: await this.getIncrementalCache(
req,
nextConfig,
......
......@@ -3,8 +3,15 @@
import fs from 'fs-extra'
import { join } from 'path'
import cheerio from 'cheerio'
import { nextServer, startApp, waitFor } from 'next-test-utils'
import { fetchViaHTTP, nextBuild, renderViaHTTP } from 'next-test-utils'
import {
fetchViaHTTP,
nextBuild,
nextServer,
renderViaHTTP,
startApp,
waitFor,
withInvocationId,
} from 'next-test-utils'
const appDir = join(__dirname, '..')
let server
......@@ -84,14 +91,24 @@ describe('Required Server Files', () => {
})
it('should render SSR page correctly', async () => {
const html = await renderViaHTTP(appPort, '/')
const html = await renderViaHTTP(
appPort,
'/',
undefined,
withInvocationId()
)
const $ = cheerio.load(html)
const data = JSON.parse($('#props').text())
expect($('#index').text()).toBe('index page')
expect(data.hello).toBe('world')
const html2 = await renderViaHTTP(appPort, '/')
const html2 = await renderViaHTTP(
appPort,
'/',
undefined,
withInvocationId()
)
const $2 = cheerio.load(html2)
const data2 = JSON.parse($2('#props').text())
......@@ -101,7 +118,12 @@ describe('Required Server Files', () => {
})
it('should render dynamic SSR page correctly', async () => {
const html = await renderViaHTTP(appPort, '/dynamic/first')
const html = await renderViaHTTP(
appPort,
'/dynamic/first',
undefined,
withInvocationId()
)
const $ = cheerio.load(html)
const data = JSON.parse($('#props').text())
......@@ -109,7 +131,12 @@ describe('Required Server Files', () => {
expect($('#slug').text()).toBe('first')
expect(data.hello).toBe('world')
const html2 = await renderViaHTTP(appPort, '/dynamic/second')
const html2 = await renderViaHTTP(
appPort,
'/dynamic/second',
undefined,
withInvocationId()
)
const $2 = cheerio.load(html2)
const data2 = JSON.parse($2('#props').text())
......@@ -120,7 +147,12 @@ describe('Required Server Files', () => {
})
it('should render fallback page correctly', async () => {
const html = await renderViaHTTP(appPort, '/fallback/first')
const html = await renderViaHTTP(
appPort,
'/fallback/first',
undefined,
withInvocationId()
)
const $ = cheerio.load(html)
const data = JSON.parse($('#props').text())
......@@ -129,7 +161,12 @@ describe('Required Server Files', () => {
expect(data.hello).toBe('world')
await waitFor(2000)
const html2 = await renderViaHTTP(appPort, '/fallback/first')
const html2 = await renderViaHTTP(
appPort,
'/fallback/first',
undefined,
withInvocationId()
)
const $2 = cheerio.load(html2)
const data2 = JSON.parse($2('#props').text())
......@@ -138,7 +175,12 @@ describe('Required Server Files', () => {
expect(isNaN(data2.random)).toBe(false)
expect(data2.random).not.toBe(data.random)
const html3 = await renderViaHTTP(appPort, '/fallback/second')
const html3 = await renderViaHTTP(
appPort,
'/fallback/second',
undefined,
withInvocationId()
)
const $3 = cheerio.load(html3)
const data3 = JSON.parse($3('#props').text())
......@@ -149,7 +191,9 @@ describe('Required Server Files', () => {
const { pageProps: data4 } = JSON.parse(
await renderViaHTTP(
appPort,
`/_next/data/${buildId}/fallback/third.json`
`/_next/data/${buildId}/fallback/third.json`,
undefined,
withInvocationId()
)
)
expect(data4.hello).toBe('world')
......@@ -161,11 +205,11 @@ describe('Required Server Files', () => {
appPort,
'/some-other-path',
undefined,
{
withInvocationId({
headers: {
'x-matched-path': '/',
},
}
})
)
const $ = cheerio.load(html)
const data = JSON.parse($('#props').text())
......@@ -177,11 +221,11 @@ describe('Required Server Files', () => {
appPort,
'/some-other-path',
undefined,
{
withInvocationId({
headers: {
'x-matched-path': '/',
},
}
})
)
const $2 = cheerio.load(html2)
const data2 = JSON.parse($2('#props').text())
......@@ -196,11 +240,11 @@ describe('Required Server Files', () => {
appPort,
'/some-other-path?nxtPslug=first',
undefined,
{
withInvocationId({
headers: {
'x-matched-path': '/dynamic/[slug]',
},
}
})
)
const $ = cheerio.load(html)
const data = JSON.parse($('#props').text())
......@@ -213,11 +257,11 @@ describe('Required Server Files', () => {
appPort,
'/some-other-path?slug=second',
undefined,
{
withInvocationId({
headers: {
'x-matched-path': '/dynamic/[slug]',
},
}
})
)
const $2 = cheerio.load(html2)
const data2 = JSON.parse($2('#props').text())
......@@ -233,12 +277,12 @@ describe('Required Server Files', () => {
appPort,
'/fallback/first',
undefined,
{
withInvocationId({
headers: {
'x-matched-path': '/fallback/first',
'x-now-route-matches': 'nxtPslug=first',
},
}
})
)
const $ = cheerio.load(html)
const data = JSON.parse($('#props').text())
......@@ -251,12 +295,12 @@ describe('Required Server Files', () => {
appPort,
`/fallback/[slug]`,
undefined,
{
withInvocationId({
headers: {
'x-matched-path': '/fallback/[slug]',
'x-now-route-matches': 'nxtPslug=second',
},
}
})
)
const $2 = cheerio.load(html2)
const data2 = JSON.parse($2('#props').text())
......@@ -272,11 +316,11 @@ describe('Required Server Files', () => {
appPort,
`/_next/data/${buildId}/dynamic/first.json?nxtPslug=first`,
undefined,
{
withInvocationId({
headers: {
'x-matched-path': '/dynamic/[slug]',
},
}
})
)
const { pageProps: data } = await res.json()
......@@ -288,12 +332,12 @@ describe('Required Server Files', () => {
appPort,
`/_next/data/${buildId}/fallback/[slug].json`,
undefined,
{
withInvocationId({
headers: {
'x-matched-path': `/_next/data/${buildId}/fallback/[slug].json`,
'x-now-route-matches': 'nxtPslug=second',
},
}
})
)
const { pageProps: data2 } = await res2.json()
......@@ -307,12 +351,12 @@ describe('Required Server Files', () => {
appPort,
'/catch-all/[[...rest]]',
undefined,
{
withInvocationId({
headers: {
'x-matched-path': '/catch-all/[[...rest]]',
'x-now-route-matches': '',
},
}
})
)
const $ = cheerio.load(html)
const data = JSON.parse($('#props').text())
......@@ -325,12 +369,12 @@ describe('Required Server Files', () => {
appPort,
'/catch-all/[[...rest]]',
undefined,
{
withInvocationId({
headers: {
'x-matched-path': '/catch-all/[[...rest]]',
'x-now-route-matches': 'nxtPrest=hello',
},
}
})
)
const $2 = cheerio.load(html2)
const data2 = JSON.parse($2('#props').text())
......@@ -344,13 +388,13 @@ describe('Required Server Files', () => {
appPort,
'/catch-all/[[...rest]]',
undefined,
{
withInvocationId({
headers: {
'x-matched-path': '/catch-all/[[...rest]]',
'x-now-route-matches':
'nxtPrest=hello/world&catchAll=hello/world',
},
}
})
)
const $3 = cheerio.load(html3)
const data3 = JSON.parse($3('#props').text())
......@@ -364,11 +408,11 @@ describe('Required Server Files', () => {
appPort,
'/catch-all/[[...rest]]',
{ nxtPrest: 'frank' },
{
withInvocationId({
headers: {
'x-matched-path': '/catch-all/[[...rest]]',
},
}
})
)
const $4 = cheerio.load(html4)
const data4 = JSON.parse($4('#props').text())
......@@ -382,11 +426,11 @@ describe('Required Server Files', () => {
appPort,
'/catch-all/[[...rest]]',
{},
{
withInvocationId({
headers: {
'x-matched-path': '/catch-all/[[...rest]]',
},
}
})
)
const $5 = cheerio.load(html5)
const data5 = JSON.parse($5('#props').text())
......@@ -400,11 +444,11 @@ describe('Required Server Files', () => {
appPort,
'/catch-all/[[...rest]]',
{ nxtPrest: 'frank' },
{
withInvocationId({
headers: {
'x-matched-path': '/catch-all/[[...rest]]',
},
}
})
)
const $6 = cheerio.load(html6)
const data6 = JSON.parse($6('#props').text())
......@@ -437,11 +481,11 @@ describe('Required Server Files', () => {
appPort,
'/partial-catch-all/[domain]/[[...rest]]',
query,
{
withInvocationId({
headers: {
'x-matched-path': '/partial-catch-all/[domain]/[[...rest]]',
},
}
})
)
const $ = cheerio.load(html)
......@@ -458,11 +502,11 @@ describe('Required Server Files', () => {
appPort,
`/_next/data/${buildId}/catch-all.json`,
undefined,
{
withInvocationId({
headers: {
'x-matched-path': '/catch-all/[[...rest]]',
},
}
})
)
const { pageProps: data } = await res.json()
......@@ -474,12 +518,12 @@ describe('Required Server Files', () => {
appPort,
`/_next/data/${buildId}/catch-all/[[...rest]].json`,
undefined,
{
withInvocationId({
headers: {
'x-matched-path': `/_next/data/${buildId}/catch-all/[[...rest]].json`,
'x-now-route-matches': 'nxtPrest=hello&rest=hello',
},
}
})
)
const { pageProps: data2 } = await res2.json()
......@@ -491,12 +535,12 @@ describe('Required Server Files', () => {
appPort,
`/_next/data/${buildId}/catch-all/[[...rest]].json`,
undefined,
{
withInvocationId({
headers: {
'x-matched-path': `/_next/data/${buildId}/catch-all/[[...rest]].json`,
'x-now-route-matches': 'nxtPrest=hello/world&rest=hello/world',
},
}
})
)
const { pageProps: data3 } = await res3.json()
......@@ -515,9 +559,14 @@ describe('Required Server Files', () => {
'/fallback/another/',
'/fallback/another',
]) {
const res = await fetchViaHTTP(appPort, path, undefined, {
const res = await fetchViaHTTP(
appPort,
path,
undefined,
withInvocationId({
redirect: 'manual',
})
)
expect(res.status).toBe(200)
}
......@@ -530,11 +579,11 @@ describe('Required Server Files', () => {
{
path: 'hello/world',
},
{
withInvocationId({
headers: {
'x-matched-path': '/',
},
}
})
)
const $ = cheerio.load(html)
expect(JSON.parse($('#router').text()).query).toEqual({
......@@ -543,19 +592,34 @@ describe('Required Server Files', () => {
})
it('should bubble error correctly for gip page', async () => {
const res = await fetchViaHTTP(appPort, '/errors/gip', { crash: '1' })
const res = await fetchViaHTTP(
appPort,
'/errors/gip',
{ crash: '1' },
withInvocationId()
)
expect(res.status).toBe(500)
expect(await res.text()).toBe('Internal Server Error')
})
it('should bubble error correctly for gssp page', async () => {
const res = await fetchViaHTTP(appPort, '/errors/gssp', { crash: '1' })
const res = await fetchViaHTTP(
appPort,
'/errors/gssp',
{ crash: '1' },
withInvocationId()
)
expect(res.status).toBe(500)
expect(await res.text()).toBe('Internal Server Error')
})
it('should bubble error correctly for gsp page', async () => {
const res = await fetchViaHTTP(appPort, '/errors/gsp/crash')
const res = await fetchViaHTTP(
appPort,
'/errors/gsp/crash',
undefined,
withInvocationId()
)
expect(res.status).toBe(500)
expect(await res.text()).toBe('Internal Server Error')
})
......@@ -565,11 +629,11 @@ describe('Required Server Files', () => {
appPort,
'/optional-ssp',
{ nxtPrest: '', another: 'value' },
{
withInvocationId({
headers: {
'x-matched-path': '/optional-ssp/[[...rest]]',
},
}
})
)
const html = await res.text()
......@@ -584,11 +648,11 @@ describe('Required Server Files', () => {
appPort,
'/optional-ssg',
{ rest: '', another: 'value' },
{
withInvocationId({
headers: {
'x-matched-path': '/optional-ssg/[[...rest]]',
},
}
})
)
const html = await res.text()
......@@ -602,11 +666,11 @@ describe('Required Server Files', () => {
appPort,
'/api/optional',
{ nxtPrest: '', another: 'value' },
{
withInvocationId({
headers: {
'x-matched-path': '/api/optional/[[...rest]]',
},
}
})
)
const json = await res.json()
......@@ -615,12 +679,17 @@ describe('Required Server Files', () => {
})
it('should match the index page correctly', async () => {
const res = await fetchViaHTTP(appPort, '/', undefined, {
const res = await fetchViaHTTP(
appPort,
'/',
undefined,
withInvocationId({
headers: {
'x-matched-path': '/index',
},
redirect: 'manual',
})
)
const html = await res.text()
const $ = cheerio.load(html)
......@@ -628,12 +697,17 @@ describe('Required Server Files', () => {
})
it('should match the root dynamic page correctly', async () => {
const res = await fetchViaHTTP(appPort, '/slug-1', undefined, {
const res = await fetchViaHTTP(
appPort,
'/slug-1',
undefined,
withInvocationId({
headers: {
'x-matched-path': '/[slug]',
},
redirect: 'manual',
})
)
const html = await res.text()
const $ = cheerio.load(html)
......@@ -646,12 +720,17 @@ describe('Required Server Files', () => {
'/non-existent',
'/404',
]) {
const res = await fetchViaHTTP(appPort, pathname, undefined, {
const res = await fetchViaHTTP(
appPort,
pathname,
undefined,
withInvocationId({
headers: {
'x-matched-path': '/404',
redirect: 'manual',
},
})
)
expect(res.status).toBe(404)
expect(await res.text()).toContain('custom 404')
}
......@@ -660,12 +739,17 @@ describe('Required Server Files', () => {
'/_next/static/chunks/pages/index-abc123.js',
'/_next/static/some-file.js',
]) {
const res = await fetchViaHTTP(appPort, pathname, undefined, {
const res = await fetchViaHTTP(
appPort,
pathname,
undefined,
withInvocationId({
headers: {
'x-matched-path': '/404',
redirect: 'manual',
},
})
)
expect(res.status).toBe(404)
expect(res.headers.get('content-type')).toBe(
'text/plain; charset=utf-8'
......
......@@ -16,6 +16,7 @@ import { writeFile } from 'fs-extra'
import getPort from 'get-port'
import { getRandomPort } from 'get-port-please'
import fetch from 'node-fetch'
import { nanoid } from 'nanoid'
import qs from 'querystring'
import treeKill from 'tree-kill'
import { once } from 'events'
......@@ -182,6 +183,37 @@ export function fetchViaHTTP(
return fetch(getFullUrl(appPort, url), opts)
}
/**
* Creates request options with a unique x-invocation-id header for testing
* cache deduplication in minimal mode. Use this when you need to ensure each
* request is treated as independent, or when multiple requests need to share
* the same invocation ID.
*
* @example
* // Independent requests (each gets its own invocation ID)
* const res1 = await fetchViaHTTP(appPort, '/page', undefined, withInvocationId())
* const res2 = await fetchViaHTTP(appPort, '/page', undefined, withInvocationId())
*
* @example
* // Grouped requests (share the same invocation ID for cache testing)
* const sharedOpts = withInvocationId()
* const res1 = await fetchViaHTTP(appPort, '/page', undefined, sharedOpts)
* const res2 = await fetchViaHTTP(appPort, '/_next/data/.../page.json', undefined, sharedOpts)
*
* @param opts - Optional existing RequestInit to merge with
* @returns RequestInit with x-invocation-id header added
*/
export function withInvocationId(opts?: RequestInit): RequestInit {
const invocationId = `test:${nanoid()}`
return {
...opts,
headers: {
...opts?.headers,
'x-invocation-id': invocationId,
},
}
}
export function renderViaHTTP(
appPort: string | number,
pathname: string,
......
......@@ -10,6 +10,7 @@ import {
findPort,
initNextServerScript,
killApp,
withInvocationId,
} from 'next-test-utils'
import { ChildProcess } from 'child_process'
......@@ -105,7 +106,11 @@ describe('required server files app router', () => {
})
it('should send the right cache headers for an app route', async () => {
const res = await fetchViaHTTP(appPort, '/api/test/123', undefined, {
const res = await fetchViaHTTP(
appPort,
'/api/test/123',
undefined,
withInvocationId({
headers: {
'x-matched-path': '/api/test/[slug]',
'x-now-route-matches': createNowRouteMatches({
......@@ -113,6 +118,7 @@ describe('required server files app router', () => {
}).toString(),
},
})
)
expect(res.status).toBe(200)
expect(res.headers.get('cache-control')).toBe('s-maxage=31536000')
})
......@@ -122,7 +128,7 @@ describe('required server files app router', () => {
appPort,
'/optional-catchall/[lang]/[flags]/[[...slug]]',
undefined,
{
withInvocationId({
headers: {
'x-matched-path': '/optional-catchall/[lang]/[flags]/[[...slug]]',
'x-now-route-matches': createNowRouteMatches({
......@@ -131,7 +137,7 @@ describe('required server files app router', () => {
slug: 'slug',
}).toString(),
},
}
})
)
expect(res.status).toBe(200)
......@@ -144,7 +150,7 @@ describe('required server files app router', () => {
appPort,
'/optional-catchall/[lang]/[flags]/[[...slug]]',
undefined,
{
withInvocationId({
headers: {
'x-matched-path': '/optional-catchall/[lang]/[flags]/[[...slug]]',
'x-now-route-matches': createNowRouteMatches({
......@@ -152,7 +158,7 @@ describe('required server files app router', () => {
flags: 'flags',
}).toString(),
},
}
})
)
expect(res.status).toBe(200)
......@@ -164,7 +170,11 @@ describe('required server files app router', () => {
})
it('should send the right cache headers for an app page', async () => {
const res = await fetchViaHTTP(appPort, '/test/123', undefined, {
const res = await fetchViaHTTP(
appPort,
'/test/123',
undefined,
withInvocationId({
headers: {
'x-matched-path': '/test/[slug]',
'x-now-route-matches': createNowRouteMatches({
......@@ -172,6 +182,7 @@ describe('required server files app router', () => {
}).toString(),
},
})
)
expect(res.status).toBe(200)
expect(res.headers.get('cache-control')).toBe(
's-maxage=3600, stale-while-revalidate=31532400'
......@@ -183,13 +194,18 @@ describe('required server files app router', () => {
})
it('should properly handle prerender for bot request', async () => {
const res = await fetchViaHTTP(appPort, '/isr/first', undefined, {
const res = await fetchViaHTTP(
appPort,
'/isr/first',
undefined,
withInvocationId({
headers: {
'user-agent':
'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.179 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
'x-matched-path': '/isr/first',
},
})
)
expect(res.status).toBe(200)
const html = await res.text()
......@@ -197,19 +213,28 @@ describe('required server files app router', () => {
expect($('#page').text()).toBe('/isr/[slug]')
const rscRes = await fetchViaHTTP(appPort, '/isr/first.rsc', undefined, {
const rscRes = await fetchViaHTTP(
appPort,
'/isr/first.rsc',
undefined,
withInvocationId({
headers: {
'user-agent':
'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.179 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
'x-matched-path': '/isr/first',
},
})
)
expect(rscRes.status).toBe(200)
})
it('should properly handle fallback for bot request', async () => {
const res = await fetchViaHTTP(appPort, '/isr/[slug]', undefined, {
const res = await fetchViaHTTP(
appPort,
'/isr/[slug]',
undefined,
withInvocationId({
headers: {
'user-agent':
'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.179 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
......@@ -219,6 +244,7 @@ describe('required server files app router', () => {
'x-matched-path': '/isr/[slug]',
},
})
)
expect(res.status).toBe(200)
const html = await res.text()
......@@ -226,7 +252,11 @@ describe('required server files app router', () => {
expect($('#page').text()).toBe('/isr/[slug]')
const rscRes = await fetchViaHTTP(appPort, '/isr/[slug].rsc', undefined, {
const rscRes = await fetchViaHTTP(
appPort,
'/isr/[slug].rsc',
undefined,
withInvocationId({
headers: {
'user-agent':
'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.179 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
......@@ -236,6 +266,7 @@ describe('required server files app router', () => {
'x-matched-path': '/isr/[slug]',
},
})
)
expect(rscRes.status).toBe(200)
})
......@@ -260,9 +291,14 @@ describe('required server files app router', () => {
],
]) {
require('console').error('checking', { path, tags })
const res = await fetchViaHTTP(appPort, path, undefined, {
const res = await fetchViaHTTP(
appPort,
path,
undefined,
withInvocationId({
redirect: 'manual',
})
)
expect(res.status).toBe(200)
expect(res.headers.get('x-next-cache-tags')).toBe(tags)
}
......@@ -275,9 +311,14 @@ describe('required server files app router', () => {
'/api/ssr/first',
'/api/ssr/second',
]) {
const res = await fetchViaHTTP(appPort, path, undefined, {
const res = await fetchViaHTTP(
appPort,
path,
undefined,
withInvocationId({
redirect: 'manual',
})
)
expect(res.status).toBe(200)
expect(res.headers.get('x-next-cache-tags')).toBeFalsy()
}
......@@ -294,9 +335,9 @@ describe('required server files app router', () => {
appPort,
path,
{ hello: 'world' },
{
withInvocationId({
redirect: 'manual',
}
})
)
expect(res.status).toBe(200)
expect(res.headers.get('x-next-cache-tags')).toBeFalsy()
......@@ -308,11 +349,11 @@ describe('required server files app router', () => {
appPort,
'/search/[key]',
{ key: 'searchParams', nxtPkey: 'params' },
{
withInvocationId({
headers: {
'x-matched-path': '/search/[key]',
},
}
})
)
const html = await res.text()
......@@ -320,4 +361,80 @@ describe('required server files app router', () => {
expect($('dd[data-params]').text()).toBe('params')
expect($('dd[data-searchParams]').text()).toBe('searchParams')
})
it('should de-dupe HTML/RSC requests for ISR pages', async () => {
// Create a shared invocation ID for HTML and RSC requests to test de-duplication
const sharedOpts = withInvocationId()
// First request: HTML for ISR page
const htmlRes = await fetchViaHTTP(appPort, '/isr/[slug]', undefined, {
...sharedOpts,
headers: {
...sharedOpts.headers,
'x-matched-path': '/isr/[slug]',
'x-now-route-matches': createNowRouteMatches({
slug: 'first',
}).toString(),
},
})
expect(htmlRes.status).toBe(200)
const html = await htmlRes.text()
const $ = cheerio.load(html)
const timestamp1 = $('#now').text()
// Second request: RSC for same page with same x-invocation-id
const rscRes = await fetchViaHTTP(appPort, '/isr/[slug].rsc', undefined, {
...sharedOpts,
headers: {
...sharedOpts.headers,
'x-matched-path': '/isr/[slug]',
'x-now-route-matches': createNowRouteMatches({
slug: 'first',
}).toString(),
},
})
expect(rscRes.status).toBe(200)
const rscText = await rscRes.text()
// Both should have the same timestamp (same cached render)
expect(rscText).toContain(timestamp1)
})
it('should isolate cache between different ISR request groups', async () => {
// First group makes a request with its own invocation ID
const group1Opts = withInvocationId()
const res1 = await fetchViaHTTP(appPort, '/isr/[slug]', undefined, {
...group1Opts,
headers: {
...group1Opts.headers,
'x-matched-path': '/isr/[slug]',
'x-now-route-matches': createNowRouteMatches({
slug: 'first',
}).toString(),
},
})
expect(res1.status).toBe(200)
const $1 = cheerio.load(await res1.text())
const data1 = $1('#data').text()
// Second group with different x-invocation-id
const group2Opts = withInvocationId()
const res2 = await fetchViaHTTP(appPort, '/isr/[slug]', undefined, {
...group2Opts,
headers: {
...group2Opts.headers,
'x-matched-path': '/isr/[slug]',
'x-now-route-matches': createNowRouteMatches({
slug: 'first',
}).toString(),
},
})
expect(res2.status).toBe(200)
const $2 = cheerio.load(await res2.text())
const data2 = $2('#data').text()
// Each group should get its own render with different random data
// since ISR pages fetch fresh data on each render
expect(data1).not.toBe(data2)
})
})
......@@ -13,6 +13,7 @@ import {
killApp,
renderViaHTTP,
waitFor,
withInvocationId,
} from 'next-test-utils'
import nodeFetch from 'node-fetch'
import { ChildProcess } from 'child_process'
......@@ -139,22 +140,32 @@ describe('required server files i18n', () => {
})
it('should not apply locale redirect in minimal mode', async () => {
const res = await fetchViaHTTP(appPort, '/', undefined, {
const res = await fetchViaHTTP(
appPort,
'/',
undefined,
withInvocationId({
redirect: 'manual',
headers: {
'accept-language': 'fr',
},
})
)
expect(res.status).toBe(200)
expect(await res.text()).toContain('index page')
const resCookie = await fetchViaHTTP(appPort, '/', undefined, {
const resCookie = await fetchViaHTTP(
appPort,
'/',
undefined,
withInvocationId({
redirect: 'manual',
headers: {
'accept-language': 'en',
cookie: 'NEXT_LOCALE=fr',
},
})
)
expect(resCookie.status).toBe(200)
expect(await resCookie.text()).toContain('index page')
})
......@@ -173,9 +184,14 @@ describe('required server files i18n', () => {
it('should set correct SWR headers with notFound gsp', async () => {
await next.patchFile('standalone/data.txt', 'show')
const res = await fetchViaHTTP(appPort, '/gsp', undefined, {
const res = await fetchViaHTTP(
appPort,
'/gsp',
undefined,
withInvocationId({
redirect: 'manual',
})
)
expect(res.status).toBe(200)
expect(res.headers.get('cache-control')).toBe(
's-maxage=1, stale-while-revalidate=31535999'
......@@ -184,9 +200,14 @@ describe('required server files i18n', () => {
await waitFor(2000)
await next.patchFile('standalone/data.txt', 'hide')
const res2 = await fetchViaHTTP(appPort, '/gsp', undefined, {
const res2 = await fetchViaHTTP(
appPort,
'/gsp',
undefined,
withInvocationId({
redirect: 'manual',
})
)
expect(res2.status).toBe(404)
expect(res2.headers.get('cache-control')).toBe(
's-maxage=1, stale-while-revalidate=31535999'
......@@ -196,9 +217,14 @@ describe('required server files i18n', () => {
it('should set correct SWR headers with notFound gssp', async () => {
await next.patchFile('standalone/data.txt', 'show')
const res = await fetchViaHTTP(appPort, '/gssp', undefined, {
const res = await fetchViaHTTP(
appPort,
'/gssp',
undefined,
withInvocationId({
redirect: 'manual',
})
)
expect(res.status).toBe(200)
expect(res.headers.get('cache-control')).toBe(
's-maxage=1, stale-while-revalidate=31535999'
......@@ -206,9 +232,14 @@ describe('required server files i18n', () => {
await next.patchFile('standalone/data.txt', 'hide')
const res2 = await fetchViaHTTP(appPort, '/gssp', undefined, {
const res2 = await fetchViaHTTP(
appPort,
'/gssp',
undefined,
withInvocationId({
redirect: 'manual',
})
)
await next.patchFile('standalone/data.txt', 'show')
expect(res2.status).toBe(404)
......@@ -218,14 +249,24 @@ describe('required server files i18n', () => {
})
it('should render SSR page correctly', async () => {
const html = await renderViaHTTP(appPort, '/gssp')
const html = await renderViaHTTP(
appPort,
'/gssp',
undefined,
withInvocationId()
)
const $ = cheerio.load(html)
const data = JSON.parse($('#props').text())
expect($('#gssp').text()).toBe('getServerSideProps page')
expect(data.hello).toBe('world')
const html2 = await renderViaHTTP(appPort, '/gssp')
const html2 = await renderViaHTTP(
appPort,
'/gssp',
undefined,
withInvocationId()
)
const $2 = cheerio.load(html2)
const data2 = JSON.parse($2('#props').text())
......@@ -235,7 +276,12 @@ describe('required server files i18n', () => {
})
it('should render dynamic SSR page correctly', async () => {
const html = await renderViaHTTP(appPort, '/dynamic/first')
const html = await renderViaHTTP(
appPort,
'/dynamic/first',
undefined,
withInvocationId()
)
const $ = cheerio.load(html)
const data = JSON.parse($('#props').text())
......@@ -243,7 +289,12 @@ describe('required server files i18n', () => {
expect($('#slug').text()).toBe('first')
expect(data.hello).toBe('world')
const html2 = await renderViaHTTP(appPort, '/dynamic/second')
const html2 = await renderViaHTTP(
appPort,
'/dynamic/second',
undefined,
withInvocationId()
)
const $2 = cheerio.load(html2)
const data2 = JSON.parse($2('#props').text())
......@@ -254,7 +305,12 @@ describe('required server files i18n', () => {
})
it('should render fallback page correctly', async () => {
const html = await renderViaHTTP(appPort, '/fallback/first')
const html = await renderViaHTTP(
appPort,
'/fallback/first',
undefined,
withInvocationId()
)
const $ = cheerio.load(html)
const data = JSON.parse($('#props').text())
......@@ -263,7 +319,13 @@ describe('required server files i18n', () => {
expect(data.hello).toBe('world')
await waitFor(2000)
const html2 = await renderViaHTTP(appPort, '/fallback/first')
const html2 = await renderViaHTTP(
appPort,
'/fallback/first',
undefined,
withInvocationId()
)
const $2 = cheerio.load(html2)
const data2 = JSON.parse($2('#props').text())
......@@ -272,7 +334,12 @@ describe('required server files i18n', () => {
expect(isNaN(data2.random)).toBe(false)
expect(data2.random).not.toBe(data.random)
const html3 = await renderViaHTTP(appPort, '/fallback/second')
const html3 = await renderViaHTTP(
appPort,
'/fallback/second',
undefined,
withInvocationId()
)
const $3 = cheerio.load(html3)
const data3 = JSON.parse($3('#props').text())
......@@ -283,7 +350,9 @@ describe('required server files i18n', () => {
const { pageProps: data4 } = JSON.parse(
await renderViaHTTP(
appPort,
`/_next/data/${next.buildId}/en/fallback/third.json`
`/_next/data/${next.buildId}/en/fallback/third.json`,
undefined,
withInvocationId()
)
)
expect(data4.hello).toBe('world')
......@@ -291,22 +360,32 @@ describe('required server files i18n', () => {
})
it('should render SSR page correctly with x-matched-path', async () => {
const html = await renderViaHTTP(appPort, '/some-other-path', undefined, {
const html = await renderViaHTTP(
appPort,
'/some-other-path',
undefined,
withInvocationId({
headers: {
'x-matched-path': '/gssp',
},
})
)
const $ = cheerio.load(html)
const data = JSON.parse($('#props').text())
expect($('#gssp').text()).toBe('getServerSideProps page')
expect(data.hello).toBe('world')
const html2 = await renderViaHTTP(appPort, '/some-other-path', undefined, {
const html2 = await renderViaHTTP(
appPort,
'/some-other-path',
undefined,
withInvocationId({
headers: {
'x-matched-path': '/gssp',
},
})
)
const $2 = cheerio.load(html2)
const data2 = JSON.parse($2('#props').text())
......@@ -320,11 +399,11 @@ describe('required server files i18n', () => {
appPort,
'/some-other-path?nxtPslug=first',
undefined,
{
withInvocationId({
headers: {
'x-matched-path': '/dynamic/[slug]',
},
}
})
)
const $ = cheerio.load(html)
const data = JSON.parse($('#props').text())
......@@ -337,11 +416,11 @@ describe('required server files i18n', () => {
appPort,
'/some-other-path?nxtPslug=second',
undefined,
{
withInvocationId({
headers: {
'x-matched-path': '/dynamic/[slug]',
},
}
})
)
const $2 = cheerio.load(html2)
const data2 = JSON.parse($2('#props').text())
......@@ -355,11 +434,11 @@ describe('required server files i18n', () => {
appPort,
'/some-other-path?nxtPslug=second',
undefined,
{
withInvocationId({
headers: {
'x-matched-path': '/dynamic/[slug]?slug=%5Bslug%5D.json',
},
}
})
)
const $3 = cheerio.load(html3)
const data3 = JSON.parse($3('#props').text())
......@@ -371,7 +450,11 @@ describe('required server files i18n', () => {
})
it('should render fallback page correctly with x-matched-path and routes-matches', async () => {
const html = await renderViaHTTP(appPort, '/fallback/first', undefined, {
const html = await renderViaHTTP(
appPort,
'/fallback/first',
undefined,
withInvocationId({
headers: {
'x-matched-path': '/fallback/first',
'x-now-route-matches': createNowRouteMatches({
......@@ -379,6 +462,7 @@ describe('required server files i18n', () => {
}).toString(),
},
})
)
const $ = cheerio.load(html)
const data = JSON.parse($('#props').text())
......@@ -386,7 +470,11 @@ describe('required server files i18n', () => {
expect($('#slug').text()).toBe('first')
expect(data.hello).toBe('world')
const html2 = await renderViaHTTP(appPort, `/fallback/[slug]`, undefined, {
const html2 = await renderViaHTTP(
appPort,
`/fallback/[slug]`,
undefined,
withInvocationId({
headers: {
'x-matched-path': '/fallback/[slug]',
'x-now-route-matches': createNowRouteMatches({
......@@ -394,6 +482,7 @@ describe('required server files i18n', () => {
}).toString(),
},
})
)
const $2 = cheerio.load(html2)
const data2 = JSON.parse($2('#props').text())
......@@ -410,11 +499,11 @@ describe('required server files i18n', () => {
{ slug: 'first' }
).toString()}`,
undefined,
{
withInvocationId({
headers: {
'x-matched-path': '/dynamic/[slug]',
},
}
})
)
const { pageProps: data } = await res.json()
......@@ -426,14 +515,14 @@ describe('required server files i18n', () => {
appPort,
`/_next/data/${next.buildId}/en/fallback/[slug].json`,
undefined,
{
withInvocationId({
headers: {
'x-matched-path': `/_next/data/${next.buildId}/en/fallback/[slug].json`,
'x-now-route-matches': createNowRouteMatches({
slug: 'second',
}).toString(),
},
}
})
)
const { pageProps: data2 } = await res2.json()
......@@ -447,12 +536,12 @@ describe('required server files i18n', () => {
appPort,
'/catch-all/[[...rest]]',
undefined,
{
withInvocationId({
headers: {
'x-matched-path': '/catch-all/[[...rest]]',
'x-now-route-matches': '',
},
}
})
)
const $ = cheerio.load(html)
const data = JSON.parse($('#props').text())
......@@ -465,14 +554,14 @@ describe('required server files i18n', () => {
appPort,
'/catch-all/[[...rest]]',
undefined,
{
withInvocationId({
headers: {
'x-matched-path': '/catch-all/[[...rest]]',
'x-now-route-matches': createNowRouteMatches({
rest: 'hello',
}).toString(),
},
}
})
)
const $2 = cheerio.load(html2)
const data2 = JSON.parse($2('#props').text())
......@@ -486,14 +575,14 @@ describe('required server files i18n', () => {
appPort,
'/catch-all/[[...rest]]',
undefined,
{
withInvocationId({
headers: {
'x-matched-path': '/catch-all/[[...rest]]',
'x-now-route-matches': createNowRouteMatches({
rest: 'hello/world',
}).toString(),
},
}
})
)
const $3 = cheerio.load(html3)
const data3 = JSON.parse($3('#props').text())
......@@ -509,11 +598,11 @@ describe('required server files i18n', () => {
appPort,
`/_next/data/${next.buildId}/en/catch-all.json`,
undefined,
{
withInvocationId({
headers: {
'x-matched-path': '/en/catch-all/[[...rest]]',
},
}
})
)
const { pageProps: data } = await res.json()
......@@ -525,14 +614,14 @@ describe('required server files i18n', () => {
appPort,
`/_next/data/${next.buildId}/en/catch-all/[[...rest]].json`,
undefined,
{
withInvocationId({
headers: {
'x-matched-path': `/_next/data/${next.buildId}/en/catch-all/[[...rest]].json`,
'x-now-route-matches': createNowRouteMatches({
rest: 'hello',
}).toString(),
},
}
})
)
const { pageProps: data2 } = await res2.json()
......@@ -544,14 +633,14 @@ describe('required server files i18n', () => {
appPort,
`/_next/data/${next.buildId}/en/catch-all/[[...rest]].json`,
undefined,
{
withInvocationId({
headers: {
'x-matched-path': `/_next/data/${next.buildId}/en/catch-all/[[...rest]].json`,
'x-now-route-matches': createNowRouteMatches({
rest: 'hello/world',
}).toString(),
},
}
})
)
const { pageProps: data3 } = await res3.json()
......@@ -570,9 +659,14 @@ describe('required server files i18n', () => {
'/fallback/another/',
'/fallback/another',
]) {
const res = await fetchViaHTTP(appPort, path, undefined, {
const res = await fetchViaHTTP(
appPort,
path,
undefined,
withInvocationId({
redirect: 'manual',
})
)
expect(res.status).toBe(200)
}
......@@ -585,11 +679,11 @@ describe('required server files i18n', () => {
{
path: 'hello/world',
},
{
withInvocationId({
headers: {
'x-matched-path': '/gssp',
},
}
})
)
const $ = cheerio.load(html)
expect(JSON.parse($('#router').text()).query.path).toEqual([
......@@ -607,18 +701,23 @@ describe('required server files i18n', () => {
path: '%c0.%c0.',
})
),
{
withInvocationId({
headers: {
'x-matched-path': '/dynamic/[slug]',
},
}
})
)
expect(res.status).toBe(400)
expect(await res.text()).toContain('Bad Request')
})
it('should bubble error correctly for gip page', async () => {
const res = await fetchViaHTTP(appPort, '/errors/gip', { crash: '1' })
const res = await fetchViaHTTP(
appPort,
'/errors/gip',
{ crash: '1' },
withInvocationId()
)
expect(res.status).toBe(500)
expect(await res.text()).toBe('Internal Server Error')
......@@ -632,7 +731,12 @@ describe('required server files i18n', () => {
})
it('should bubble error correctly for gssp page', async () => {
const res = await fetchViaHTTP(appPort, '/errors/gssp', { crash: '1' })
const res = await fetchViaHTTP(
appPort,
'/errors/gssp',
{ crash: '1' },
withInvocationId()
)
expect(res.status).toBe(500)
expect(await res.text()).toBe('Internal Server Error')
await check(
......@@ -645,7 +749,12 @@ describe('required server files i18n', () => {
})
it('should bubble error correctly for gsp page', async () => {
const res = await fetchViaHTTP(appPort, '/errors/gsp/crash')
const res = await fetchViaHTTP(
appPort,
'/errors/gsp/crash',
undefined,
withInvocationId()
)
expect(res.status).toBe(500)
expect(await res.text()).toBe('Internal Server Error')
await check(
......@@ -659,7 +768,12 @@ describe('required server files i18n', () => {
it('should bubble error correctly for API page', async () => {
errors = []
const res = await fetchViaHTTP(appPort, '/api/error')
const res = await fetchViaHTTP(
appPort,
'/api/error',
undefined,
withInvocationId()
)
expect(res.status).toBe(500)
expect(await res.text()).toBe('Internal Server Error')
await check(
......@@ -685,11 +799,11 @@ describe('required server files i18n', () => {
}
)
),
{
withInvocationId({
headers: {
'x-matched-path': '/optional-ssp/[[...rest]]',
},
}
})
)
const html = await res.text()
......@@ -704,7 +818,7 @@ describe('required server files i18n', () => {
appPort,
'/en/optional-ssg/[[...rest]]',
undefined,
{
withInvocationId({
headers: {
'x-matched-path': '/en/optional-ssg/[[...rest]]',
'x-now-route-matches': createNowRouteMatches(
......@@ -714,7 +828,7 @@ describe('required server files i18n', () => {
}
).toString(),
},
}
})
)
const html = await res.text()
......@@ -728,7 +842,7 @@ describe('required server files i18n', () => {
appPort,
'/en/[slug]/social/[[...rest]]',
undefined,
{
withInvocationId({
headers: {
'x-matched-path': '/en/[slug]/social/[[...rest]]',
'x-now-route-matches': createNowRouteMatches(
......@@ -736,7 +850,7 @@ describe('required server files i18n', () => {
{ nextLocale: 'en' }
).toString(),
},
}
})
)
const html = await res.text()
......@@ -753,12 +867,12 @@ describe('required server files i18n', () => {
appPort,
'/optional-ssg/[[...rest]]',
undefined,
{
withInvocationId({
headers: {
'x-matched-path': '/optional-ssg/[[...rest]]',
'x-now-route-matches': 'nxtPrest=en%2Fes%2Fhello%252Fworld',
},
}
})
)
const html = await res.text()
......@@ -783,11 +897,11 @@ describe('required server files i18n', () => {
}
)
),
{
withInvocationId({
headers: {
'x-matched-path': '/api/optional/[[...rest]]',
},
}
})
)
const json = await res.json()
......@@ -796,12 +910,17 @@ describe('required server files i18n', () => {
})
it('should match the index page correctly', async () => {
const res = await fetchViaHTTP(appPort, '/', undefined, {
const res = await fetchViaHTTP(
appPort,
'/',
undefined,
withInvocationId({
headers: {
'x-matched-path': '/index',
},
redirect: 'manual',
})
)
const html = await res.text()
const $ = cheerio.load(html)
......@@ -809,12 +928,17 @@ describe('required server files i18n', () => {
})
it('should match the root dyanmic page correctly', async () => {
const res = await fetchViaHTTP(appPort, '/slug-1', undefined, {
const res = await fetchViaHTTP(
appPort,
'/slug-1',
undefined,
withInvocationId({
headers: {
'x-matched-path': '/[slug]',
},
redirect: 'manual',
})
)
const html = await res.text()
const $ = cheerio.load(html)
......@@ -822,7 +946,11 @@ describe('required server files i18n', () => {
})
it('should have the correct asPath for fallback page', async () => {
const res = await fetchViaHTTP(appPort, '/en/fallback/[slug]', undefined, {
const res = await fetchViaHTTP(
appPort,
'/en/fallback/[slug]',
undefined,
withInvocationId({
headers: {
'x-matched-path': '/en/fallback/[slug]',
'x-now-route-matches': createNowRouteMatches(
......@@ -836,6 +964,7 @@ describe('required server files i18n', () => {
},
redirect: 'manual',
})
)
const html = await res.text()
const $ = cheerio.load(html)
......@@ -847,7 +976,11 @@ describe('required server files i18n', () => {
})
it('should have the correct asPath for fallback page locale', async () => {
const res = await fetchViaHTTP(appPort, '/fr/fallback/[slug]', undefined, {
const res = await fetchViaHTTP(
appPort,
'/fr/fallback/[slug]',
undefined,
withInvocationId({
headers: {
'x-matched-path': '/fr/fallback/[slug]',
'x-now-route-matches': createNowRouteMatches(
......@@ -861,6 +994,7 @@ describe('required server files i18n', () => {
},
redirect: 'manual',
})
)
const html = await res.text()
const $ = cheerio.load(html)
......
......@@ -10,6 +10,7 @@ import {
findPort,
initNextServerScript,
killApp,
withInvocationId,
} from 'next-test-utils'
import { ChildProcess } from 'child_process'
......@@ -139,12 +140,19 @@ describe('required server files app router', () => {
require('console').error('requesting', outputSegmentPath)
const res = await fetchViaHTTP(appPort, outputSegmentPath, undefined, {
const res = await fetchViaHTTP(
appPort,
outputSegmentPath,
undefined,
withInvocationId({
headers: {
'x-matched-path': '/isr/[slug].segments/_tree.segment.rsc',
'x-now-route-matches': 'slug=first&1=first',
'x-now-route-matches': createNowRouteMatches({
slug: 'first',
}).toString(),
},
})
)
expect(res.status).toBe(200)
expect(res.headers.get('content-type')).toBe('text/x-component')
......@@ -158,7 +166,11 @@ describe('required server files app router', () => {
}
it('should properly stream resume with Next-Resume', async () => {
const res = await fetchViaHTTP(appPort, '/delayed', undefined, {
const res = await fetchViaHTTP(
appPort,
'/delayed',
undefined,
withInvocationId({
headers: {
'x-matched-path': '/delayed',
'next-resume': '1',
......@@ -166,6 +178,7 @@ describe('required server files app router', () => {
method: 'POST',
body: delayedPostpone,
})
)
expect(res.status).toBe(200)
......@@ -192,13 +205,18 @@ describe('required server files app router', () => {
})
it('should properly handle prerender for bot request', async () => {
const res = await fetchViaHTTP(appPort, '/isr/first', undefined, {
const res = await fetchViaHTTP(
appPort,
'/isr/first',
undefined,
withInvocationId({
headers: {
'user-agent':
'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.179 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
'x-matched-path': '/isr/first',
},
})
)
expect(res.status).toBe(200)
const html = await res.text()
......@@ -206,19 +224,28 @@ describe('required server files app router', () => {
expect($('#page').text()).toBe('/isr/[slug]')
const rscRes = await fetchViaHTTP(appPort, '/isr/first.rsc', undefined, {
const rscRes = await fetchViaHTTP(
appPort,
'/isr/first.rsc',
undefined,
withInvocationId({
headers: {
'user-agent':
'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.179 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
'x-matched-path': '/isr/first',
},
})
)
expect(rscRes.status).toBe(200)
})
it('should properly handle fallback for bot request', async () => {
const res = await fetchViaHTTP(appPort, '/isr/[slug]', undefined, {
const res = await fetchViaHTTP(
appPort,
'/isr/[slug]',
undefined,
withInvocationId({
headers: {
'user-agent':
'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.179 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
......@@ -228,6 +255,7 @@ describe('required server files app router', () => {
'x-matched-path': '/isr/[slug]',
},
})
)
expect(res.status).toBe(200)
const html = await res.text()
......@@ -235,7 +263,11 @@ describe('required server files app router', () => {
expect($('#page').text()).toBe('/isr/[slug]')
const rscRes = await fetchViaHTTP(appPort, '/isr/[slug].rsc', undefined, {
const rscRes = await fetchViaHTTP(
appPort,
'/isr/[slug].rsc',
undefined,
withInvocationId({
headers: {
'user-agent':
'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.179 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
......@@ -245,6 +277,7 @@ describe('required server files app router', () => {
'x-matched-path': '/isr/[slug]',
},
})
)
expect(rscRes.status).toBe(200)
})
......@@ -255,14 +288,14 @@ describe('required server files app router', () => {
appPort,
'/rewrite-with-cookie',
undefined,
{
withInvocationId({
method: 'POST',
headers: {
'x-matched-path': '/rewrite/first-cookie',
'next-resume': '1',
},
body: rewritePostpone,
}
})
)
expect(res.status).toBe(200)
......@@ -277,7 +310,11 @@ describe('required server files app router', () => {
it('should still render when postponed is corrupted with Next-Resume', async () => {
const random = Math.random().toString(36).substring(2)
const res = await fetchViaHTTP(appPort, '/dyn/' + random, undefined, {
const res = await fetchViaHTTP(
appPort,
'/dyn/' + random,
undefined,
withInvocationId({
method: 'POST',
headers: {
'x-matched-path': '/dyn/[slug]',
......@@ -286,6 +323,7 @@ describe('required server files app router', () => {
// This is a corrupted postponed JSON payload.
body: '{',
})
)
expect(res.status).toBe(200)
......@@ -316,9 +354,14 @@ describe('required server files app router', () => {
],
]) {
require('console').error('checking', { path, tags })
const res = await fetchViaHTTP(appPort, path, undefined, {
const res = await fetchViaHTTP(
appPort,
path,
undefined,
withInvocationId({
redirect: 'manual',
})
)
expect(res.status).toBe(200)
expect(res.headers.get('x-next-cache-tags')).toBe(tags)
}
......@@ -331,9 +374,15 @@ describe('required server files app router', () => {
'/api/ssr/first',
'/api/ssr/second',
]) {
const res = await fetchViaHTTP(appPort, path, undefined, {
const res = await fetchViaHTTP(
appPort,
path,
undefined,
withInvocationId({
redirect: 'manual',
})
)
expect(res.status).toBe(200)
expect(res.headers.get('x-next-cache-tags')).toBeFalsy()
}
......@@ -350,9 +399,9 @@ describe('required server files app router', () => {
appPort,
path,
{ hello: 'world' },
{
withInvocationId({
redirect: 'manual',
}
})
)
expect(res.status).toBe(200)
expect(res.headers.get('x-next-cache-tags')).toBeFalsy()
......@@ -360,11 +409,19 @@ describe('required server files app router', () => {
})
it('should handle RSC requests', async () => {
const res = await fetchViaHTTP(appPort, '/dyn/first.rsc', undefined, {
const res = await fetchViaHTTP(
appPort,
'/dyn/first.rsc',
undefined,
withInvocationId({
headers: {
'x-matched-path': '/dyn/[slug]',
'x-now-route-matches': createNowRouteMatches({
slug: 'first',
}).toString(),
},
})
)
expect(res.status).toBe(200)
expect(res.headers.get('content-type')).toEqual('text/x-component')
......@@ -376,11 +433,11 @@ describe('required server files app router', () => {
appPort,
'/dyn/first.prefetch.rsc',
undefined,
{
withInvocationId({
headers: {
'x-matched-path': '/dyn/[slug]',
},
}
})
)
expect(res.status).toBe(200)
......@@ -389,7 +446,11 @@ describe('required server files app router', () => {
})
it('should handle revalidating the fallback page', async () => {
const res = await fetchViaHTTP(appPort, '/postpone/isr/[slug]', undefined, {
const res = await fetchViaHTTP(
appPort,
'/postpone/isr/[slug]',
undefined,
withInvocationId({
headers: {
'x-matched-path': '/postpone/isr/[slug]',
// We don't include the `x-now-route-matches` header because we want to
......@@ -397,6 +458,7 @@ describe('required server files app router', () => {
'x-now-route-matches': '',
},
})
)
expect(res.status).toBe(200)
......
......@@ -15,6 +15,7 @@ import {
renderViaHTTP,
retry,
waitFor,
withInvocationId,
} from 'next-test-utils'
import { ChildProcess } from 'child_process'
......@@ -173,12 +174,12 @@ describe('required server files', () => {
appPort,
'/route-resolving/import/first',
undefined,
{
withInvocationId({
redirect: 'manual',
headers: {
'x-matched-path': '/route-resolving/import/[slug]',
},
}
})
)
expect(res.status).toBe(307)
expect(new URL(res.headers.get('location'), 'http://n').pathname).toBe(
......@@ -197,11 +198,16 @@ describe('required server files', () => {
await next.renameFile(toRename, `${toRename}.bak`)
try {
const res = await fetchViaHTTP(appPort, '/auto-static', undefined, {
const res = await fetchViaHTTP(
appPort,
'/auto-static',
undefined,
withInvocationId({
headers: {
'x-matched-path': '/auto-static',
},
})
)
expect(res.status).toBe(500)
await check(() => stderr, /Invariant: failed to load static page/)
......@@ -226,9 +232,14 @@ describe('required server files', () => {
])(
`should have correct cache-control for $case`,
async ({ path, dest, cacheControl }) => {
const res = await fetchViaHTTP(appPort, path, undefined, {
const res = await fetchViaHTTP(
appPort,
path,
undefined,
withInvocationId({
redirect: 'manual',
})
)
expect(res.status).toBe(307)
expect(new URL(res.headers.get('location'), 'http://n').pathname).toBe(
dest
......@@ -239,9 +250,9 @@ describe('required server files', () => {
appPort,
`/_next/data/${next.buildId}${path}.json`,
undefined,
{
withInvocationId({
redirect: 'manual',
}
})
)
expect(dataRes.headers.get('cache-control')).toBe(cacheControl)
expect((await dataRes.json()).pageProps).toEqual({
......@@ -256,11 +267,11 @@ describe('required server files', () => {
appPort,
`/_next/data/${next.buildId}/catch-all.json`,
{},
{
withInvocationId({
headers: {
'x-matched-path': `/_next/data/${next.buildId}/catch-all.json`,
},
}
})
)
expect(res.status).toBe(200)
......@@ -273,11 +284,11 @@ describe('required server files', () => {
appPort,
`/_next/data/${next.buildId}/catch-all/next.js.json`,
{},
{
withInvocationId({
headers: {
'x-matched-path': `/_next/data/${next.buildId}/catch-all/next.js.json`,
},
}
})
)
expect(res.status).toBe(200)
......@@ -303,9 +314,14 @@ describe('required server files', () => {
])(
`should have correct cache-control for $case`,
async ({ path, dest, cacheControl }) => {
const res = await fetchViaHTTP(appPort, path, undefined, {
const res = await fetchViaHTTP(
appPort,
path,
undefined,
withInvocationId({
redirect: 'manual',
})
)
expect(res.status).toBe(404)
expect(res.headers.get('cache-control')).toBe(cacheControl)
......@@ -313,16 +329,21 @@ describe('required server files', () => {
appPort,
`/_next/data/${next.buildId}${path}.json`,
undefined,
{
withInvocationId({
redirect: 'manual',
}
})
)
expect(dataRes.headers.get('cache-control')).toBe(cacheControl)
}
)
it('should have the correct cache-control for props with no revalidate', async () => {
const res = await fetchViaHTTP(appPort, '/optional-ssg/props-no-revalidate')
const res = await fetchViaHTTP(
appPort,
'/optional-ssg/props-no-revalidate',
undefined,
withInvocationId()
)
expect(res.status).toBe(200)
expect(res.headers.get('cache-control')).toBe('s-maxage=31536000')
const $ = cheerio.load(await res.text())
......@@ -333,7 +354,8 @@ describe('required server files', () => {
const dataRes = await fetchViaHTTP(
appPort,
`/_next/data/${next.buildId}/optional-ssg/props-no-revalidate.json`,
undefined
undefined,
withInvocationId()
)
expect(dataRes.status).toBe(200)
expect(res.headers.get('cache-control')).toBe('s-maxage=31536000')
......@@ -346,7 +368,7 @@ describe('required server files', () => {
;(process.env.IS_TURBOPACK_TEST ? it.skip : it)(
'should warn when "next" is imported directly',
async () => {
await renderViaHTTP(appPort, '/gssp')
await renderViaHTTP(appPort, '/gssp', undefined, withInvocationId())
await check(
() => stderr,
/"next" should not be imported directly, imported in/
......@@ -414,9 +436,14 @@ describe('required server files', () => {
})
it('should de-dupe HTML/data requests', async () => {
// Create a shared invocation ID for /gsp - both HTML and JSON requests share same x-invocation-id
const gspOpts = withInvocationId()
const res = await fetchViaHTTP(appPort, '/gsp', undefined, {
...gspOpts,
redirect: 'manual',
headers: {
...gspOpts.headers,
// ensure the nextjs-data header being present
// doesn't incorrectly return JSON for HTML path
// during prerendering
......@@ -434,6 +461,7 @@ describe('required server files', () => {
`/_next/data/${next.buildId}/gsp.json`,
undefined,
{
...gspOpts,
redirect: 'manual',
}
)
......@@ -442,9 +470,14 @@ describe('required server files', () => {
const { pageProps: props2 } = await res2.json()
expect(props2.gspCalls).toBe(props.gspCalls)
// Create a separate shared invocation ID for /index - different x-invocation-id
const indexOpts = withInvocationId()
const res3 = await fetchViaHTTP(appPort, '/index', undefined, {
...indexOpts,
redirect: 'manual',
headers: {
...indexOpts.headers,
'x-matched-path': '/index',
},
})
......@@ -458,6 +491,7 @@ describe('required server files', () => {
`/_next/data/${next.buildId}/index.json`,
undefined,
{
...indexOpts,
redirect: 'manual',
}
)
......@@ -466,30 +500,6 @@ describe('required server files', () => {
expect(props4.gspCalls).toBe(props3.gspCalls)
})
it('should cap de-dupe previousCacheItem expires time', async () => {
const res = await fetchViaHTTP(appPort, '/gsp-long-revalidate', undefined, {
redirect: 'manual',
})
expect(res.status).toBe(200)
const $ = cheerio.load(await res.text())
const props = JSON.parse($('#props').text())
expect(props.gspCalls).toBeDefined()
await waitFor(1000)
const res2 = await fetchViaHTTP(
appPort,
`/_next/data/${next.buildId}/gsp-long-revalidate.json`,
undefined,
{
redirect: 'manual',
}
)
expect(res2.status).toBe(200)
const { pageProps: props2 } = await res2.json()
expect(props2.gspCalls).not.toBe(props.gspCalls)
})
it('should not 404 for onlyGenerated on-demand revalidate in minimal mode', async () => {
const previewProps = JSON.parse(
await next.readFile('standalone/.next/prerender-manifest.json')
......@@ -499,12 +509,12 @@ describe('required server files', () => {
appPort,
'/optional-ssg/only-generated-1',
undefined,
{
withInvocationId({
headers: {
'x-prerender-revalidate': previewProps.previewModeId,
'x-prerender-revalidate-if-generated': '1',
},
}
})
)
expect(res.status).toBe(200)
})
......@@ -513,9 +523,14 @@ describe('required server files', () => {
await waitFor(2000)
await next.patchFile('standalone/data.txt', 'show')
const res = await fetchViaHTTP(appPort, '/gsp', undefined, {
const res = await fetchViaHTTP(
appPort,
'/gsp',
undefined,
withInvocationId({
redirect: 'manual',
})
)
expect(res.status).toBe(200)
expect(res.headers.get('cache-control')).toBe(
's-maxage=1, stale-while-revalidate=31535999'
......@@ -524,9 +539,14 @@ describe('required server files', () => {
await waitFor(2000)
await next.patchFile('standalone/data.txt', 'hide')
const res2 = await fetchViaHTTP(appPort, '/gsp', undefined, {
const res2 = await fetchViaHTTP(
appPort,
'/gsp',
undefined,
withInvocationId({
redirect: 'manual',
})
)
expect(res2.status).toBe(404)
expect(res2.headers.get('cache-control')).toBe(
's-maxage=1, stale-while-revalidate=31535999'
......@@ -536,9 +556,14 @@ describe('required server files', () => {
it('should set correct SWR headers with notFound gssp', async () => {
await next.patchFile('standalone/data.txt', 'show')
const res = await fetchViaHTTP(appPort, '/gssp', undefined, {
const res = await fetchViaHTTP(
appPort,
'/gssp',
undefined,
withInvocationId({
redirect: 'manual',
})
)
expect(res.status).toBe(200)
expect(res.headers.get('cache-control')).toBe(
's-maxage=1, stale-while-revalidate=31535999'
......@@ -546,9 +571,14 @@ describe('required server files', () => {
await next.patchFile('standalone/data.txt', 'hide')
const res2 = await fetchViaHTTP(appPort, '/gssp', undefined, {
const res2 = await fetchViaHTTP(
appPort,
'/gssp',
undefined,
withInvocationId({
redirect: 'manual',
})
)
await next.patchFile('standalone/data.txt', 'show')
expect(res2.status).toBe(404)
......@@ -558,14 +588,24 @@ describe('required server files', () => {
})
it('should render SSR page correctly', async () => {
const html = await renderViaHTTP(appPort, '/gssp')
const html = await renderViaHTTP(
appPort,
'/gssp',
undefined,
withInvocationId()
)
const $ = cheerio.load(html)
const data = JSON.parse($('#props').text())
expect($('#gssp').text()).toBe('getServerSideProps page')
expect(data.hello).toBe('world')
const html2 = await renderViaHTTP(appPort, '/gssp')
const html2 = await renderViaHTTP(
appPort,
'/gssp',
undefined,
withInvocationId()
)
const $2 = cheerio.load(html2)
const data2 = JSON.parse($2('#props').text())
......@@ -575,7 +615,12 @@ describe('required server files', () => {
})
it('should render dynamic SSR page correctly', async () => {
const html = await renderViaHTTP(appPort, '/dynamic/first')
const html = await renderViaHTTP(
appPort,
'/dynamic/first',
undefined,
withInvocationId()
)
const $ = cheerio.load(html)
const data = JSON.parse($('#props').text())
......@@ -583,7 +628,12 @@ describe('required server files', () => {
expect($('#slug').text()).toBe('first')
expect(data.hello).toBe('world')
const html2 = await renderViaHTTP(appPort, '/dynamic/second')
const html2 = await renderViaHTTP(
appPort,
'/dynamic/second',
undefined,
withInvocationId()
)
const $2 = cheerio.load(html2)
const data2 = JSON.parse($2('#props').text())
......@@ -594,7 +644,12 @@ describe('required server files', () => {
})
it('should render fallback page correctly', async () => {
const html = await renderViaHTTP(appPort, '/fallback/first')
const html = await renderViaHTTP(
appPort,
'/fallback/first',
undefined,
withInvocationId()
)
const $ = cheerio.load(html)
const data = JSON.parse($('#props').text())
......@@ -603,7 +658,13 @@ describe('required server files', () => {
expect(data.hello).toBe('world')
await waitFor(2000)
const html2 = await renderViaHTTP(appPort, '/fallback/first')
const html2 = await renderViaHTTP(
appPort,
'/fallback/first',
undefined,
withInvocationId()
)
const $2 = cheerio.load(html2)
const data2 = JSON.parse($2('#props').text())
......@@ -612,7 +673,12 @@ describe('required server files', () => {
expect(isNaN(data2.random)).toBe(false)
expect(data2.random).not.toBe(data.random)
const html3 = await renderViaHTTP(appPort, '/fallback/second')
const html3 = await renderViaHTTP(
appPort,
'/fallback/second',
undefined,
withInvocationId()
)
const $3 = cheerio.load(html3)
const data3 = JSON.parse($3('#props').text())
......@@ -623,7 +689,9 @@ describe('required server files', () => {
const { pageProps: data4 } = JSON.parse(
await renderViaHTTP(
appPort,
`/_next/data/${next.buildId}/fallback/third.json`
`/_next/data/${next.buildId}/fallback/third.json`,
undefined,
withInvocationId()
)
)
expect(data4.hello).toBe('world')
......@@ -631,22 +699,32 @@ describe('required server files', () => {
})
it('should render SSR page correctly with x-matched-path', async () => {
const html = await renderViaHTTP(appPort, '/some-other-path', undefined, {
const html = await renderViaHTTP(
appPort,
'/some-other-path',
undefined,
withInvocationId({
headers: {
'x-matched-path': '/gssp',
},
})
)
const $ = cheerio.load(html)
const data = JSON.parse($('#props').text())
expect($('#gssp').text()).toBe('getServerSideProps page')
expect(data.hello).toBe('world')
const html2 = await renderViaHTTP(appPort, '/some-other-path', undefined, {
const html2 = await renderViaHTTP(
appPort,
'/some-other-path',
undefined,
withInvocationId({
headers: {
'x-matched-path': '/gssp',
},
})
)
const $2 = cheerio.load(html2)
const data2 = JSON.parse($2('#props').text())
......@@ -660,11 +738,11 @@ describe('required server files', () => {
appPort,
'/some-other-path?nxtPslug=first',
undefined,
{
withInvocationId({
headers: {
'x-matched-path': '/dynamic/[slug]',
},
}
})
)
const $ = cheerio.load(html)
const data = JSON.parse($('#props').text())
......@@ -677,11 +755,11 @@ describe('required server files', () => {
appPort,
'/some-other-path?nxtPslug=second',
undefined,
{
withInvocationId({
headers: {
'x-matched-path': '/dynamic/[slug]',
},
}
})
)
const $2 = cheerio.load(html2)
const data2 = JSON.parse($2('#props').text())
......@@ -695,11 +773,11 @@ describe('required server files', () => {
appPort,
'/some-other-path?nxtPslug=second',
undefined,
{
withInvocationId({
headers: {
'x-matched-path': '/dynamic/[slug]',
},
}
})
)
const $3 = cheerio.load(html3)
const data3 = JSON.parse($3('#props').text())
......@@ -711,7 +789,11 @@ describe('required server files', () => {
})
it('should render fallback page correctly with x-matched-path and routes-matches', async () => {
const html = await renderViaHTTP(appPort, '/fallback/first', undefined, {
const html = await renderViaHTTP(
appPort,
'/fallback/first',
undefined,
withInvocationId({
headers: {
'x-matched-path': '/fallback/first',
'x-now-route-matches': createNowRouteMatches({
......@@ -719,6 +801,7 @@ describe('required server files', () => {
}).toString(),
},
})
)
const $ = cheerio.load(html)
const data = JSON.parse($('#props').text())
......@@ -726,7 +809,11 @@ describe('required server files', () => {
expect($('#slug').text()).toBe('first')
expect(data.hello).toBe('world')
const html2 = await renderViaHTTP(appPort, `/fallback/[slug]`, undefined, {
const html2 = await renderViaHTTP(
appPort,
`/fallback/[slug]`,
undefined,
withInvocationId({
headers: {
'x-matched-path': '/fallback/[slug]',
'x-now-route-matches': createNowRouteMatches({
......@@ -734,6 +821,7 @@ describe('required server files', () => {
}).toString(),
},
})
)
const $2 = cheerio.load(html2)
const data2 = JSON.parse($2('#props').text())
......@@ -744,7 +832,11 @@ describe('required server files', () => {
})
it('should favor valid route params over routes-matches', async () => {
const html = await renderViaHTTP(appPort, '/fallback/first', undefined, {
const html = await renderViaHTTP(
appPort,
'/fallback/first',
undefined,
withInvocationId({
headers: {
'x-matched-path': '/fallback/first',
'x-now-route-matches': createNowRouteMatches({
......@@ -752,6 +844,7 @@ describe('required server files', () => {
}).toString(),
},
})
)
const $ = cheerio.load(html)
const data = JSON.parse($('#props').text())
......@@ -759,7 +852,11 @@ describe('required server files', () => {
expect($('#slug').text()).toBe('first')
expect(data.hello).toBe('world')
const html2 = await renderViaHTTP(appPort, `/fallback/second`, undefined, {
const html2 = await renderViaHTTP(
appPort,
`/fallback/second`,
undefined,
withInvocationId({
headers: {
'x-matched-path': '/fallback/[slug]',
'x-now-route-matches': createNowRouteMatches({
......@@ -767,6 +864,7 @@ describe('required server files', () => {
}).toString(),
},
})
)
const $2 = cheerio.load(html2)
const data2 = JSON.parse($2('#props').text())
......@@ -777,17 +875,26 @@ describe('required server files', () => {
})
it('should favor valid route params over routes-matches optional', async () => {
const html = await renderViaHTTP(appPort, '/optional-ssg', undefined, {
const html = await renderViaHTTP(
appPort,
'/optional-ssg',
undefined,
withInvocationId({
headers: {
'x-matched-path': '/optional-ssg',
'x-now-route-matches': '',
},
})
)
const $ = cheerio.load(html)
const data = JSON.parse($('#props').text())
expect(data.params).toEqual({})
const html2 = await renderViaHTTP(appPort, `/optional-ssg`, undefined, {
const html2 = await renderViaHTTP(
appPort,
`/optional-ssg`,
undefined,
withInvocationId({
headers: {
'x-matched-path': '/optional-ssg',
'x-now-route-matches': createNowRouteMatches({
......@@ -795,6 +902,7 @@ describe('required server files', () => {
}).toString(),
},
})
)
const $2 = cheerio.load(html2)
const data2 = JSON.parse($2('#props').text())
......@@ -809,11 +917,11 @@ describe('required server files', () => {
slug: 'first',
}).toString()}`,
undefined,
{
withInvocationId({
headers: {
'x-matched-path': `/dynamic/[slug]`,
},
}
})
)
const { pageProps: data } = await res.json()
......@@ -825,14 +933,14 @@ describe('required server files', () => {
appPort,
`/_next/data/${next.buildId}/fallback/[slug].json`,
undefined,
{
withInvocationId({
headers: {
'x-matched-path': `/_next/data/${next.buildId}/fallback/[slug].json`,
'x-now-route-matches': createNowRouteMatches({
slug: 'second',
}).toString(),
},
}
})
)
const { pageProps: data2 } = await res2.json()
......@@ -846,12 +954,12 @@ describe('required server files', () => {
appPort,
'/catch-all/[[...rest]]',
undefined,
{
withInvocationId({
headers: {
'x-matched-path': '/catch-all/[[...rest]]',
'x-now-route-matches': '',
},
}
})
)
const $ = cheerio.load(html)
const data = JSON.parse($('#props').text())
......@@ -864,14 +972,14 @@ describe('required server files', () => {
appPort,
'/catch-all/[[...rest]]',
undefined,
{
withInvocationId({
headers: {
'x-matched-path': '/catch-all/[[...rest]]',
'x-now-route-matches': createNowRouteMatches({
rest: 'hello',
}).toString(),
},
}
})
)
const $2 = cheerio.load(html2)
const data2 = JSON.parse($2('#props').text())
......@@ -885,14 +993,14 @@ describe('required server files', () => {
appPort,
'/catch-all/[[...rest]]',
undefined,
{
withInvocationId({
headers: {
'x-matched-path': '/catch-all/[[...rest]]',
'x-now-route-matches': createNowRouteMatches({
rest: 'hello/world',
}).toString(),
},
}
})
)
const $3 = cheerio.load(html3)
const data3 = JSON.parse($3('#props').text())
......@@ -909,11 +1017,11 @@ describe('required server files', () => {
`/_next/data/${next.buildId}/catch-all.json`,
undefined,
{
withInvocationId({
headers: {
'x-matched-path': '/catch-all/[[...rest]]',
},
}
})
)
const { pageProps: data } = await res.json()
......@@ -925,14 +1033,14 @@ describe('required server files', () => {
appPort,
`/_next/data/${next.buildId}/catch-all/[[...rest]].json`,
undefined,
{
withInvocationId({
headers: {
'x-matched-path': `/_next/data/${next.buildId}/catch-all/[[...rest]].json`,
'x-now-route-matches': createNowRouteMatches({
rest: 'hello',
}).toString(),
},
}
})
)
const { pageProps: data2 } = await res2.json()
......@@ -944,14 +1052,14 @@ describe('required server files', () => {
appPort,
`/_next/data/${next.buildId}/catch-all/[[...rest]].json`,
undefined,
{
withInvocationId({
headers: {
'x-matched-path': `/_next/data/${next.buildId}/catch-all/[[...rest]].json`,
'x-now-route-matches': createNowRouteMatches({
rest: 'hello/world',
}).toString(),
},
}
})
)
const { pageProps: data3 } = await res3.json()
......@@ -970,9 +1078,14 @@ describe('required server files', () => {
'/fallback/another/',
'/fallback/another',
]) {
const res = await fetchViaHTTP(appPort, path, undefined, {
const res = await fetchViaHTTP(
appPort,
path,
undefined,
withInvocationId({
redirect: 'manual',
})
)
expect(res.status).toBe(200)
}
......@@ -985,11 +1098,11 @@ describe('required server files', () => {
{
path: 'hello/world',
},
{
withInvocationId({
headers: {
'x-matched-path': '/gssp',
},
}
})
)
const $ = cheerio.load(html)
expect(JSON.parse($('#router').text()).query).toEqual({
......@@ -1004,33 +1117,43 @@ describe('required server files', () => {
{
path: '%c0.%c0.',
},
{
withInvocationId({
headers: {
'x-matched-path': '/dynamic/[slug]',
},
}
})
)
expect(res.status).toBe(400)
expect(await res.text()).toContain('Bad Request')
})
it('should have correct resolvedUrl from rewrite', async () => {
const res = await fetchViaHTTP(appPort, '/to-dynamic/post-1', undefined, {
const res = await fetchViaHTTP(
appPort,
'/to-dynamic/post-1',
undefined,
withInvocationId({
headers: {
'x-matched-path': '/dynamic/[slug]',
},
})
)
expect(res.status).toBe(200)
const $ = cheerio.load(await res.text())
expect($('#resolved-url').text()).toBe('/dynamic/post-1')
})
it('should have correct resolvedUrl from rewrite with added query', async () => {
const res = await fetchViaHTTP(appPort, '/to-dynamic/post-2', undefined, {
const res = await fetchViaHTTP(
appPort,
'/to-dynamic/post-2',
undefined,
withInvocationId({
headers: {
'x-matched-path': '/dynamic/[slug]',
},
})
)
expect(res.status).toBe(200)
const $ = cheerio.load(await res.text())
expect($('#resolved-url').text()).toBe('/dynamic/post-2')
......@@ -1042,11 +1165,11 @@ describe('required server files', () => {
appPort,
`/_next/data/${next.buildId}/dynamic/post-2.json`,
{ slug: 'post-2' },
{
withInvocationId({
headers: {
'x-matched-path': '/dynamic/[slug]',
},
}
})
)
expect(res.status).toBe(200)
const json = await res.json()
......@@ -1054,7 +1177,12 @@ describe('required server files', () => {
})
it('should bubble error correctly for gip page', async () => {
const res = await fetchViaHTTP(appPort, '/errors/gip', { crash: '1' })
const res = await fetchViaHTTP(
appPort,
'/errors/gip',
{ crash: '1' },
withInvocationId()
)
expect(res.status).toBe(500)
expect(await res.text()).toBe('Internal Server Error')
......@@ -1064,7 +1192,12 @@ describe('required server files', () => {
})
it('should bubble error correctly for gssp page', async () => {
const res = await fetchViaHTTP(appPort, '/errors/gssp', { crash: '1' })
const res = await fetchViaHTTP(
appPort,
'/errors/gssp',
{ crash: '1' },
withInvocationId()
)
expect(res.status).toBe(500)
expect(await res.text()).toBe('Internal Server Error')
......@@ -1074,7 +1207,12 @@ describe('required server files', () => {
})
it('should bubble error correctly for gsp page', async () => {
const res = await fetchViaHTTP(appPort, '/errors/gsp/crash')
const res = await fetchViaHTTP(
appPort,
'/errors/gsp/crash',
undefined,
withInvocationId()
)
expect(res.status).toBe(500)
expect(await res.text()).toBe('Internal Server Error')
......@@ -1084,7 +1222,12 @@ describe('required server files', () => {
})
it('should bubble error correctly for API page', async () => {
const res = await fetchViaHTTP(appPort, '/api/error')
const res = await fetchViaHTTP(
appPort,
'/api/error',
undefined,
withInvocationId()
)
expect(res.status).toBe(500)
expect(await res.text()).toBe('Internal Server Error')
......@@ -1098,11 +1241,11 @@ describe('required server files', () => {
appPort,
'/optional-ssp',
{ nxtPrest: '', another: 'value' },
{
withInvocationId({
headers: {
'x-matched-path': '/optional-ssp/[[...rest]]',
},
}
})
)
const html = await res.text()
......@@ -1117,11 +1260,11 @@ describe('required server files', () => {
appPort,
'/optional-ssg',
{ nxtPrest: '', another: 'value' },
{
withInvocationId({
headers: {
'x-matched-path': '/optional-ssg/[[...rest]]',
},
}
})
)
const html = await res.text()
......@@ -1171,7 +1314,7 @@ describe('required server files', () => {
headers: {
'x-matched-path': `/_next/data/${next.buildId}/optional-ssg/[[...rest]].json`,
'x-now-route-matches': '',
'x-vercel-id': 'cle1::',
'x-invocation-id': 'cle1::',
},
},
{
......@@ -1179,7 +1322,7 @@ describe('required server files', () => {
headers: {
'x-matched-path': `/_next/data/${next.buildId}/optional-ssg/[[...rest]].json`,
'x-now-route-matches': '',
'x-vercel-id': 'cle1::',
'x-invocation-id': 'cle1::',
},
},
{
......@@ -1187,7 +1330,7 @@ describe('required server files', () => {
headers: {
'x-matched-path': `/optional-ssg/[[...rest]]`,
'x-now-route-matches': '',
'x-vercel-id': 'cle1::',
'x-invocation-id': 'cle1::',
},
},
]
......@@ -1195,6 +1338,7 @@ describe('required server files', () => {
for (const req of reqs) {
console.error('checking', req)
const res = await fetchViaHTTP(appPort, req.path, req.query, {
...withInvocationId(),
headers: req.headers,
})
......@@ -1217,12 +1361,12 @@ describe('required server files', () => {
appPort,
'/optional-ssg/[[...rest]]',
undefined,
{
withInvocationId({
headers: {
'x-matched-path': '/optional-ssg/[[...rest]]',
'x-now-route-matches': 'nxtPrest=en%2Fes%2Fhello%252Fworld',
},
}
})
)
const html = await res.text()
......@@ -1238,11 +1382,11 @@ describe('required server files', () => {
appPort,
'/api/optional',
{ nxtPrest: '', another: 'value' },
{
withInvocationId({
headers: {
'x-matched-path': '/api/optional/[[...rest]]',
},
}
})
)
const json = await res.json()
......@@ -1255,11 +1399,11 @@ describe('required server files', () => {
appPort,
'/api/optional/index',
{ nxtPrest: 'index', another: 'value' },
{
withInvocationId({
headers: {
'x-matched-path': '/api/optional/[[...rest]]',
},
}
})
)
const json = await res.json()
......@@ -1268,12 +1412,17 @@ describe('required server files', () => {
})
it('should match the index page correctly', async () => {
const res = await fetchViaHTTP(appPort, '/', undefined, {
const res = await fetchViaHTTP(
appPort,
'/',
undefined,
withInvocationId({
headers: {
'x-matched-path': '/index',
},
redirect: 'manual',
})
)
const html = await res.text()
const $ = cheerio.load(html)
......@@ -1281,12 +1430,17 @@ describe('required server files', () => {
})
it('should match the root dynamic page correctly', async () => {
const res = await fetchViaHTTP(appPort, '/slug-1', undefined, {
const res = await fetchViaHTTP(
appPort,
'/slug-1',
undefined,
withInvocationId({
headers: {
'x-matched-path': '/[slug]',
},
redirect: 'manual',
})
)
const html = await res.text()
const $ = cheerio.load(html)
......@@ -1295,12 +1449,17 @@ describe('required server files', () => {
slug: 'slug-1',
})
const res2 = await fetchViaHTTP(appPort, '/[slug]', undefined, {
const res2 = await fetchViaHTTP(
appPort,
'/[slug]',
undefined,
withInvocationId({
headers: {
'x-matched-path': '/[slug]',
},
redirect: 'manual',
})
)
const html2 = await res2.text()
const $2 = cheerio.load(html2)
......@@ -1311,12 +1470,17 @@ describe('required server files', () => {
})
it('should have correct asPath on dynamic SSG page correctly', async () => {
const res = await fetchViaHTTP(appPort, '/an-ssg-path', undefined, {
const res = await fetchViaHTTP(
appPort,
'/an-ssg-path',
undefined,
withInvocationId({
headers: {
'x-matched-path': '/[slug]',
},
redirect: 'manual',
})
)
const html = await res.text()
const $ = cheerio.load(html)
......@@ -1337,12 +1501,17 @@ describe('required server files', () => {
]
for (const check of toCheck) {
console.warn('checking', check)
const res = await fetchViaHTTP(appPort, check.pathname, undefined, {
const res = await fetchViaHTTP(
appPort,
check.pathname,
undefined,
withInvocationId({
headers: {
'x-matched-path': check.matchedPath,
},
redirect: 'manual',
})
)
const html = await res.text()
const $ = cheerio.load(html)
......@@ -1354,7 +1523,12 @@ describe('required server files', () => {
})
it('should read .env files and process.env', async () => {
const res = await fetchViaHTTP(appPort, '/api/env')
const res = await fetchViaHTTP(
appPort,
'/api/env',
undefined,
withInvocationId()
)
const envVariables = await res.json()
......@@ -1371,7 +1545,12 @@ describe('required server files', () => {
it('should run middleware correctly', async () => {
const standaloneDir = join(next.testDir, 'standalone')
const res = await fetchViaHTTP(appPort, '/')
const res = await fetchViaHTTP(
appPort,
'/',
undefined,
withInvocationId()
)
expect(res.status).toBe(200)
expect(await res.text()).toContain('index page')
......@@ -1389,7 +1568,9 @@ describe('required server files', () => {
const resImageResponse = await fetchViaHTTP(
appPort,
'/a-non-existent-page/to-test-with-middleware'
'/a-non-existent-page/to-test-with-middleware',
undefined,
withInvocationId()
)
expect(resImageResponse.status).toBe(200)
......@@ -1402,11 +1583,11 @@ describe('required server files', () => {
appPort,
`/_next/data/${nanoid()}/index.json`,
undefined,
{
withInvocationId({
headers: {
'x-matched-path': '/[teamSlug]/[project]/[id]/[suffix]',
},
}
})
)
expect(res.status).toBe(404)
......
......@@ -95,7 +95,7 @@ describe('minimal-mode-response-cache', () => {
vary: 'rsc, next-router-state-tree, next-router-prefetch',
'x-now-route-matches': '1=compare&rsc=1',
'x-matched-path': '/app-blog/compare.rsc',
'x-vercel-id': '1',
'x-invocation-id': '1',
rsc: '1',
}
const res1 = await fetchViaHTTP(
......@@ -125,7 +125,7 @@ describe('minimal-mode-response-cache', () => {
vary: 'rsc, next-router-state-tree, next-router-prefetch',
'x-now-route-matches': '1=app-another&rsc=1',
'x-matched-path': '/app-another.rsc',
'x-vercel-id': '1',
'x-invocation-id': '1',
rsc: '1',
}
const res1 = await fetchViaHTTP(appPort, '/app-another.rsc', undefined, {
......
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