File size: 44,584 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 |
import type { LoaderTree } from '../../server/lib/app-dir-module'
import type { IncomingMessage, ServerResponse } from 'node:http'
import {
AppPageRouteModule,
type AppPageRouteHandlerContext,
} from '../../server/route-modules/app-page/module.compiled' with { 'turbopack-transition': 'next-ssr' }
import { RouteKind } from '../../server/route-kind' with { 'turbopack-transition': 'next-server-utility' }
import { getRevalidateReason } from '../../server/instrumentation/utils'
import { getTracer, SpanKind, type Span } from '../../server/lib/trace/tracer'
import { getRequestMeta } from '../../server/request-meta'
import { BaseServerSpan } from '../../server/lib/trace/constants'
import { interopDefault } from '../../server/app-render/interop-default'
import { stripFlightHeaders } from '../../server/app-render/strip-flight-headers'
import { NodeNextRequest, NodeNextResponse } from '../../server/base-http/node'
import { checkIsAppPPREnabled } from '../../server/lib/experimental/ppr'
import {
getFallbackRouteParams,
type FallbackRouteParams,
} from '../../server/request/fallback-params'
import { setReferenceManifestsSingleton } from '../../server/app-render/encryption-utils'
import {
isHtmlBotRequest,
shouldServeStreamingMetadata,
} from '../../server/lib/streaming-metadata'
import { createServerModuleMap } from '../../server/app-render/action-utils'
import { normalizeAppPath } from '../../shared/lib/router/utils/app-paths'
import { getIsPossibleServerAction } from '../../server/lib/server-action-request-meta'
import {
RSC_HEADER,
NEXT_ROUTER_PREFETCH_HEADER,
NEXT_IS_PRERENDER_HEADER,
NEXT_DID_POSTPONE_HEADER,
RSC_CONTENT_TYPE_HEADER,
} from '../../client/components/app-router-headers'
import { getBotType, isBot } from '../../shared/lib/router/utils/is-bot'
import {
CachedRouteKind,
type CachedAppPageValue,
type CachedPageValue,
type ResponseCacheEntry,
type ResponseGenerator,
} from '../../server/response-cache'
import { FallbackMode, parseFallbackField } from '../../lib/fallback'
import RenderResult from '../../server/render-result'
import {
CACHE_ONE_YEAR,
HTML_CONTENT_TYPE_HEADER,
NEXT_CACHE_TAGS_HEADER,
} from '../../lib/constants'
import type { CacheControl } from '../../server/lib/cache-control'
import { ENCODED_TAGS } from '../../server/stream-utils/encoded-tags'
import { sendRenderResult } from '../../server/send-payload'
import { NoFallbackError } from '../../shared/lib/no-fallback-error.external'
// These are injected by the loader afterwards.
/**
* The tree created in next-app-loader that holds component segments and modules
* and I've updated it.
*/
declare const tree: LoaderTree
declare const pages: any
// We inject the tree and pages here so that we can use them in the route
// module.
// INJECT:tree
// INJECT:pages
export { tree, pages }
import GlobalError from 'VAR_MODULE_GLOBAL_ERROR' with { 'turbopack-transition': 'next-server-utility' }
export { GlobalError }
// These are injected by the loader afterwards.
declare const __next_app_require__: (id: string | number) => unknown
declare const __next_app_load_chunk__: (id: string | number) => Promise<unknown>
// INJECT:__next_app_require__
// INJECT:__next_app_load_chunk__
export const __next_app__ = {
require: __next_app_require__,
loadChunk: __next_app_load_chunk__,
}
import * as entryBase from '../../server/app-render/entry-base' with { 'turbopack-transition': 'next-server-utility' }
import { RedirectStatusCode } from '../../client/components/redirect-status-code'
export * from '../../server/app-render/entry-base' with { 'turbopack-transition': 'next-server-utility' }
// Create and export the route module that will be consumed.
export const routeModule = new AppPageRouteModule({
definition: {
kind: RouteKind.APP_PAGE,
page: 'VAR_DEFINITION_PAGE',
pathname: 'VAR_DEFINITION_PATHNAME',
// The following aren't used in production.
bundlePath: '',
filename: '',
appPaths: [],
},
userland: {
loaderTree: tree,
},
distDir: process.env.__NEXT_RELATIVE_DIST_DIR || '',
relativeProjectDir: process.env.__NEXT_RELATIVE_PROJECT_DIR || '',
})
export async function handler(
req: IncomingMessage,
res: ServerResponse,
ctx: {
waitUntil: (prom: Promise<void>) => void
}
) {
let srcPage = 'VAR_DEFINITION_PAGE'
// turbopack doesn't normalize `/index` in the page name
// so we need to to process dynamic routes properly
// TODO: fix turbopack providing differing value from webpack
if (process.env.TURBOPACK) {
srcPage = srcPage.replace(/\/index$/, '') || '/'
} else if (srcPage === '/index') {
// we always normalize /index specifically
srcPage = '/'
}
const multiZoneDraftMode = process.env
.__NEXT_MULTI_ZONE_DRAFT_MODE as any as boolean
const initialPostponed = getRequestMeta(req, 'postponed')
// TODO: replace with more specific flags
const minimalMode = getRequestMeta(req, 'minimalMode')
const prepareResult = await routeModule.prepare(req, res, {
srcPage,
multiZoneDraftMode,
})
if (!prepareResult) {
res.statusCode = 400
res.end('Bad Request')
ctx.waitUntil?.(Promise.resolve())
return null
}
const {
buildId,
query,
params,
parsedUrl,
pageIsDynamic,
buildManifest,
nextFontManifest,
reactLoadableManifest,
serverActionsManifest,
clientReferenceManifest,
subresourceIntegrityManifest,
prerenderManifest,
isDraftMode,
resolvedPathname,
revalidateOnlyGenerated,
routerServerContext,
nextConfig,
interceptionRoutePatterns,
} = prepareResult
const pathname = parsedUrl.pathname || '/'
const normalizedSrcPage = normalizeAppPath(srcPage)
let { isOnDemandRevalidate } = prepareResult
const prerenderInfo = routeModule.match(pathname, prerenderManifest)
const isPrerendered = !!prerenderManifest.routes[resolvedPathname]
let isSSG = Boolean(
prerenderInfo ||
isPrerendered ||
prerenderManifest.routes[normalizedSrcPage]
)
const userAgent = req.headers['user-agent'] || ''
const botType = getBotType(userAgent)
const isHtmlBot = isHtmlBotRequest(req)
/**
* If true, this indicates that the request being made is for an app
* prefetch request.
*/
const isPrefetchRSCRequest =
getRequestMeta(req, 'isPrefetchRSCRequest') ??
Boolean(req.headers[NEXT_ROUTER_PREFETCH_HEADER])
// NOTE: Don't delete headers[RSC] yet, it still needs to be used in renderToHTML later
const isRSCRequest =
getRequestMeta(req, 'isRSCRequest') ?? Boolean(req.headers[RSC_HEADER])
const isPossibleServerAction = getIsPossibleServerAction(req)
/**
* If the route being rendered is an app page, and the ppr feature has been
* enabled, then the given route _could_ support PPR.
*/
const couldSupportPPR: boolean = checkIsAppPPREnabled(
nextConfig.experimental.ppr
)
// When enabled, this will allow the use of the `?__nextppronly` query to
// enable debugging of the static shell.
const hasDebugStaticShellQuery =
process.env.__NEXT_EXPERIMENTAL_STATIC_SHELL_DEBUGGING === '1' &&
typeof query.__nextppronly !== 'undefined' &&
couldSupportPPR
// When enabled, this will allow the use of the `?__nextppronly` query
// to enable debugging of the fallback shell.
const hasDebugFallbackShellQuery =
hasDebugStaticShellQuery && query.__nextppronly === 'fallback'
// This page supports PPR if it is marked as being `PARTIALLY_STATIC` in the
// prerender manifest and this is an app page.
const isRoutePPREnabled: boolean =
couldSupportPPR &&
((
prerenderManifest.routes[normalizedSrcPage] ??
prerenderManifest.dynamicRoutes[normalizedSrcPage]
)?.renderingMode === 'PARTIALLY_STATIC' ||
// Ideally we'd want to check the appConfig to see if this page has PPR
// enabled or not, but that would require plumbing the appConfig through
// to the server during development. We assume that the page supports it
// but only during development.
(hasDebugStaticShellQuery &&
(routeModule.isDev === true ||
routerServerContext?.experimentalTestProxy === true)))
const isDebugStaticShell: boolean =
hasDebugStaticShellQuery && isRoutePPREnabled
// We should enable debugging dynamic accesses when the static shell
// debugging has been enabled and we're also in development mode.
const isDebugDynamicAccesses =
isDebugStaticShell && routeModule.isDev === true
const isDebugFallbackShell = hasDebugFallbackShellQuery && isRoutePPREnabled
// If we're in minimal mode, then try to get the postponed information from
// the request metadata. If available, use it for resuming the postponed
// render.
const minimalPostponed = isRoutePPREnabled ? initialPostponed : undefined
// If PPR is enabled, and this is a RSC request (but not a prefetch), then
// we can use this fact to only generate the flight data for the request
// because we can't cache the HTML (as it's also dynamic).
const isDynamicRSCRequest =
isRoutePPREnabled && isRSCRequest && !isPrefetchRSCRequest
// Need to read this before it's stripped by stripFlightHeaders. We don't
// need to transfer it to the request meta because it's only read
// within this function; the static segment data should have already been
// generated, so we will always either return a static response or a 404.
const segmentPrefetchHeader = getRequestMeta(req, 'segmentPrefetchRSCRequest')
// TODO: investigate existing bug with shouldServeStreamingMetadata always
// being true for a revalidate due to modifying the base-server this.renderOpts
// when fixing this to correct logic it causes hydration issue since we set
// serveStreamingMetadata to true during export
let serveStreamingMetadata = !userAgent
? true
: shouldServeStreamingMetadata(userAgent, nextConfig.htmlLimitedBots)
if (isHtmlBot && isRoutePPREnabled) {
isSSG = false
serveStreamingMetadata = false
}
// In development, we always want to generate dynamic HTML.
let supportsDynamicResponse: boolean =
// If we're in development, we always support dynamic HTML, unless it's
// a data request, in which case we only produce static HTML.
routeModule.isDev === true ||
// If this is not SSG or does not have static paths, then it supports
// dynamic HTML.
!isSSG ||
// If this request has provided postponed data, it supports dynamic
// HTML.
typeof initialPostponed === 'string' ||
// If this is a dynamic RSC request, then this render supports dynamic
// HTML (it's dynamic).
isDynamicRSCRequest
// When html bots request PPR page, perform the full dynamic rendering.
const shouldWaitOnAllReady = isHtmlBot && isRoutePPREnabled
let ssgCacheKey: string | null = null
if (
!isDraftMode &&
isSSG &&
!supportsDynamicResponse &&
!isPossibleServerAction &&
!minimalPostponed &&
!isDynamicRSCRequest
) {
ssgCacheKey = resolvedPathname
}
// the staticPathKey differs from ssgCacheKey since
// ssgCacheKey is null in dev since we're always in "dynamic"
// mode in dev to bypass the cache, but we still need to honor
// dynamicParams = false in dev mode
let staticPathKey = ssgCacheKey
if (!staticPathKey && routeModule.isDev) {
staticPathKey = resolvedPathname
}
// If this is a request for an app path that should be statically generated
// and we aren't in the edge runtime, strip the flight headers so it will
// generate the static response.
if (
!routeModule.isDev &&
!isDraftMode &&
isSSG &&
isRSCRequest &&
!isDynamicRSCRequest
) {
stripFlightHeaders(req.headers)
}
const ComponentMod = {
...entryBase,
tree,
pages,
GlobalError,
handler,
routeModule,
__next_app__,
}
// Before rendering (which initializes component tree modules), we have to
// set the reference manifests to our global store so Server Action's
// encryption util can access to them at the top level of the page module.
if (serverActionsManifest && clientReferenceManifest) {
setReferenceManifestsSingleton({
page: srcPage,
clientReferenceManifest,
serverActionsManifest,
serverModuleMap: createServerModuleMap({
serverActionsManifest,
}),
})
}
const method = req.method || 'GET'
const tracer = getTracer()
const activeSpan = tracer.getActiveScopeSpan()
try {
const varyHeader = routeModule.getVaryHeader(
resolvedPathname,
interceptionRoutePatterns
)
res.setHeader('Vary', varyHeader)
const invokeRouteModule = async (
span: Span | undefined,
context: AppPageRouteHandlerContext
) => {
const nextReq = new NodeNextRequest(req)
const nextRes = new NodeNextResponse(res)
// TODO: adapt for putting the RDC inside the postponed data
// If we're in dev, and this isn't a prefetch or a server action,
// we should seed the resume data cache.
if (process.env.NODE_ENV === 'development') {
if (
nextConfig.experimental.cacheComponents &&
!isPrefetchRSCRequest &&
!context.renderOpts.isPossibleServerAction
) {
const warmup = await routeModule.warmup(nextReq, nextRes, context)
// If the warmup is successful, we should use the resume data
// cache from the warmup.
if (warmup.metadata.renderResumeDataCache) {
context.renderOpts.renderResumeDataCache =
warmup.metadata.renderResumeDataCache
}
}
}
return routeModule.render(nextReq, nextRes, context).finally(() => {
if (!span) return
span.setAttributes({
'http.status_code': res.statusCode,
'next.rsc': false,
})
const rootSpanAttributes = tracer.getRootSpanAttributes()
// We were unable to get attributes, probably OTEL is not enabled
if (!rootSpanAttributes) {
return
}
if (
rootSpanAttributes.get('next.span_type') !==
BaseServerSpan.handleRequest
) {
console.warn(
`Unexpected root span type '${rootSpanAttributes.get(
'next.span_type'
)}'. Please report this Next.js issue https://github.com/vercel/next.js`
)
return
}
const route = rootSpanAttributes.get('next.route')
if (route) {
const name = `${method} ${route}`
span.setAttributes({
'next.route': route,
'http.route': route,
'next.span_name': name,
})
span.updateName(name)
} else {
span.updateName(`${method} ${req.url}`)
}
})
}
const doRender = async ({
span,
postponed,
fallbackRouteParams,
}: {
span?: Span
/**
* The postponed data for this render. This is only provided when resuming
* a render that has been postponed.
*/
postponed: string | undefined
/**
* The unknown route params for this render.
*/
fallbackRouteParams: FallbackRouteParams | null
}): Promise<ResponseCacheEntry> => {
const context: AppPageRouteHandlerContext = {
query,
params,
page: normalizedSrcPage,
sharedContext: {
buildId,
},
serverComponentsHmrCache: getRequestMeta(
req,
'serverComponentsHmrCache'
),
fallbackRouteParams,
renderOpts: {
App: () => null,
Document: () => null,
pageConfig: {},
ComponentMod,
Component: interopDefault(ComponentMod),
params,
routeModule,
page: srcPage,
postponed,
shouldWaitOnAllReady,
serveStreamingMetadata,
supportsDynamicResponse:
typeof postponed === 'string' || supportsDynamicResponse,
buildManifest,
nextFontManifest,
reactLoadableManifest,
subresourceIntegrityManifest,
serverActionsManifest,
clientReferenceManifest,
setIsrStatus: routerServerContext?.setIsrStatus,
dir:
process.env.NEXT_RUNTIME === 'nodejs'
? (require('path') as typeof import('path')).join(
/* turbopackIgnore: true */
process.cwd(),
routeModule.relativeProjectDir
)
: `${process.cwd()}/${routeModule.relativeProjectDir}`,
isDraftMode,
isRevalidate: isSSG && !postponed && !isDynamicRSCRequest,
botType,
isOnDemandRevalidate,
isPossibleServerAction,
assetPrefix: nextConfig.assetPrefix,
nextConfigOutput: nextConfig.output,
crossOrigin: nextConfig.crossOrigin,
trailingSlash: nextConfig.trailingSlash,
previewProps: prerenderManifest.preview,
deploymentId: nextConfig.deploymentId,
enableTainting: nextConfig.experimental.taint,
htmlLimitedBots: nextConfig.htmlLimitedBots,
devtoolSegmentExplorer:
nextConfig.experimental.devtoolSegmentExplorer,
reactMaxHeadersLength: nextConfig.reactMaxHeadersLength,
multiZoneDraftMode,
incrementalCache: getRequestMeta(req, 'incrementalCache'),
cacheLifeProfiles: nextConfig.experimental.cacheLife,
basePath: nextConfig.basePath,
serverActions: nextConfig.experimental.serverActions,
...(isDebugStaticShell || isDebugDynamicAccesses
? {
nextExport: true,
supportsDynamicResponse: false,
isStaticGeneration: true,
isRevalidate: true,
isDebugDynamicAccesses: isDebugDynamicAccesses,
}
: {}),
experimental: {
isRoutePPREnabled,
expireTime: nextConfig.expireTime,
staleTimes: nextConfig.experimental.staleTimes,
cacheComponents: Boolean(nextConfig.experimental.cacheComponents),
clientSegmentCache: Boolean(
nextConfig.experimental.clientSegmentCache
),
dynamicOnHover: Boolean(nextConfig.experimental.dynamicOnHover),
inlineCss: Boolean(nextConfig.experimental.inlineCss),
authInterrupts: Boolean(nextConfig.experimental.authInterrupts),
clientTraceMetadata:
nextConfig.experimental.clientTraceMetadata || ([] as any),
},
waitUntil: ctx.waitUntil,
onClose: (cb) => {
res.on('close', cb)
},
onAfterTaskError: () => {},
onInstrumentationRequestError: (error, _request, errorContext) =>
routeModule.onRequestError(
req,
error,
errorContext,
routerServerContext
),
err: getRequestMeta(req, 'invokeError'),
dev: routeModule.isDev,
},
}
const result = await invokeRouteModule(span, context)
const { metadata } = result
const {
cacheControl,
headers = {},
// Add any fetch tags that were on the page to the response headers.
fetchTags: cacheTags,
} = metadata
if (cacheTags) {
headers[NEXT_CACHE_TAGS_HEADER] = cacheTags
}
// Pull any fetch metrics from the render onto the request.
;(req as any).fetchMetrics = metadata.fetchMetrics
// we don't throw static to dynamic errors in dev as isSSG
// is a best guess in dev since we don't have the prerender pass
// to know whether the path is actually static or not
if (
isSSG &&
cacheControl?.revalidate === 0 &&
!routeModule.isDev &&
!isRoutePPREnabled
) {
const staticBailoutInfo = metadata.staticBailoutInfo
const err = new Error(
`Page changed from static to dynamic at runtime ${resolvedPathname}${
staticBailoutInfo?.description
? `, reason: ${staticBailoutInfo.description}`
: ``
}` +
`\nsee more here https://nextjs.org/docs/messages/app-static-to-dynamic-error`
)
if (staticBailoutInfo?.stack) {
const stack = staticBailoutInfo.stack
err.stack = err.message + stack.substring(stack.indexOf('\n'))
}
throw err
}
return {
value: {
kind: CachedRouteKind.APP_PAGE,
html: result,
headers,
rscData: metadata.flightData,
postponed: metadata.postponed,
status: metadata.statusCode,
segmentData: metadata.segmentData,
} satisfies CachedAppPageValue,
cacheControl,
} satisfies ResponseCacheEntry
}
const responseGenerator: ResponseGenerator = async ({
hasResolved,
previousCacheEntry,
isRevalidating,
span,
}) => {
const isProduction = routeModule.isDev === false
const didRespond = hasResolved || res.writableEnded
// skip on-demand revalidate if cache is not present and
// revalidate-if-generated is set
if (
isOnDemandRevalidate &&
revalidateOnlyGenerated &&
!previousCacheEntry &&
!minimalMode
) {
if (routerServerContext?.render404) {
await routerServerContext.render404(req, res)
} else {
res.statusCode = 404
res.end('This page could not be found')
}
return null
}
let fallbackMode: FallbackMode | undefined
if (prerenderInfo) {
fallbackMode = parseFallbackField(prerenderInfo.fallback)
}
// When serving a bot request, we want to serve a blocking render and not
// the prerendered page. This ensures that the correct content is served
// to the bot in the head.
if (fallbackMode === FallbackMode.PRERENDER && isBot(userAgent)) {
fallbackMode = FallbackMode.BLOCKING_STATIC_RENDER
}
if (previousCacheEntry?.isStale === -1) {
isOnDemandRevalidate = true
}
// TODO: adapt for PPR
// only allow on-demand revalidate for fallback: true/blocking
// or for prerendered fallback: false paths
if (
isOnDemandRevalidate &&
(fallbackMode !== FallbackMode.NOT_FOUND || previousCacheEntry)
) {
fallbackMode = FallbackMode.BLOCKING_STATIC_RENDER
}
if (
!minimalMode &&
fallbackMode !== FallbackMode.BLOCKING_STATIC_RENDER &&
staticPathKey &&
!didRespond &&
!isDraftMode &&
pageIsDynamic &&
(isProduction || !isPrerendered)
) {
// if the page has dynamicParams: false and this pathname wasn't
// prerendered trigger the no fallback handling
if (
// In development, fall through to render to handle missing
// getStaticPaths.
(isProduction || prerenderInfo) &&
// When fallback isn't present, abort this render so we 404
fallbackMode === FallbackMode.NOT_FOUND
) {
throw new NoFallbackError()
}
let fallbackResponse: ResponseCacheEntry | null | undefined
if (isRoutePPREnabled && !isRSCRequest) {
const cacheKey =
typeof prerenderInfo?.fallback === 'string'
? prerenderInfo.fallback
: isProduction
? normalizedSrcPage
: null
// We use the response cache here to handle the revalidation and
// management of the fallback shell.
fallbackResponse = await routeModule.handleResponse({
cacheKey,
req,
nextConfig,
routeKind: RouteKind.APP_PAGE,
isFallback: true,
prerenderManifest,
isRoutePPREnabled,
responseGenerator: async () =>
doRender({
span,
// We pass `undefined` as rendering a fallback isn't resumed
// here.
postponed: undefined,
fallbackRouteParams:
// If we're in production or we're debugging the fallback
// shell then we should postpone when dynamic params are
// accessed.
isProduction || isDebugFallbackShell
? getFallbackRouteParams(normalizedSrcPage)
: null,
}),
waitUntil: ctx.waitUntil,
})
// If the fallback response was set to null, then we should return null.
if (fallbackResponse === null) return null
// Otherwise, if we did get a fallback response, we should return it.
if (fallbackResponse) {
// Remove the cache control from the response to prevent it from being
// used in the surrounding cache.
delete fallbackResponse.cacheControl
return fallbackResponse
}
}
}
// Only requests that aren't revalidating can be resumed. If we have the
// minimal postponed data, then we should resume the render with it.
const postponed =
!isOnDemandRevalidate && !isRevalidating && minimalPostponed
? minimalPostponed
: undefined
// When we're in minimal mode, if we're trying to debug the static shell,
// we should just return nothing instead of resuming the dynamic render.
if (
(isDebugStaticShell || isDebugDynamicAccesses) &&
typeof postponed !== 'undefined'
) {
return {
cacheControl: { revalidate: 1, expire: undefined },
value: {
kind: CachedRouteKind.PAGES,
html: RenderResult.EMPTY,
pageData: {},
headers: undefined,
status: undefined,
} satisfies CachedPageValue,
}
}
// If this is a dynamic route with PPR enabled and the default route
// matches were set, then we should pass the fallback route params to
// the renderer as this is a fallback revalidation request.
const fallbackRouteParams =
pageIsDynamic &&
isRoutePPREnabled &&
(getRequestMeta(req, 'renderFallbackShell') || isDebugFallbackShell)
? getFallbackRouteParams(pathname)
: null
// Perform the render.
return doRender({
span,
postponed,
fallbackRouteParams,
})
}
const handleResponse = async (span?: Span): Promise<null | void> => {
const cacheEntry = await routeModule.handleResponse({
cacheKey: ssgCacheKey,
responseGenerator: (c) =>
responseGenerator({
span,
...c,
}),
routeKind: RouteKind.APP_PAGE,
isOnDemandRevalidate,
isRoutePPREnabled,
req,
nextConfig,
prerenderManifest,
waitUntil: ctx.waitUntil,
})
if (isDraftMode) {
res.setHeader(
'Cache-Control',
'private, no-cache, no-store, max-age=0, must-revalidate'
)
}
// In dev, we should not cache pages for any reason.
if (routeModule.isDev) {
res.setHeader('Cache-Control', 'no-store, must-revalidate')
}
if (!cacheEntry) {
if (ssgCacheKey) {
// A cache entry might not be generated if a response is written
// in `getInitialProps` or `getServerSideProps`, but those shouldn't
// have a cache key. If we do have a cache key but we don't end up
// with a cache entry, then either Next.js or the application has a
// bug that needs fixing.
throw new Error('invariant: cache entry required but not generated')
}
return null
}
if (cacheEntry.value?.kind !== CachedRouteKind.APP_PAGE) {
throw new Error(
`Invariant app-page handler received invalid cache entry ${cacheEntry.value?.kind}`
)
}
const didPostpone = typeof cacheEntry.value.postponed === 'string'
if (
isSSG &&
// We don't want to send a cache header for requests that contain dynamic
// data. If this is a Dynamic RSC request or wasn't a Prefetch RSC
// request, then we should set the cache header.
!isDynamicRSCRequest &&
(!didPostpone || isPrefetchRSCRequest)
) {
if (!minimalMode) {
// set x-nextjs-cache header to match the header
// we set for the image-optimizer
res.setHeader(
'x-nextjs-cache',
isOnDemandRevalidate
? 'REVALIDATED'
: cacheEntry.isMiss
? 'MISS'
: cacheEntry.isStale
? 'STALE'
: 'HIT'
)
}
// Set a header used by the client router to signal the response is static
// and should respect the `static` cache staleTime value.
res.setHeader(NEXT_IS_PRERENDER_HEADER, '1')
}
const { value: cachedData } = cacheEntry
// Coerce the cache control parameter from the render.
let cacheControl: CacheControl | undefined
// If this is a resume request in minimal mode it is streamed with dynamic
// content and should not be cached.
if (minimalPostponed) {
cacheControl = { revalidate: 0, expire: undefined }
}
// If this is in minimal mode and this is a flight request that isn't a
// prefetch request while PPR is enabled, it cannot be cached as it contains
// dynamic content.
else if (
minimalMode &&
isRSCRequest &&
!isPrefetchRSCRequest &&
isRoutePPREnabled
) {
cacheControl = { revalidate: 0, expire: undefined }
} else if (!routeModule.isDev) {
// If this is a preview mode request, we shouldn't cache it
if (isDraftMode) {
cacheControl = { revalidate: 0, expire: undefined }
}
// If this isn't SSG, then we should set change the header only if it is
// not set already.
else if (!isSSG) {
if (!res.getHeader('Cache-Control')) {
cacheControl = { revalidate: 0, expire: undefined }
}
} else if (cacheEntry.cacheControl) {
// If the cache entry has a cache control with a revalidate value that's
// a number, use it.
if (typeof cacheEntry.cacheControl.revalidate === 'number') {
if (cacheEntry.cacheControl.revalidate < 1) {
throw new Error(
`Invalid revalidate configuration provided: ${cacheEntry.cacheControl.revalidate} < 1`
)
}
cacheControl = {
revalidate: cacheEntry.cacheControl.revalidate,
expire: cacheEntry.cacheControl?.expire ?? nextConfig.expireTime,
}
}
// Otherwise if the revalidate value is false, then we should use the
// cache time of one year.
else {
cacheControl = { revalidate: CACHE_ONE_YEAR, expire: undefined }
}
}
}
cacheEntry.cacheControl = cacheControl
if (
typeof segmentPrefetchHeader === 'string' &&
cachedData?.kind === CachedRouteKind.APP_PAGE &&
cachedData.segmentData
) {
// This is a prefetch request issued by the client Segment Cache. These
// should never reach the application layer (lambda). We should either
// respond from the cache (HIT) or respond with 204 No Content (MISS).
// Set a header to indicate that PPR is enabled for this route. This
// lets the client distinguish between a regular cache miss and a cache
// miss due to PPR being disabled. In other contexts this header is used
// to indicate that the response contains dynamic data, but here we're
// only using it to indicate that the feature is enabled — the segment
// response itself contains whether the data is dynamic.
res.setHeader(NEXT_DID_POSTPONE_HEADER, '2')
// Add the cache tags header to the response if it exists and we're in
// minimal mode while rendering a static page.
const tags = cachedData.headers?.[NEXT_CACHE_TAGS_HEADER]
if (minimalMode && isSSG && tags && typeof tags === 'string') {
res.setHeader(NEXT_CACHE_TAGS_HEADER, tags)
}
const matchedSegment = cachedData.segmentData.get(segmentPrefetchHeader)
if (matchedSegment !== undefined) {
// Cache hit
return sendRenderResult({
req,
res,
generateEtags: nextConfig.generateEtags,
poweredByHeader: nextConfig.poweredByHeader,
result: RenderResult.fromStatic(
matchedSegment,
RSC_CONTENT_TYPE_HEADER
),
cacheControl: cacheEntry.cacheControl,
})
}
// Cache miss. Either a cache entry for this route has not been generated
// (which technically should not be possible when PPR is enabled, because
// at a minimum there should always be a fallback entry) or there's no
// match for the requested segment. Respond with a 204 No Content. We
// don't bother to respond with 404, because these requests are only
// issued as part of a prefetch.
res.statusCode = 204
return sendRenderResult({
req,
res,
generateEtags: nextConfig.generateEtags,
poweredByHeader: nextConfig.poweredByHeader,
result: RenderResult.EMPTY,
cacheControl: cacheEntry.cacheControl,
})
}
// If there's a callback for `onCacheEntry`, call it with the cache entry
// and the revalidate options.
const onCacheEntry = getRequestMeta(req, 'onCacheEntry')
if (onCacheEntry) {
const finished = await onCacheEntry(
{
...cacheEntry,
// TODO: remove this when upstream doesn't
// always expect this value to be "PAGE"
value: {
...cacheEntry.value,
kind: 'PAGE',
},
},
{
url: getRequestMeta(req, 'initURL'),
}
)
if (finished) {
// TODO: maybe we have to end the request?
return null
}
}
// If the request has a postponed state and it's a resume request we
// should error.
if (didPostpone && minimalPostponed) {
throw new Error(
'Invariant: postponed state should not be present on a resume request'
)
}
if (cachedData.headers) {
const headers = { ...cachedData.headers }
if (!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)
}
}
}
// Add the cache tags header to the response if it exists and we're in
// minimal mode while rendering a static page.
const tags = cachedData.headers?.[NEXT_CACHE_TAGS_HEADER]
if (minimalMode && isSSG && tags && typeof tags === 'string') {
res.setHeader(NEXT_CACHE_TAGS_HEADER, tags)
}
// If the request is a data request, then we shouldn't set the status code
// from the response because it should always be 200. This should be gated
// behind the experimental PPR flag.
if (cachedData.status && (!isRSCRequest || !isRoutePPREnabled)) {
res.statusCode = cachedData.status
}
// Redirect information is encoded in RSC payload, so we don't need to use redirect status codes
if (
!minimalMode &&
cachedData.status &&
RedirectStatusCode[cachedData.status] &&
isRSCRequest
) {
res.statusCode = 200
}
// Mark that the request did postpone.
if (didPostpone) {
res.setHeader(NEXT_DID_POSTPONE_HEADER, '1')
}
// we don't go through this block when preview mode is true
// as preview mode is a dynamic request (bypasses cache) and doesn't
// generate both HTML and payloads in the same request so continue to just
// return the generated payload
if (isRSCRequest && !isDraftMode) {
// If this is a dynamic RSC request, then stream the response.
if (typeof cachedData.rscData === 'undefined') {
if (cachedData.postponed) {
throw new Error('Invariant: Expected postponed to be undefined')
}
return sendRenderResult({
req,
res,
generateEtags: nextConfig.generateEtags,
poweredByHeader: nextConfig.poweredByHeader,
result: cachedData.html,
// Dynamic RSC responses cannot be cached, even if they're
// configured with `force-static` because we have no way of
// distinguishing between `force-static` and pages that have no
// postponed state.
// TODO: distinguish `force-static` from pages with no postponed state (static)
cacheControl: isDynamicRSCRequest
? { revalidate: 0, expire: undefined }
: cacheEntry.cacheControl,
})
}
// As this isn't a prefetch request, we should serve the static flight
// data.
return sendRenderResult({
req,
res,
generateEtags: nextConfig.generateEtags,
poweredByHeader: nextConfig.poweredByHeader,
result: RenderResult.fromStatic(
cachedData.rscData,
RSC_CONTENT_TYPE_HEADER
),
cacheControl: cacheEntry.cacheControl,
})
}
// This is a request for HTML data.
let body = cachedData.html
// If there's no postponed state, we should just serve the HTML. This
// should also be the case for a resume request because it's completed
// as a server render (rather than a static render).
if (!didPostpone || minimalMode || isRSCRequest) {
// If we're in test mode, we should add a sentinel chunk to the response
// that's between the static and dynamic parts so we can compare the
// chunks and add assertions.
if (
process.env.__NEXT_TEST_MODE &&
minimalMode &&
isRoutePPREnabled &&
body.contentType === HTML_CONTENT_TYPE_HEADER
) {
// As we're in minimal mode, the static part would have already been
// streamed first. The only part that this streams is the dynamic part
// so we should FIRST stream the sentinel and THEN the dynamic part.
body.unshift(createPPRBoundarySentinel())
}
return sendRenderResult({
req,
res,
generateEtags: nextConfig.generateEtags,
poweredByHeader: nextConfig.poweredByHeader,
result: body,
cacheControl: cacheEntry.cacheControl,
})
}
// If we're debugging the static shell or the dynamic API accesses, we
// should just serve the HTML without resuming the render. The returned
// HTML will be the static shell so all the Dynamic API's will be used
// during static generation.
if (isDebugStaticShell || isDebugDynamicAccesses) {
// Since we're not resuming the render, we need to at least add the
// closing body and html tags to create valid HTML.
body.push(
new ReadableStream({
start(controller) {
controller.enqueue(ENCODED_TAGS.CLOSED.BODY_AND_HTML)
controller.close()
},
})
)
return sendRenderResult({
req,
res,
generateEtags: nextConfig.generateEtags,
poweredByHeader: nextConfig.poweredByHeader,
result: body,
cacheControl: { revalidate: 0, expire: undefined },
})
}
// If we're in test mode, we should add a sentinel chunk to the response
// that's between the static and dynamic parts so we can compare the
// chunks and add assertions.
if (process.env.__NEXT_TEST_MODE) {
body.push(createPPRBoundarySentinel())
}
// This request has postponed, so let's create a new transformer that the
// dynamic data can pipe to that will attach the dynamic data to the end
// of the response.
const transformer = new TransformStream<Uint8Array, Uint8Array>()
body.push(transformer.readable)
// Perform the render again, but this time, provide the postponed state.
// We don't await because we want the result to start streaming now, and
// we've already chained the transformer's readable to the render result.
doRender({
span,
postponed: cachedData.postponed,
// This is a resume render, not a fallback render, so we don't need to
// set this.
fallbackRouteParams: null,
})
.then(async (result) => {
if (!result) {
throw new Error('Invariant: expected a result to be returned')
}
if (result.value?.kind !== CachedRouteKind.APP_PAGE) {
throw new Error(
`Invariant: expected a page response, got ${result.value?.kind}`
)
}
// Pipe the resume result to the transformer.
await result.value.html.pipeTo(transformer.writable)
})
.catch((err) => {
// An error occurred during piping or preparing the render, abort
// the transformers writer so we can terminate the stream.
transformer.writable.abort(err).catch((e) => {
console.error("couldn't abort transformer", e)
})
})
return sendRenderResult({
req,
res,
generateEtags: nextConfig.generateEtags,
poweredByHeader: nextConfig.poweredByHeader,
result: body,
// We don't want to cache the response if it has postponed data because
// the response being sent to the client it's dynamic parts are streamed
// to the client on the same request.
cacheControl: { revalidate: 0, expire: undefined },
})
}
// TODO: activeSpan code path is for when wrapped by
// next-server can be removed when this is no longer used
if (activeSpan) {
await handleResponse(activeSpan)
} else {
return await tracer.withPropagatedContext(req.headers, () =>
tracer.trace(
BaseServerSpan.handleRequest,
{
spanName: `${method} ${req.url}`,
kind: SpanKind.SERVER,
attributes: {
'http.method': method,
'http.target': req.url,
},
},
handleResponse
)
)
}
} catch (err) {
// if we aren't wrapped by base-server handle here
if (!activeSpan && !(err instanceof NoFallbackError)) {
await routeModule.onRequestError(
req,
err,
{
routerKind: 'App Router',
routePath: srcPage,
routeType: 'render',
revalidateReason: getRevalidateReason({
isRevalidate: isSSG,
isOnDemandRevalidate,
}),
},
routerServerContext
)
}
// rethrow so that we can handle serving error page
throw err
}
}
// TODO: omit this from production builds, only test builds should include it
/**
* Creates a readable stream that emits a PPR boundary sentinel.
*
* @returns A readable stream that emits a PPR boundary sentinel.
*/
function createPPRBoundarySentinel() {
return new ReadableStream({
start(controller) {
controller.enqueue(
new TextEncoder().encode('<!-- PPR_BOUNDARY_SENTINEL -->')
)
controller.close()
},
})
}
|