feat: always emit postpone header when PPR is enabled to assist with debugging

parent 8ae1167c
......@@ -111,7 +111,7 @@ export async function fetchServerResponse(
const canonicalUrl = res.redirected ? responseUrl : undefined
const contentType = res.headers.get('content-type') || ''
const postponed = !!res.headers.get(NEXT_DID_POSTPONE_HEADER)
const postponed = res.headers.get(NEXT_DID_POSTPONE_HEADER) === '1'
let isFlightResponse = contentType === RSC_CONTENT_TYPE_HEADER
if (process.env.NODE_ENV === 'production') {
......
......@@ -35,6 +35,7 @@ import {
import { canSegmentBeOverridden } from '../../client/components/match-segments'
import { stripInternalQueries } from '../internal-utils'
import {
NEXT_DID_POSTPONE_HEADER,
NEXT_ROUTER_PREFETCH_HEADER,
NEXT_ROUTER_STATE_TREE,
RSC_HEADER,
......@@ -79,6 +80,7 @@ import { MissingPostponeDataError } from './is-missing-postpone-error'
import { DetachedPromise } from '../../lib/detached-promise'
import { DYNAMIC_ERROR_CODE } from '../../client/components/hooks-server-context'
import { useFlightResponse } from './use-flight-response'
import { createStaticHeadersAdapter } from './static/create-static-headers-adapter'
export type GetDynamicParamFromSegment = (
// [slug] / [[slug]] / [...slug]
......@@ -606,6 +608,14 @@ async function renderToHTMLOrFlightImpl(
const silenceStaticGenerationErrors =
renderOpts.experimental.ppr && isStaticGeneration
// If this is during static generation, we shouldn't write to the headers
// object directly, instead we should add to the render result. This ensures
// that the headers are correctly written to the metadata or the response
// depending on whether this is a static generation or not.
const headers = isStaticGeneration
? createStaticHeadersAdapter(metadata)
: res
const serverComponentsErrorHandler = createErrorHandler({
_source: 'serverComponentsRenderer',
dev,
......@@ -909,22 +919,18 @@ async function renderToHTMLOrFlightImpl(
: null,
streamOptions: {
onError: htmlRendererErrorHandler,
onHeaders: (headers: Headers) => {
onHeaders: (incoming: Headers) => {
// If this is during static generation, we shouldn't write to the
// headers object directly, instead we should add to the render
// result.
if (isStaticGeneration) {
headers.forEach((value, key) => {
metadata.headers ??= {}
metadata.headers[key] = value
})
incoming.forEach((value, key) => {
headers.appendHeader(key, value)
})
// Resolve the promise to continue the stream.
// Resolve the promise to continue the stream if we're in static
// generation. Otherwise the promise is not awaited.
if (isStaticGeneration) {
onHeadersFinished.resolve()
} else {
headers.forEach((value, key) => {
res.appendHeader(key, value)
})
}
},
maxHeadersLength: 600,
......@@ -937,6 +943,12 @@ async function renderToHTMLOrFlightImpl(
try {
let { stream, postponed } = await renderer.render(children)
// If PPR is enabled and this is a static render, we should add the
// postpone header to the response.
if (renderOpts.experimental.ppr && isStaticGeneration) {
headers.setHeader(NEXT_DID_POSTPONE_HEADER, postponed ? '1' : '0')
}
// If the stream was postponed, we need to add the result to the
// metadata so that it can be resumed later.
if (postponed) {
......@@ -1003,12 +1015,12 @@ async function renderToHTMLOrFlightImpl(
hasRedirectError = true
res.statusCode = getRedirectStatusCodeFromError(err)
if (err.mutableCookies) {
const headers = new Headers()
const cookieHeaders = new Headers()
// If there were mutable cookies set, we need to set them on the
// response.
if (appendMutableCookies(headers, err.mutableCookies)) {
res.setHeader('set-cookie', Array.from(headers.values()))
if (appendMutableCookies(cookieHeaders, err.mutableCookies)) {
res.setHeader('set-cookie', Array.from(cookieHeaders.values()))
}
}
const redirectUrl = addPathPrefix(
......
import type { OutgoingHttpHeader } from 'http'
import type { AppPageRenderResultMetadata } from '../../render-result'
/**
* This adapter is used to set headers in the `AppPageRenderResultMetadata`
* object.
*/
export type StaticHeadersAdapter = {
appendHeader: (name: string, value: string) => void
setHeader: (name: string, value: OutgoingHttpHeader) => void
}
/**
* Creates a static headers adapter that can be used to set headers in the
* `AppPageRenderResultMetadata` object.
*/
export const createStaticHeadersAdapter = (
metadata: AppPageRenderResultMetadata
): StaticHeadersAdapter => ({
appendHeader: (name, value) => {
metadata.headers ??= {}
const existing = metadata.headers[name]
if (Array.isArray(existing)) {
metadata.headers[name] = [...existing, value]
} else if (typeof existing === 'string') {
metadata.headers[name] = [existing, value]
} else if (typeof existing === 'number') {
metadata.headers[name] = [existing.toString(), value]
} else {
metadata.headers[name] = value
}
},
setHeader: (name, value) => {
metadata.headers ??= {}
metadata.headers[name] = value
},
})
......@@ -83,7 +83,6 @@ import {
RSC_VARY_HEADER,
NEXT_RSC_UNION_QUERY,
NEXT_ROUTER_PREFETCH_HEADER,
NEXT_DID_POSTPONE_HEADER,
} from '../client/components/app-router-headers'
import type {
MatchOptions,
......@@ -101,10 +100,7 @@ import { BaseServerSpan } from './lib/trace/constants'
import { I18NProvider } from './future/helpers/i18n-provider'
import { sendResponse } from './send-response'
import { handleInternalServerErrorResponse } from './future/route-modules/helpers/response-handlers'
import {
fromNodeOutgoingHttpHeaders,
toNodeOutgoingHttpHeaders,
} from './web/utils'
import { toNodeOutgoingHttpHeaders } from './web/utils'
import {
CACHE_ONE_YEAR,
NEXT_CACHE_TAGS_HEADER,
......@@ -2695,6 +2691,36 @@ export default abstract class Server<ServerOptions extends Options = Options> {
cacheEntry.revalidate = revalidate
// If the cache entry produced headers, we should append them to the
// response.
if (
cacheEntry.value &&
'headers' in cacheEntry.value &&
cacheEntry.value.headers
) {
for (const [key, value] of Object.entries(cacheEntry.value.headers)) {
// If the value is undefined, then we can't append it.
if (typeof value === 'undefined') {
continue
}
// We should only send the cache tags header when we're in minimal
// mode and this is a SSG request.
if (key === NEXT_CACHE_TAGS_HEADER && (!this.minimalMode || !isSSG)) {
continue
}
// Otherwise, we should append the header.
if (Array.isArray(value)) {
value.forEach((v) => res.appendHeader(key, v))
} else if (typeof value === 'number') {
res.appendHeader(key, value.toString())
} else {
res.appendHeader(key, value)
}
}
}
// If there's a callback for `onCacheEntry`, call it with the cache entry
// and the revalidate options.
const onCacheEntry = getRequestMeta(req, 'onCacheEntry')
......@@ -2743,17 +2769,10 @@ export default abstract class Server<ServerOptions extends Options = Options> {
return null
}
} else if (cachedData.kind === 'ROUTE') {
const headers = { ...cachedData.headers }
if (!(this.minimalMode && isSSG)) {
delete headers[NEXT_CACHE_TAGS_HEADER]
}
await sendResponse(
req,
res,
new Response(cachedData.body, {
headers: fromNodeOutgoingHttpHeaders(headers),
status: cachedData.status || 200,
})
)
......@@ -2767,49 +2786,10 @@ export default abstract class Server<ServerOptions extends Options = Options> {
)
}
if (cachedData.headers) {
const headers = { ...cachedData.headers }
if (!this.minimalMode || !isSSG) {
delete headers[NEXT_CACHE_TAGS_HEADER]
}
for (let [key, value] of Object.entries(headers)) {
if (typeof value === 'undefined') continue
if (Array.isArray(value)) {
for (const v of value) {
res.appendHeader(key, v)
}
} else if (typeof value === 'number') {
value = value.toString()
res.appendHeader(key, value)
} else {
res.appendHeader(key, value)
}
}
}
if (
this.minimalMode &&
isSSG &&
cachedData.headers?.[NEXT_CACHE_TAGS_HEADER]
) {
res.setHeader(
NEXT_CACHE_TAGS_HEADER,
cachedData.headers[NEXT_CACHE_TAGS_HEADER] as string
)
}
if (cachedData.status) {
res.statusCode = cachedData.status
}
// Mark that the request did postpone if this is a data request.
if (cachedData.postponed && isRSCRequest) {
res.setHeader(NEXT_DID_POSTPONE_HEADER, '1')
}
if (isDataReq) {
// If this is a dynamic RSC request, then stream the response.
if (isDynamicRSCRequest) {
......
......@@ -160,6 +160,12 @@ createNextDescribe(
} else {
expect(res.headers.get('x-nextjs-cache')).toEqual(null)
}
if (dynamic === true || dynamic === 'force-dynamic') {
expect(res.headers.get('x-nextjs-postponed')).toEqual('1')
} else {
expect(res.headers.get('x-nextjs-postponed')).toEqual('0')
}
})
if (dynamic === true) {
......@@ -258,46 +264,59 @@ createNextDescribe(
if (!isNextDev) {
describe('Prefetch RSC Response', () => {
describe.each(pages)('for $pathname', ({ pathname, revalidate }) => {
it('should have correct headers', async () => {
const res = await next.fetch(pathname, {
headers: { RSC: '1', 'Next-Router-Prefetch': '1' },
})
expect(res.status).toEqual(200)
expect(res.headers.get('content-type')).toEqual('text/x-component')
// cache header handling is different when in minimal mode
const cache = res.headers.get('cache-control')
if (isNextDeploy) {
expect(cache).toEqual('public, max-age=0, must-revalidate')
} else {
expect(cache).toEqual(
`s-maxage=${revalidate || '31536000'}, stale-while-revalidate`
describe.each(pages)(
'for $pathname',
({ pathname, dynamic, revalidate }) => {
it('should have correct headers', async () => {
const res = await next.fetch(pathname, {
headers: { RSC: '1', 'Next-Router-Prefetch': '1' },
})
expect(res.status).toEqual(200)
expect(res.headers.get('content-type')).toEqual(
'text/x-component'
)
}
if (!isNextDeploy) {
expect(res.headers.get('x-nextjs-cache')).toEqual('HIT')
} else {
expect(res.headers.get('x-nextjs-cache')).toEqual(null)
}
})
// cache header handling is different when in minimal mode
const cache = res.headers.get('cache-control')
if (isNextDeploy) {
expect(cache).toEqual('public, max-age=0, must-revalidate')
} else {
expect(cache).toEqual(
`s-maxage=${revalidate || '31536000'}, stale-while-revalidate`
)
}
it('should not contain dynamic content', async () => {
const unexpected = `${Date.now()}:${Math.random()}`
const res = await next.fetch(pathname, {
headers: {
RSC: '1',
'Next-Router-Prefetch': '1',
'X-Test-Input': unexpected,
},
if (!isNextDeploy) {
expect(res.headers.get('x-nextjs-cache')).toEqual('HIT')
} else {
expect(res.headers.get('x-nextjs-cache')).toEqual(null)
}
if (dynamic === true || dynamic === 'force-dynamic') {
expect(res.headers.get('x-nextjs-postponed')).toEqual('1')
} else {
expect(res.headers.get('x-nextjs-postponed')).toEqual('0')
}
})
expect(res.status).toEqual(200)
expect(res.headers.get('content-type')).toEqual('text/x-component')
const text = await res.text()
expect(text).not.toContain(unexpected)
})
})
it('should not contain dynamic content', async () => {
const unexpected = `${Date.now()}:${Math.random()}`
const res = await next.fetch(pathname, {
headers: {
RSC: '1',
'Next-Router-Prefetch': '1',
'X-Test-Input': unexpected,
},
})
expect(res.status).toEqual(200)
expect(res.headers.get('content-type')).toEqual(
'text/x-component'
)
const text = await res.text()
expect(text).not.toContain(unexpected)
})
}
)
})
describe('Dynamic RSC Response', () => {
......
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