File size: 98,078 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 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 |
import type { __ApiPreviewProps } from './api-utils'
import type { LoadComponentsReturnType } from './load-components'
import type { MiddlewareRouteMatch } from '../shared/lib/router/utils/middleware-route-matcher'
import type { Params } from './request/params'
import type { NextConfig, NextConfigComplete } from './config-shared'
import type {
NextParsedUrlQuery,
NextUrlWithParsedQuery,
RequestMeta,
} from './request-meta'
import type { ParsedUrlQuery } from 'querystring'
import type { RenderOptsPartial as PagesRenderOptsPartial } from './render'
import type {
RenderOptsPartial as AppRenderOptsPartial,
ServerOnInstrumentationRequestError,
} from './app-render/types'
import type {
ServerComponentsHmrCache,
ResponseCacheBase,
} from './response-cache'
import type { UrlWithParsedQuery } from 'url'
import {
NormalizeError,
DecodeError,
normalizeRepeatedSlashes,
MissingStaticPage,
} from '../shared/lib/utils'
import type { PagesManifest } from '../build/webpack/plugins/pages-manifest-plugin'
import type { BaseNextRequest, BaseNextResponse } from './base-http'
import type {
ManifestRewriteRoute,
ManifestRoute,
PrerenderManifest,
} from '../build'
import type { ClientReferenceManifest } from '../build/webpack/plugins/flight-manifest-plugin'
import type { NextFontManifest } from '../build/webpack/plugins/next-font-manifest-plugin'
import type { PagesAPIRouteMatch } from './route-matches/pages-api-route-match'
import type {
Server as HTTPServer,
IncomingMessage,
ServerResponse as HTTPServerResponse,
} from 'http'
import type { MiddlewareMatcher } from '../build/analysis/get-page-static-info'
import type { TLSSocket } from 'tls'
import type { PathnameNormalizer } from './normalizers/request/pathname-normalizer'
import type { InstrumentationModule } from './instrumentation/types'
import { format as formatUrl, parse as parseUrl } from 'url'
import { formatHostname } from './lib/format-hostname'
import {
APP_PATHS_MANIFEST,
NEXT_BUILTIN_DOCUMENT,
PAGES_MANIFEST,
STATIC_STATUS_PAGES,
UNDERSCORE_NOT_FOUND_ROUTE,
UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,
} from '../shared/lib/constants'
import { isDynamicRoute } from '../shared/lib/router/utils'
import { setConfig } from '../shared/lib/runtime-config.external'
import { execOnce } from '../shared/lib/utils'
import { isBlockedPage } from './utils'
import { getBotType, isBot } from '../shared/lib/router/utils/is-bot'
import RenderResult from './render-result'
import { removeTrailingSlash } from '../shared/lib/router/utils/remove-trailing-slash'
import { denormalizePagePath } from '../shared/lib/page-path/denormalize-page-path'
import * as Log from '../build/output/log'
import { getPreviouslyRevalidatedTags, getServerUtils } from './server-utils'
import isError, { getProperError } from '../lib/is-error'
import {
addRequestMeta,
getRequestMeta,
removeRequestMeta,
setRequestMeta,
} from './request-meta'
import { removePathPrefix } from '../shared/lib/router/utils/remove-path-prefix'
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths'
import { getHostname } from '../shared/lib/get-hostname'
import { parseUrl as parseUrlUtil } from '../shared/lib/router/utils/parse-url'
import { getNextPathnameInfo } from '../shared/lib/router/utils/get-next-pathname-info'
import {
RSC_HEADER,
NEXT_RSC_UNION_QUERY,
NEXT_ROUTER_PREFETCH_HEADER,
NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,
NEXT_URL,
NEXT_ROUTER_STATE_TREE_HEADER,
} from '../client/components/app-router-headers'
import type {
MatchOptions,
RouteMatcherManager,
} from './route-matcher-managers/route-matcher-manager'
import { LocaleRouteNormalizer } from './normalizers/locale-route-normalizer'
import { DefaultRouteMatcherManager } from './route-matcher-managers/default-route-matcher-manager'
import { AppPageRouteMatcherProvider } from './route-matcher-providers/app-page-route-matcher-provider'
import { AppRouteRouteMatcherProvider } from './route-matcher-providers/app-route-route-matcher-provider'
import { PagesAPIRouteMatcherProvider } from './route-matcher-providers/pages-api-route-matcher-provider'
import { PagesRouteMatcherProvider } from './route-matcher-providers/pages-route-matcher-provider'
import { ServerManifestLoader } from './route-matcher-providers/helpers/manifest-loaders/server-manifest-loader'
import { getTracer, isBubbledError, SpanKind } from './lib/trace/tracer'
import { BaseServerSpan } from './lib/trace/constants'
import { I18NProvider } from './lib/i18n-provider'
import { sendResponse } from './send-response'
import { normalizeNextQueryParam } from './web/utils'
import {
HTML_CONTENT_TYPE_HEADER,
JSON_CONTENT_TYPE_HEADER,
MATCHED_PATH_HEADER,
NEXT_RESUME_HEADER,
} from '../lib/constants'
import { normalizeLocalePath } from '../shared/lib/i18n/normalize-locale-path'
import { matchNextDataPathname } from './lib/match-next-data-pathname'
import getRouteFromAssetPath from '../shared/lib/router/utils/get-route-from-asset-path'
import { RSCPathnameNormalizer } from './normalizers/request/rsc'
import { stripFlightHeaders } from './app-render/strip-flight-headers'
import {
isAppPageRouteModule,
isAppRouteRouteModule,
} from './route-modules/checks'
import { PrefetchRSCPathnameNormalizer } from './normalizers/request/prefetch-rsc'
import { NextDataPathnameNormalizer } from './normalizers/request/next-data'
import { getIsPossibleServerAction } from './lib/server-action-request-meta'
import { isInterceptionRouteAppPath } from '../shared/lib/router/utils/interception-routes'
import { toRoute } from './lib/to-route'
import type { DeepReadonly } from '../shared/lib/deep-readonly'
import { isNodeNextRequest, isNodeNextResponse } from './base-http/helpers'
import { patchSetHeaderWithCookieSupport } from './lib/patch-set-header'
import { checkIsAppPPREnabled } from './lib/experimental/ppr'
import {
getBuiltinRequestContext,
type WaitUntil,
} from './after/builtin-request-context'
import { NextRequestHint } from './web/adapter'
import type { RouteModule } from './route-modules/route-module'
import { type FallbackMode, parseFallbackField } from '../lib/fallback'
import { SegmentPrefixRSCPathnameNormalizer } from './normalizers/request/segment-prefix-rsc'
import { shouldServeStreamingMetadata } from './lib/streaming-metadata'
import { decodeQueryPathParameter } from './lib/decode-query-path-parameter'
import { NoFallbackError } from '../shared/lib/no-fallback-error.external'
import { getCacheHandlers } from './use-cache/handlers'
import { fixMojibake } from './lib/fix-mojibake'
import { computeCacheBustingSearchParam } from '../shared/lib/router/utils/cache-busting-search-param'
import { setCacheBustingSearchParamWithHash } from '../client/components/router-reducer/set-cache-busting-search-param'
import type { CacheControl } from './lib/cache-control'
export type FindComponentsResult = {
components: LoadComponentsReturnType
query: NextParsedUrlQuery
}
export interface MiddlewareRoutingItem {
page: string
match: MiddlewareRouteMatch
matchers?: MiddlewareMatcher[]
}
export type RouteHandler<
ServerRequest extends BaseNextRequest = BaseNextRequest,
ServerResponse extends BaseNextResponse = BaseNextResponse,
> = (
req: ServerRequest,
res: ServerResponse,
parsedUrl: NextUrlWithParsedQuery
) => PromiseLike<boolean> | boolean
/**
* The normalized route manifest is the same as the route manifest, but with
* the rewrites normalized to the object shape that the router expects.
*/
export type NormalizedRouteManifest = {
readonly dynamicRoutes: ReadonlyArray<ManifestRoute>
readonly rewrites: {
readonly beforeFiles: ReadonlyArray<ManifestRewriteRoute>
readonly afterFiles: ReadonlyArray<ManifestRewriteRoute>
readonly fallback: ReadonlyArray<ManifestRewriteRoute>
}
}
export interface Options {
/**
* Object containing the configuration next.config.js
*/
conf: NextConfig
/**
* Set to false when the server was created by Next.js
*/
customServer?: boolean
/**
* Tells if Next.js is running in dev mode
*/
dev?: boolean
/**
* Enables the experimental testing mode.
*/
experimentalTestProxy?: boolean
/**
* Whether or not the dev server is running in experimental HTTPS mode
*/
experimentalHttpsServer?: boolean
/**
* Where the Next project is located
*/
dir?: string
/**
* Tells if Next.js is at the platform-level
*/
minimalMode?: boolean
/**
* Hide error messages containing server information
*/
quiet?: boolean
/**
* The hostname the server is running behind
*/
hostname?: string
/**
* The port the server is running behind
*/
port?: number
/**
* The HTTP Server that Next.js is running behind
*/
httpServer?: HTTPServer
}
export type RenderOpts = PagesRenderOptsPartial & AppRenderOptsPartial
export type LoadedRenderOpts = RenderOpts &
LoadComponentsReturnType &
RequestLifecycleOpts
export type RequestLifecycleOpts = {
waitUntil: ((promise: Promise<any>) => void) | undefined
onClose: (callback: () => void) => void
onAfterTaskError: ((error: unknown) => void) | undefined
}
type BaseRenderOpts = RenderOpts & {
poweredByHeader: boolean
generateEtags: boolean
previewProps: __ApiPreviewProps
}
/**
* The public interface for rendering with the server programmatically. This
* would typically only allow the base request or response to extend it, but
* because this can be programmatically accessed, we assume that it could also
* be the base Node.js request and response types.
*/
export interface BaseRequestHandler<
ServerRequest extends BaseNextRequest | IncomingMessage = BaseNextRequest,
ServerResponse extends
| BaseNextResponse
| HTTPServerResponse = BaseNextResponse,
> {
(
req: ServerRequest,
res: ServerResponse,
parsedUrl?: NextUrlWithParsedQuery | undefined
): Promise<void> | void
}
export type RequestContext<
ServerRequest extends BaseNextRequest = BaseNextRequest,
ServerResponse extends BaseNextResponse = BaseNextResponse,
> = {
req: ServerRequest
res: ServerResponse
pathname: string
query: NextParsedUrlQuery
renderOpts: RenderOpts
}
// Internal wrapper around build errors at development
// time, to prevent us from propagating or logging them
export class WrappedBuildError extends Error {
innerError: Error
constructor(innerError: Error) {
super()
this.innerError = innerError
}
}
type ResponsePayload = {
body: RenderResult
cacheControl?: CacheControl
}
export type NextEnabledDirectories = {
readonly pages: boolean
readonly app: boolean
}
export default abstract class Server<
ServerOptions extends Options = Options,
ServerRequest extends BaseNextRequest = BaseNextRequest,
ServerResponse extends BaseNextResponse = BaseNextResponse,
> {
public readonly hostname?: string
public readonly fetchHostname?: string
public readonly port?: number
protected readonly dir: string
protected readonly quiet: boolean
protected readonly nextConfig: NextConfigComplete
protected readonly distDir: string
protected readonly publicDir: string
protected readonly hasStaticDir: boolean
protected readonly pagesManifest?: PagesManifest
protected readonly appPathsManifest?: PagesManifest
protected readonly buildId: string
protected readonly minimalMode: boolean
protected readonly renderOpts: BaseRenderOpts
protected readonly serverOptions: Readonly<ServerOptions>
protected readonly appPathRoutes?: Record<string, string[]>
protected readonly clientReferenceManifest?: DeepReadonly<ClientReferenceManifest>
protected interceptionRoutePatterns: RegExp[]
protected nextFontManifest?: DeepReadonly<NextFontManifest>
protected instrumentation: InstrumentationModule | undefined
private readonly responseCache: ResponseCacheBase
protected abstract getPublicDir(): string
protected abstract getHasStaticDir(): boolean
protected abstract getPagesManifest(): PagesManifest | undefined
protected abstract getAppPathsManifest(): PagesManifest | undefined
protected abstract getBuildId(): string
protected abstract getinterceptionRoutePatterns(): RegExp[]
protected readonly enabledDirectories: NextEnabledDirectories
protected abstract getEnabledDirectories(dev: boolean): NextEnabledDirectories
protected readonly experimentalTestProxy?: boolean
protected abstract findPageComponents(params: {
locale: string | undefined
page: string
query: NextParsedUrlQuery
params: Params
isAppPath: boolean
// The following parameters are used in the development server's
// implementation.
sriEnabled?: boolean
appPaths?: ReadonlyArray<string> | null
shouldEnsure?: boolean
url?: string
}): Promise<FindComponentsResult | null>
protected abstract getPrerenderManifest(): DeepReadonly<PrerenderManifest>
protected abstract getNextFontManifest():
| DeepReadonly<NextFontManifest>
| undefined
protected abstract attachRequestMeta(
req: ServerRequest,
parsedUrl: NextUrlWithParsedQuery
): void
protected abstract hasPage(pathname: string): Promise<boolean>
protected abstract sendRenderResult(
req: ServerRequest,
res: ServerResponse,
options: {
result: RenderResult
generateEtags: boolean
poweredByHeader: boolean
cacheControl: CacheControl | undefined
}
): Promise<void>
protected abstract runApi(
req: ServerRequest,
res: ServerResponse,
query: ParsedUrlQuery,
match: PagesAPIRouteMatch
): Promise<boolean>
protected abstract renderHTML(
req: ServerRequest,
res: ServerResponse,
pathname: string,
query: NextParsedUrlQuery,
renderOpts: LoadedRenderOpts
): Promise<RenderResult>
protected abstract getIncrementalCache(options: {
requestHeaders: Record<string, undefined | string | string[]>
}): Promise<import('./lib/incremental-cache').IncrementalCache>
protected abstract getResponseCache(options: {
dev: boolean
}): ResponseCacheBase
protected getServerComponentsHmrCache():
| ServerComponentsHmrCache
| undefined {
return this.nextConfig.experimental.serverComponentsHmrCache
? (globalThis as any).__serverComponentsHmrCache
: undefined
}
protected abstract loadEnvConfig(params: {
dev: boolean
forceReload?: boolean
}): void
// TODO-APP: (wyattjoh): Make protected again. Used for turbopack in route-resolver.ts right now.
public readonly matchers: RouteMatcherManager
protected readonly i18nProvider?: I18NProvider
protected readonly localeNormalizer?: LocaleRouteNormalizer
protected readonly normalizers: {
readonly rsc: RSCPathnameNormalizer | undefined
readonly prefetchRSC: PrefetchRSCPathnameNormalizer | undefined
readonly segmentPrefetchRSC: SegmentPrefixRSCPathnameNormalizer | undefined
readonly data: NextDataPathnameNormalizer | undefined
}
private readonly isAppPPREnabled: boolean
private readonly isAppSegmentPrefetchEnabled: boolean
/**
* This is used to persist cache scopes across
* prefetch -> full route requests for cache components
* it's only fully used in dev
*/
public constructor(options: ServerOptions) {
const {
dir = '.',
quiet = false,
conf,
dev = false,
minimalMode = false,
hostname,
port,
experimentalTestProxy,
} = options
this.experimentalTestProxy = experimentalTestProxy
this.serverOptions = options
this.dir = (require('path') as typeof import('path')).resolve(dir)
this.quiet = quiet
this.loadEnvConfig({ dev })
// TODO: should conf be normalized to prevent missing
// values from causing issues as this can be user provided
this.nextConfig = conf as NextConfigComplete
this.hostname = hostname
if (this.hostname) {
// we format the hostname so that it can be fetched
this.fetchHostname = formatHostname(this.hostname)
}
this.port = port
this.distDir = (require('path') as typeof import('path')).join(
this.dir,
this.nextConfig.distDir
)
this.publicDir = this.getPublicDir()
this.hasStaticDir = !minimalMode && this.getHasStaticDir()
this.i18nProvider = this.nextConfig.i18n?.locales
? new I18NProvider(this.nextConfig.i18n)
: undefined
// Configure the locale normalizer, it's used for routes inside `pages/`.
this.localeNormalizer = this.i18nProvider
? new LocaleRouteNormalizer(this.i18nProvider)
: undefined
// Only serverRuntimeConfig needs the default
// publicRuntimeConfig gets it's default in client/index.js
const {
serverRuntimeConfig = {},
publicRuntimeConfig,
assetPrefix,
generateEtags,
} = this.nextConfig
this.buildId = this.getBuildId()
// this is a hack to avoid Webpack knowing this is equal to this.minimalMode
// because we replace this.minimalMode to true in production bundles.
const minimalModeKey = 'minimalMode'
this[minimalModeKey] =
minimalMode || !!process.env.NEXT_PRIVATE_MINIMAL_MODE
this.enabledDirectories = this.getEnabledDirectories(dev)
this.isAppPPREnabled =
this.enabledDirectories.app &&
checkIsAppPPREnabled(this.nextConfig.experimental.ppr)
this.isAppSegmentPrefetchEnabled =
this.enabledDirectories.app &&
this.nextConfig.experimental.clientSegmentCache === true
this.normalizers = {
// We should normalize the pathname from the RSC prefix only in minimal
// mode as otherwise that route is not exposed external to the server as
// we instead only rely on the headers.
rsc:
this.enabledDirectories.app && this.minimalMode
? new RSCPathnameNormalizer()
: undefined,
prefetchRSC:
this.isAppPPREnabled && this.minimalMode
? new PrefetchRSCPathnameNormalizer()
: undefined,
segmentPrefetchRSC:
this.isAppSegmentPrefetchEnabled && this.minimalMode
? new SegmentPrefixRSCPathnameNormalizer()
: undefined,
data: this.enabledDirectories.pages
? new NextDataPathnameNormalizer(this.buildId)
: undefined,
}
this.nextFontManifest = this.getNextFontManifest()
process.env.NEXT_DEPLOYMENT_ID = this.nextConfig.deploymentId || ''
this.renderOpts = {
dir: this.dir,
supportsDynamicResponse: true,
trailingSlash: this.nextConfig.trailingSlash,
deploymentId: this.nextConfig.deploymentId,
poweredByHeader: this.nextConfig.poweredByHeader,
canonicalBase: this.nextConfig.amp.canonicalBase || '',
generateEtags,
previewProps: this.getPrerenderManifest().preview,
ampOptimizerConfig: this.nextConfig.experimental.amp?.optimizer,
basePath: this.nextConfig.basePath,
images: this.nextConfig.images,
optimizeCss: this.nextConfig.experimental.optimizeCss,
nextConfigOutput: this.nextConfig.output,
nextScriptWorkers: this.nextConfig.experimental.nextScriptWorkers,
disableOptimizedLoading:
this.nextConfig.experimental.disableOptimizedLoading,
domainLocales: this.nextConfig.i18n?.domains,
distDir: this.distDir,
serverComponents: this.enabledDirectories.app,
cacheLifeProfiles: this.nextConfig.experimental.cacheLife,
enableTainting: this.nextConfig.experimental.taint,
crossOrigin: this.nextConfig.crossOrigin
? this.nextConfig.crossOrigin
: undefined,
largePageDataBytes: this.nextConfig.experimental.largePageDataBytes,
// Only the `publicRuntimeConfig` key is exposed to the client side
// It'll be rendered as part of __NEXT_DATA__ on the client side
runtimeConfig:
Object.keys(publicRuntimeConfig).length > 0
? publicRuntimeConfig
: undefined,
isExperimentalCompile: this.nextConfig.experimental.isExperimentalCompile,
// `htmlLimitedBots` is passed to server as serialized config in string format
htmlLimitedBots: this.nextConfig.htmlLimitedBots,
experimental: {
expireTime: this.nextConfig.expireTime,
staleTimes: this.nextConfig.experimental.staleTimes,
clientTraceMetadata: this.nextConfig.experimental.clientTraceMetadata,
cacheComponents: this.nextConfig.experimental.cacheComponents ?? false,
clientSegmentCache:
this.nextConfig.experimental.clientSegmentCache === 'client-only'
? 'client-only'
: Boolean(this.nextConfig.experimental.clientSegmentCache),
dynamicOnHover: this.nextConfig.experimental.dynamicOnHover ?? false,
inlineCss: this.nextConfig.experimental.inlineCss ?? false,
authInterrupts: !!this.nextConfig.experimental.authInterrupts,
},
onInstrumentationRequestError:
this.instrumentationOnRequestError.bind(this),
reactMaxHeadersLength: this.nextConfig.reactMaxHeadersLength,
devtoolSegmentExplorer:
this.nextConfig.experimental.devtoolSegmentExplorer,
}
// Initialize next/config with the environment configuration
setConfig({
serverRuntimeConfig,
publicRuntimeConfig,
})
this.pagesManifest = this.getPagesManifest()
this.appPathsManifest = this.getAppPathsManifest()
this.appPathRoutes = this.getAppPathRoutes()
this.interceptionRoutePatterns = this.getinterceptionRoutePatterns()
// Configure the routes.
this.matchers = this.getRouteMatchers()
// Start route compilation. We don't wait for the routes to finish loading
// because we use the `waitTillReady` promise below in `handleRequest` to
// wait. Also we can't `await` in the constructor.
void this.matchers.reload()
this.setAssetPrefix(assetPrefix)
this.responseCache = this.getResponseCache({ dev })
}
private handleRSCRequest: RouteHandler<ServerRequest, ServerResponse> = (
req,
_res,
parsedUrl
) => {
if (!parsedUrl.pathname) return false
if (this.normalizers.segmentPrefetchRSC?.match(parsedUrl.pathname)) {
const result = this.normalizers.segmentPrefetchRSC.extract(
parsedUrl.pathname
)
if (!result) return false
const { originalPathname, segmentPath } = result
parsedUrl.pathname = originalPathname
// Mark the request as a router prefetch request.
req.headers[RSC_HEADER.toLowerCase()] = '1'
req.headers[NEXT_ROUTER_PREFETCH_HEADER.toLowerCase()] = '1'
req.headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER.toLowerCase()] =
segmentPath
addRequestMeta(req, 'isRSCRequest', true)
addRequestMeta(req, 'isPrefetchRSCRequest', true)
addRequestMeta(req, 'segmentPrefetchRSCRequest', segmentPath)
} else if (this.normalizers.prefetchRSC?.match(parsedUrl.pathname)) {
parsedUrl.pathname = this.normalizers.prefetchRSC.normalize(
parsedUrl.pathname,
true
)
// Mark the request as a router prefetch request.
req.headers[RSC_HEADER.toLowerCase()] = '1'
req.headers[NEXT_ROUTER_PREFETCH_HEADER.toLowerCase()] = '1'
addRequestMeta(req, 'isRSCRequest', true)
addRequestMeta(req, 'isPrefetchRSCRequest', true)
} else if (this.normalizers.rsc?.match(parsedUrl.pathname)) {
parsedUrl.pathname = this.normalizers.rsc.normalize(
parsedUrl.pathname,
true
)
// Mark the request as a RSC request.
req.headers[RSC_HEADER.toLowerCase()] = '1'
addRequestMeta(req, 'isRSCRequest', true)
} else if (req.headers['x-now-route-matches']) {
// If we didn't match, return with the flight headers stripped. If in
// minimal mode we didn't match based on the path, this can't be a RSC
// request. This is because Vercel only sends this header during
// revalidation requests and we want the cache to instead depend on the
// request path for flight information.
stripFlightHeaders(req.headers)
return false
} else if (req.headers[RSC_HEADER.toLowerCase()] === '1') {
addRequestMeta(req, 'isRSCRequest', true)
if (req.headers[NEXT_ROUTER_PREFETCH_HEADER.toLowerCase()] === '1') {
addRequestMeta(req, 'isPrefetchRSCRequest', true)
const segmentPrefetchRSCRequest =
req.headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER.toLowerCase()]
if (typeof segmentPrefetchRSCRequest === 'string') {
addRequestMeta(
req,
'segmentPrefetchRSCRequest',
segmentPrefetchRSCRequest
)
}
}
} else {
// Otherwise just return without doing anything.
return false
}
if (req.url) {
const parsed = parseUrl(req.url)
parsed.pathname = parsedUrl.pathname
req.url = formatUrl(parsed)
}
return false
}
private handleNextDataRequest: RouteHandler<ServerRequest, ServerResponse> =
async (req, res, parsedUrl) => {
const middleware = await this.getMiddleware()
const params = matchNextDataPathname(parsedUrl.pathname)
// ignore for non-next data URLs
if (!params || !params.path) {
return false
}
if (params.path[0] !== this.buildId) {
// Ignore if its a middleware request when we aren't on edge.
if (getRequestMeta(req, 'middlewareInvoke')) {
return false
}
// Make sure to 404 if the buildId isn't correct
await this.render404(req, res, parsedUrl)
return true
}
// remove buildId from URL
params.path.shift()
const lastParam = params.path[params.path.length - 1]
// show 404 if it doesn't end with .json
if (typeof lastParam !== 'string' || !lastParam.endsWith('.json')) {
await this.render404(req, res, parsedUrl)
return true
}
// re-create page's pathname
let pathname = `/${params.path.join('/')}`
pathname = getRouteFromAssetPath(pathname, '.json')
// ensure trailing slash is normalized per config
if (middleware) {
if (this.nextConfig.trailingSlash && !pathname.endsWith('/')) {
pathname += '/'
}
if (
!this.nextConfig.trailingSlash &&
pathname.length > 1 &&
pathname.endsWith('/')
) {
pathname = pathname.substring(0, pathname.length - 1)
}
}
if (this.i18nProvider) {
// Remove the port from the hostname if present.
const hostname = req?.headers.host?.split(':', 1)[0].toLowerCase()
const domainLocale = this.i18nProvider.detectDomainLocale(hostname)
const defaultLocale =
domainLocale?.defaultLocale ?? this.i18nProvider.config.defaultLocale
const localePathResult = this.i18nProvider.analyze(pathname)
// If the locale is detected from the path, we need to remove it
// from the pathname.
if (localePathResult.detectedLocale) {
pathname = localePathResult.pathname
}
// Update the query with the detected locale and default locale.
addRequestMeta(req, 'locale', localePathResult.detectedLocale)
addRequestMeta(req, 'defaultLocale', defaultLocale)
// If the locale is not detected from the path, we need to mark that
// it was not inferred from default.
if (!localePathResult.detectedLocale) {
removeRequestMeta(req, 'localeInferredFromDefault')
}
// If no locale was detected and we don't have middleware, we need
// to render a 404 page.
if (!localePathResult.detectedLocale && !middleware) {
addRequestMeta(req, 'locale', defaultLocale)
await this.render404(req, res, parsedUrl)
return true
}
}
parsedUrl.pathname = pathname
addRequestMeta(req, 'isNextDataReq', true)
return false
}
protected handleNextImageRequest: RouteHandler<
ServerRequest,
ServerResponse
> = () => false
protected handleCatchallRenderRequest: RouteHandler<
ServerRequest,
ServerResponse
> = () => false
protected handleCatchallMiddlewareRequest: RouteHandler<
ServerRequest,
ServerResponse
> = () => false
protected getRouteMatchers(): RouteMatcherManager {
// Create a new manifest loader that get's the manifests from the server.
const manifestLoader = new ServerManifestLoader((name) => {
switch (name) {
case PAGES_MANIFEST:
return this.getPagesManifest() ?? null
case APP_PATHS_MANIFEST:
return this.getAppPathsManifest() ?? null
default:
return null
}
})
// Configure the matchers and handlers.
const matchers: RouteMatcherManager = new DefaultRouteMatcherManager()
// Match pages under `pages/`.
matchers.push(
new PagesRouteMatcherProvider(
this.distDir,
manifestLoader,
this.i18nProvider
)
)
// Match api routes under `pages/api/`.
matchers.push(
new PagesAPIRouteMatcherProvider(
this.distDir,
manifestLoader,
this.i18nProvider
)
)
// If the app directory is enabled, then add the app matchers and handlers.
if (this.enabledDirectories.app) {
// Match app pages under `app/`.
matchers.push(
new AppPageRouteMatcherProvider(this.distDir, manifestLoader)
)
matchers.push(
new AppRouteRouteMatcherProvider(this.distDir, manifestLoader)
)
}
return matchers
}
protected async instrumentationOnRequestError(
...args: Parameters<ServerOnInstrumentationRequestError>
) {
const [err, req, ctx] = args
if (this.instrumentation) {
try {
await this.instrumentation.onRequestError?.(
err,
{
path: req.url || '',
method: req.method || 'GET',
// Normalize middleware headers and other server request headers
headers:
req instanceof NextRequestHint
? Object.fromEntries(req.headers.entries())
: req.headers,
},
ctx
)
} catch (handlerErr) {
// Log the soft error and continue, since errors can thrown from react stream handler
console.error('Error in instrumentation.onRequestError:', handlerErr)
}
}
}
public logError(err: Error): void {
if (this.quiet) return
Log.error(err)
}
public async handleRequest(
req: ServerRequest,
res: ServerResponse,
parsedUrl?: NextUrlWithParsedQuery
): Promise<void> {
await this.prepare()
const method = req.method.toUpperCase()
const tracer = getTracer()
return tracer.withPropagatedContext(req.headers, () => {
return tracer.trace(
BaseServerSpan.handleRequest,
{
spanName: `${method} ${req.url}`,
kind: SpanKind.SERVER,
attributes: {
'http.method': method,
'http.target': req.url,
},
},
async (span) =>
this.handleRequestImpl(req, res, parsedUrl).finally(() => {
if (!span) return
const isRSCRequest = getRequestMeta(req, 'isRSCRequest') ?? false
span.setAttributes({
'http.status_code': res.statusCode,
'next.rsc': isRSCRequest,
})
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 = isRSCRequest
? `RSC ${method} ${route}`
: `${method} ${route}`
span.setAttributes({
'next.route': route,
'http.route': route,
'next.span_name': name,
})
span.updateName(name)
} else {
span.updateName(
isRSCRequest
? `RSC ${method} ${req.url}`
: `${method} ${req.url}`
)
}
})
)
})
}
private async handleRequestImpl(
req: ServerRequest,
res: ServerResponse,
parsedUrl?: NextUrlWithParsedQuery
): Promise<void> {
try {
// Wait for the matchers to be ready.
await this.matchers.waitTillReady()
// ensure cookies set in middleware are merged and
// not overridden by API routes/getServerSideProps
patchSetHeaderWithCookieSupport(
req,
isNodeNextResponse(res) ? res.originalResponse : res
)
const urlParts = (req.url || '').split('?', 1)
const urlNoQuery = urlParts[0]
// this normalizes repeated slashes in the path e.g. hello//world ->
// hello/world or backslashes to forward slashes, this does not
// handle trailing slash as that is handled the same as a next.config.js
// redirect
if (urlNoQuery?.match(/(\\|\/\/)/)) {
const cleanUrl = normalizeRepeatedSlashes(req.url!)
res.redirect(cleanUrl, 308).body(cleanUrl).send()
return
}
// Parse url if parsedUrl not provided
if (!parsedUrl || typeof parsedUrl !== 'object') {
if (!req.url) {
throw new Error('Invariant: url can not be undefined')
}
parsedUrl = parseUrl(req.url!, true)
}
if (!parsedUrl.pathname) {
throw new Error("Invariant: pathname can't be empty")
}
// Parse the querystring ourselves if the user doesn't handle querystring parsing
if (typeof parsedUrl.query === 'string') {
parsedUrl.query = Object.fromEntries(
new URLSearchParams(parsedUrl.query)
)
}
// Update the `x-forwarded-*` headers.
const { originalRequest = null } = isNodeNextRequest(req) ? req : {}
const xForwardedProto = originalRequest?.headers['x-forwarded-proto']
const isHttps = xForwardedProto
? xForwardedProto === 'https'
: !!(originalRequest?.socket as TLSSocket)?.encrypted
req.headers['x-forwarded-host'] ??= req.headers['host'] ?? this.hostname
req.headers['x-forwarded-port'] ??= this.port
? this.port.toString()
: isHttps
? '443'
: '80'
req.headers['x-forwarded-proto'] ??= isHttps ? 'https' : 'http'
req.headers['x-forwarded-for'] ??= originalRequest?.socket?.remoteAddress
// This should be done before any normalization of the pathname happens as
// it captures the initial URL.
this.attachRequestMeta(req, parsedUrl)
let finished = await this.handleRSCRequest(req, res, parsedUrl)
if (finished) return
const domainLocale = this.i18nProvider?.detectDomainLocale(
getHostname(parsedUrl, req.headers)
)
const defaultLocale =
domainLocale?.defaultLocale || this.nextConfig.i18n?.defaultLocale
addRequestMeta(req, 'defaultLocale', defaultLocale)
const url = parseUrlUtil(req.url.replace(/^\/+/, '/'))
const pathnameInfo = getNextPathnameInfo(url.pathname, {
nextConfig: this.nextConfig,
i18nProvider: this.i18nProvider,
})
url.pathname = pathnameInfo.pathname
if (pathnameInfo.basePath) {
req.url = removePathPrefix(req.url!, this.nextConfig.basePath)
}
const useMatchedPathHeader =
this.minimalMode && typeof req.headers[MATCHED_PATH_HEADER] === 'string'
// TODO: merge handling with invokePath
if (useMatchedPathHeader) {
try {
if (this.enabledDirectories.app) {
// ensure /index path is normalized for prerender
// in minimal mode
if (req.url.match(/^\/index($|\?)/)) {
req.url = req.url.replace(/^\/index/, '/')
}
parsedUrl.pathname =
parsedUrl.pathname === '/index' ? '/' : parsedUrl.pathname
}
// x-matched-path is the source of truth, it tells what page
// should be rendered because we don't process rewrites in minimalMode
let { pathname: matchedPath } = new URL(
fixMojibake(req.headers[MATCHED_PATH_HEADER] as string),
'http://localhost'
)
let { pathname: urlPathname } = new URL(req.url, 'http://localhost')
// For ISR the URL is normalized to the prerenderPath so if
// it's a data request the URL path will be the data URL,
// basePath is already stripped by this point
if (this.normalizers.data?.match(urlPathname)) {
addRequestMeta(req, 'isNextDataReq', true)
}
// In minimal mode, if PPR is enabled, then we should check to see if
// the request should be a resume request.
else if (
this.isAppPPREnabled &&
this.minimalMode &&
req.headers[NEXT_RESUME_HEADER] === '1' &&
req.method === 'POST'
) {
// Decode the postponed state from the request body, it will come as
// an array of buffers, so collect them and then concat them to form
// the string.
const body: Array<Buffer> = []
for await (const chunk of req.body) {
body.push(chunk)
}
const postponed = Buffer.concat(body).toString('utf8')
addRequestMeta(req, 'postponed', postponed)
}
matchedPath = this.normalize(matchedPath)
const normalizedUrlPath = this.stripNextDataPath(urlPathname)
matchedPath = denormalizePagePath(matchedPath)
// Perform locale detection and normalization.
const localeAnalysisResult = this.i18nProvider?.analyze(matchedPath, {
defaultLocale,
})
// The locale result will be defined even if the locale was not
// detected for the request because it will be inferred from the
// default locale.
if (localeAnalysisResult) {
addRequestMeta(req, 'locale', localeAnalysisResult.detectedLocale)
// If the detected locale was inferred from the default locale, we
// need to modify the metadata on the request to indicate that.
if (localeAnalysisResult.inferredFromDefault) {
addRequestMeta(req, 'localeInferredFromDefault', true)
} else {
removeRequestMeta(req, 'localeInferredFromDefault')
}
}
let srcPathname = matchedPath
let pageIsDynamic = isDynamicRoute(srcPathname)
let paramsResult: {
params: ParsedUrlQuery | false
hasValidParams: boolean
} = {
params: false,
hasValidParams: false,
}
if (!pageIsDynamic) {
const match = await this.matchers.match(srcPathname, {
i18n: localeAnalysisResult,
})
// Update the source pathname to the matched page's pathname.
if (match) {
srcPathname = match.definition.pathname
// The page is dynamic if the params are defined. We know at this
// stage that the matched path is not a static page if the params
// were parsed from the matched path header.
if (typeof match.params !== 'undefined') {
pageIsDynamic = true
paramsResult.params = match.params
paramsResult.hasValidParams = true
}
}
}
// The rest of this function can't handle i18n properly, so ensure we
// restore the pathname with the locale information stripped from it
// now that we're done matching if we're using i18n.
if (localeAnalysisResult) {
matchedPath = localeAnalysisResult.pathname
}
const utils = getServerUtils({
pageIsDynamic,
page: srcPathname,
i18n: this.nextConfig.i18n,
basePath: this.nextConfig.basePath,
rewrites: this.getRoutesManifest()?.rewrites || {
beforeFiles: [],
afterFiles: [],
fallback: [],
},
caseSensitive: !!this.nextConfig.experimental.caseSensitiveRoutes,
})
// Ensure parsedUrl.pathname includes locale before processing
// rewrites or they won't match correctly.
if (defaultLocale && !pathnameInfo.locale) {
parsedUrl.pathname = `/${defaultLocale}${parsedUrl.pathname}`
}
// Store a copy of `parsedUrl.query` before calling handleRewrites.
// Since `handleRewrites` might add new queries to `parsedUrl.query`.
const originQueryParams = { ...parsedUrl.query }
const pathnameBeforeRewrite = parsedUrl.pathname
const rewriteParamKeys = Object.keys(
utils.handleRewrites(req, parsedUrl)
)
// Create a copy of the query params to avoid mutating the original
// object. This prevents any overlapping query params that have the
// same normalized key from causing issues.
const queryParams = { ...parsedUrl.query }
const didRewrite = pathnameBeforeRewrite !== parsedUrl.pathname
if (didRewrite && parsedUrl.pathname) {
addRequestMeta(req, 'rewroteURL', parsedUrl.pathname)
}
const routeParamKeys = new Set<string>()
for (const [key, value] of Object.entries(parsedUrl.query)) {
const normalizedKey = normalizeNextQueryParam(key)
if (!normalizedKey) continue
// Remove the prefixed key from the query params because we want
// to consume it for the dynamic route matcher.
delete parsedUrl.query[key]
routeParamKeys.add(normalizedKey)
if (typeof value === 'undefined') continue
queryParams[normalizedKey] = Array.isArray(value)
? value.map((v) => decodeQueryPathParameter(v))
: decodeQueryPathParameter(value)
}
// interpolate dynamic params and normalize URL if needed
if (pageIsDynamic) {
let params: ParsedUrlQuery | false = {}
// If we don't already have valid params, try to parse them from
// the query params.
if (!paramsResult.hasValidParams) {
paramsResult = utils.normalizeDynamicRouteParams(
queryParams,
false
)
}
// for prerendered ISR paths we attempt parsing the route
// params from the URL directly as route-matches may not
// contain the correct values due to the filesystem path
// matching before the dynamic route has been matched
if (
!paramsResult.hasValidParams &&
!isDynamicRoute(normalizedUrlPath)
) {
let matcherParams = utils.dynamicRouteMatcher?.(normalizedUrlPath)
if (matcherParams) {
utils.normalizeDynamicRouteParams(matcherParams, false)
Object.assign(paramsResult.params, matcherParams)
paramsResult.hasValidParams = true
}
}
// if an action request is bypassing a prerender and we
// don't have the params in the URL since it was prerendered
// and matched during handle: 'filesystem' rather than dynamic route
// resolving we need to parse the params from the matched-path.
// Note: this is similar to above case but from match-path instead
// of from the request URL since a rewrite could cause that to not
// match the src pathname
if (
// we can have a collision with /index and a top-level /[slug]
matchedPath !== '/index' &&
!paramsResult.hasValidParams &&
!isDynamicRoute(matchedPath)
) {
let matcherParams = utils.dynamicRouteMatcher?.(matchedPath)
if (matcherParams) {
const curParamsResult = utils.normalizeDynamicRouteParams(
matcherParams,
false
)
if (curParamsResult.hasValidParams) {
Object.assign(params, matcherParams)
paramsResult = curParamsResult
}
}
}
if (paramsResult.hasValidParams) {
params = paramsResult.params
}
const routeMatchesHeader = req.headers['x-now-route-matches']
if (
typeof routeMatchesHeader === 'string' &&
routeMatchesHeader &&
isDynamicRoute(matchedPath) &&
!paramsResult.hasValidParams
) {
const routeMatches =
utils.getParamsFromRouteMatches(routeMatchesHeader)
if (routeMatches) {
paramsResult = utils.normalizeDynamicRouteParams(
routeMatches,
true
)
if (paramsResult.hasValidParams) {
params = paramsResult.params
}
}
}
// Try to parse the params from the query if we couldn't parse them
// from the route matches but ignore missing optional params.
if (!paramsResult.hasValidParams) {
paramsResult = utils.normalizeDynamicRouteParams(
queryParams,
true
)
if (paramsResult.hasValidParams) {
params = paramsResult.params
}
}
// If the pathname being requested is the same as the source
// pathname, and we don't have valid params, we want to use the
// default route matches.
if (
utils.defaultRouteMatches &&
normalizedUrlPath === srcPathname &&
!paramsResult.hasValidParams
) {
params = utils.defaultRouteMatches
// If the route matches header is an empty string, we want to
// render a fallback shell. This is because we know this came from
// a prerender (it has the header) but it's values were filtered
// out (because the allowQuery was empty). If it was undefined
// then we know that the request is hitting the lambda directly.
if (routeMatchesHeader === '') {
addRequestMeta(req, 'renderFallbackShell', true)
}
}
if (params) {
matchedPath = utils.interpolateDynamicPath(srcPathname, params)
req.url = utils.interpolateDynamicPath(req.url!, params)
// If the request is for a segment prefetch, we need to update the
// segment prefetch request path to include the interpolated
// params.
let segmentPrefetchRSCRequest = getRequestMeta(
req,
'segmentPrefetchRSCRequest'
)
if (
segmentPrefetchRSCRequest &&
isDynamicRoute(segmentPrefetchRSCRequest, false)
) {
segmentPrefetchRSCRequest = utils.interpolateDynamicPath(
segmentPrefetchRSCRequest,
params
)
req.headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER.toLowerCase()] =
segmentPrefetchRSCRequest
addRequestMeta(
req,
'segmentPrefetchRSCRequest',
segmentPrefetchRSCRequest
)
}
}
}
if (pageIsDynamic || didRewrite) {
utils.normalizeCdnUrl(req, [
...rewriteParamKeys,
...Object.keys(utils.defaultRouteRegex?.groups || {}),
])
}
// Remove the route `params` keys from `parsedUrl.query` if they are
// not in the original query params.
// If it's used in both route `params` and query `searchParams`, it should be kept.
for (const key of routeParamKeys) {
if (!(key in originQueryParams)) {
delete parsedUrl.query[key]
}
}
parsedUrl.pathname = matchedPath
url.pathname = parsedUrl.pathname
finished = await this.normalizeAndAttachMetadata(req, res, parsedUrl)
if (finished) return
} catch (err) {
if (err instanceof DecodeError || err instanceof NormalizeError) {
res.statusCode = 400
return this.renderError(null, req, res, '/_error', {})
}
throw err
}
}
addRequestMeta(req, 'isLocaleDomain', Boolean(domainLocale))
if (pathnameInfo.locale) {
req.url = formatUrl(url)
addRequestMeta(req, 'didStripLocale', true)
}
// If we aren't in minimal mode or there is no locale in the query
// string, add the locale to the query string.
if (!this.minimalMode || !getRequestMeta(req, 'locale')) {
// If the locale is in the pathname, add it to the query string.
if (pathnameInfo.locale) {
addRequestMeta(req, 'locale', pathnameInfo.locale)
}
// If the default locale is available, add it to the query string and
// mark it as inferred rather than implicit.
else if (defaultLocale) {
addRequestMeta(req, 'locale', defaultLocale)
addRequestMeta(req, 'localeInferredFromDefault', true)
}
}
// set incremental cache to request meta so it can
// be passed down for edge functions and the fetch disk
// cache can be leveraged locally
if (
!(this.serverOptions as any).webServerConfig &&
!getRequestMeta(req, 'incrementalCache')
) {
const incrementalCache = await this.getIncrementalCache({
requestHeaders: Object.assign({}, req.headers),
})
incrementalCache.resetRequestCache()
addRequestMeta(req, 'incrementalCache', incrementalCache)
// This is needed for pages router to leverage unstable_cache
// TODO: re-work this handling to not use global and use a AsyncStore
;(globalThis as any).__incrementalCache = incrementalCache
}
const cacheHandlers = getCacheHandlers()
if (cacheHandlers) {
await Promise.all(
[...cacheHandlers].map(async (cacheHandler) => {
if ('refreshTags' in cacheHandler) {
// Note: cacheHandler.refreshTags() is called lazily before the
// first cache entry is retrieved. It allows us to skip the
// refresh request if no caches are read at all.
} else {
const previouslyRevalidatedTags = getPreviouslyRevalidatedTags(
req.headers,
this.getPrerenderManifest().preview.previewModeId
)
await cacheHandler.receiveExpiredTags(
...previouslyRevalidatedTags
)
}
})
)
}
// set server components HMR cache to request meta so it can be passed
// down for edge functions
if (!getRequestMeta(req, 'serverComponentsHmrCache')) {
addRequestMeta(
req,
'serverComponentsHmrCache',
this.getServerComponentsHmrCache()
)
}
// when invokePath is specified we can short short circuit resolving
// we only honor this header if we are inside of a render worker to
// prevent external users coercing the routing path
const invokePath = getRequestMeta(req, 'invokePath')
const useInvokePath = !useMatchedPathHeader && invokePath
if (useInvokePath) {
const invokeStatus = getRequestMeta(req, 'invokeStatus')
if (invokeStatus) {
const invokeQuery = getRequestMeta(req, 'invokeQuery')
if (invokeQuery) {
Object.assign(parsedUrl.query, invokeQuery)
}
res.statusCode = invokeStatus
let err: Error | null = getRequestMeta(req, 'invokeError') || null
return this.renderError(err, req, res, '/_error', parsedUrl.query)
}
const parsedMatchedPath = new URL(invokePath || '/', 'http://n')
const invokePathnameInfo = getNextPathnameInfo(
parsedMatchedPath.pathname,
{
nextConfig: this.nextConfig,
parseData: false,
}
)
if (invokePathnameInfo.locale) {
addRequestMeta(req, 'locale', invokePathnameInfo.locale)
}
if (parsedUrl.pathname !== parsedMatchedPath.pathname) {
parsedUrl.pathname = parsedMatchedPath.pathname
addRequestMeta(req, 'rewroteURL', invokePathnameInfo.pathname)
}
const normalizeResult = normalizeLocalePath(
removePathPrefix(parsedUrl.pathname, this.nextConfig.basePath || ''),
this.nextConfig.i18n?.locales
)
if (normalizeResult.detectedLocale) {
addRequestMeta(req, 'locale', normalizeResult.detectedLocale)
}
parsedUrl.pathname = normalizeResult.pathname
for (const key of Object.keys(parsedUrl.query)) {
delete parsedUrl.query[key]
}
const invokeQuery = getRequestMeta(req, 'invokeQuery')
if (invokeQuery) {
Object.assign(parsedUrl.query, invokeQuery)
}
finished = await this.normalizeAndAttachMetadata(req, res, parsedUrl)
if (finished) return
await this.handleCatchallRenderRequest(req, res, parsedUrl)
return
}
if (getRequestMeta(req, 'middlewareInvoke')) {
finished = await this.normalizeAndAttachMetadata(req, res, parsedUrl)
if (finished) return
finished = await this.handleCatchallMiddlewareRequest(
req,
res,
parsedUrl
)
if (finished) return
const err = new Error()
;(err as any).result = {
response: new Response(null, {
headers: {
'x-middleware-next': '1',
},
}),
}
;(err as any).bubble = true
throw err
}
// This wasn't a request via the matched path or the invoke path, so
// prepare for a legacy run by removing the base path.
// ensure we strip the basePath when not using an invoke header
if (!useMatchedPathHeader && pathnameInfo.basePath) {
parsedUrl.pathname = removePathPrefix(
parsedUrl.pathname,
pathnameInfo.basePath
)
}
res.statusCode = 200
return await this.run(req, res, parsedUrl)
} catch (err: any) {
if (err instanceof NoFallbackError) {
throw err
}
if (
(err && typeof err === 'object' && err.code === 'ERR_INVALID_URL') ||
err instanceof DecodeError ||
err instanceof NormalizeError
) {
res.statusCode = 400
return this.renderError(null, req, res, '/_error', {})
}
if (
this.minimalMode ||
this.renderOpts.dev ||
(isBubbledError(err) && err.bubble)
) {
throw err
}
this.logError(getProperError(err))
res.statusCode = 500
res.body('Internal Server Error').send()
}
}
/**
* Normalizes a pathname without attaching any metadata from any matched
* normalizer.
*
* @param pathname the pathname to normalize
* @returns the normalized pathname
*/
private normalize = (pathname: string) => {
const normalizers: Array<PathnameNormalizer> = []
if (this.normalizers.data) {
normalizers.push(this.normalizers.data)
}
// We have to put the segment prefetch normalizer before the RSC normalizer
// because the RSC normalizer will match the prefetch RSC routes too.
if (this.normalizers.segmentPrefetchRSC) {
normalizers.push(this.normalizers.segmentPrefetchRSC)
}
// We have to put the prefetch normalizer before the RSC normalizer
// because the RSC normalizer will match the prefetch RSC routes too.
if (this.normalizers.prefetchRSC) {
normalizers.push(this.normalizers.prefetchRSC)
}
if (this.normalizers.rsc) {
normalizers.push(this.normalizers.rsc)
}
for (const normalizer of normalizers) {
if (!normalizer.match(pathname)) continue
return normalizer.normalize(pathname, true)
}
return pathname
}
private normalizeAndAttachMetadata: RouteHandler<
ServerRequest,
ServerResponse
> = async (req, res, url) => {
let finished = await this.handleNextImageRequest(req, res, url)
if (finished) return true
if (this.enabledDirectories.pages) {
finished = await this.handleNextDataRequest(req, res, url)
if (finished) return true
}
return false
}
/**
* @internal - this method is internal to Next.js and should not be used directly by end-users
*/
public getRequestHandlerWithMetadata(
meta: RequestMeta
): BaseRequestHandler<ServerRequest, ServerResponse> {
const handler = this.getRequestHandler()
return (req, res, parsedUrl) => {
setRequestMeta(req, meta)
return handler(req, res, parsedUrl)
}
}
public getRequestHandler(): BaseRequestHandler<
ServerRequest,
ServerResponse
> {
return this.handleRequest.bind(this)
}
protected abstract handleUpgrade(
req: ServerRequest,
socket: any,
head?: any
): Promise<void>
public setAssetPrefix(prefix?: string): void {
this.renderOpts.assetPrefix = prefix ? prefix.replace(/\/$/, '') : ''
}
protected prepared: boolean = false
protected preparedPromise: Promise<void> | null = null
/**
* Runs async initialization of server.
* It is idempotent, won't fire underlying initialization more than once.
*/
public async prepare(): Promise<void> {
if (this.prepared) return
// Get instrumentation module
if (!this.instrumentation) {
this.instrumentation = await this.loadInstrumentationModule()
}
if (this.preparedPromise === null) {
this.preparedPromise = this.prepareImpl().then(() => {
this.prepared = true
this.preparedPromise = null
})
}
return this.preparedPromise
}
protected async prepareImpl(): Promise<void> {}
protected async loadInstrumentationModule(): Promise<any> {}
public async close(): Promise<void> {}
protected getAppPathRoutes(): Record<string, string[]> {
const appPathRoutes: Record<string, string[]> = {}
Object.keys(this.appPathsManifest || {}).forEach((entry) => {
const normalizedPath = normalizeAppPath(entry)
if (!appPathRoutes[normalizedPath]) {
appPathRoutes[normalizedPath] = []
}
appPathRoutes[normalizedPath].push(entry)
})
return appPathRoutes
}
protected async run(
req: ServerRequest,
res: ServerResponse,
parsedUrl: UrlWithParsedQuery
): Promise<void> {
return getTracer().trace(BaseServerSpan.run, async () =>
this.runImpl(req, res, parsedUrl)
)
}
private async runImpl(
req: ServerRequest,
res: ServerResponse,
parsedUrl: UrlWithParsedQuery
): Promise<void> {
await this.handleCatchallRenderRequest(req, res, parsedUrl)
}
private async pipe(
fn: (
ctx: RequestContext<ServerRequest, ServerResponse>
) => Promise<ResponsePayload | null>,
partialContext: Omit<
RequestContext<ServerRequest, ServerResponse>,
'renderOpts'
>
): Promise<void> {
return getTracer().trace(BaseServerSpan.pipe, async () =>
this.pipeImpl(fn, partialContext)
)
}
private async pipeImpl(
fn: (
ctx: RequestContext<ServerRequest, ServerResponse>
) => Promise<ResponsePayload | null>,
partialContext: Omit<
RequestContext<ServerRequest, ServerResponse>,
'renderOpts'
>
): Promise<void> {
const ua = partialContext.req.headers['user-agent'] || ''
const ctx: RequestContext<ServerRequest, ServerResponse> = {
...partialContext,
renderOpts: {
...this.renderOpts,
// `renderOpts.botType` is accumulated in `this.renderImpl()`
supportsDynamicResponse: !this.renderOpts.botType,
serveStreamingMetadata: shouldServeStreamingMetadata(
ua,
this.nextConfig.htmlLimitedBots
),
},
}
const payload = await fn(ctx)
if (payload === null) {
return
}
const { req, res } = ctx
const originalStatus = res.statusCode
const { body } = payload
let { cacheControl } = payload
if (!res.sent) {
const { generateEtags, poweredByHeader, dev } = this.renderOpts
// In dev, we should not cache pages for any reason.
if (dev) {
res.setHeader('Cache-Control', 'no-store, must-revalidate')
cacheControl = undefined
}
if (cacheControl && cacheControl.expire === undefined) {
cacheControl.expire = this.nextConfig.expireTime
}
await this.sendRenderResult(req, res, {
result: body,
generateEtags,
poweredByHeader,
cacheControl,
})
res.statusCode = originalStatus
}
}
private async getStaticHTML(
fn: (
ctx: RequestContext<ServerRequest, ServerResponse>
) => Promise<ResponsePayload | null>,
partialContext: Omit<
RequestContext<ServerRequest, ServerResponse>,
'renderOpts'
>
): Promise<string | null> {
const ctx: RequestContext<ServerRequest, ServerResponse> = {
...partialContext,
renderOpts: {
...this.renderOpts,
supportsDynamicResponse: false,
},
}
const payload = await fn(ctx)
if (payload === null) {
return null
}
return payload.body.toUnchunkedString()
}
public async render(
req: ServerRequest,
res: ServerResponse,
pathname: string,
query: NextParsedUrlQuery = {},
parsedUrl?: NextUrlWithParsedQuery,
internalRender = false
): Promise<void> {
return getTracer().trace(BaseServerSpan.render, async () =>
this.renderImpl(req, res, pathname, query, parsedUrl, internalRender)
)
}
protected getWaitUntil(): WaitUntil | undefined {
const builtinRequestContext = getBuiltinRequestContext()
if (builtinRequestContext) {
// the platform provided a request context.
// use the `waitUntil` from there, whether actually present or not --
// if not present, `after` will error.
// NOTE: if we're in an edge runtime sandbox, this context will be used to forward the outer waitUntil.
return builtinRequestContext.waitUntil
}
if (this.minimalMode) {
// we're built for a serverless environment, and `waitUntil` is not available,
// but using a noop would likely lead to incorrect behavior,
// because we have no way of keeping the invocation alive.
// return nothing, and `after` will error if used.
//
// NOTE: for edge functions, `NextWebServer` always runs in minimal mode.
//
// NOTE: if we're in an edge runtime sandbox, waitUntil will be passed in using "@next/request-context",
// so we won't get here.
return undefined
}
return this.getInternalWaitUntil()
}
protected getInternalWaitUntil(): WaitUntil | undefined {
return undefined
}
private async renderImpl(
req: ServerRequest,
res: ServerResponse,
pathname: string,
query: NextParsedUrlQuery = {},
parsedUrl?: NextUrlWithParsedQuery,
internalRender = false
): Promise<void> {
if (!pathname.startsWith('/')) {
console.warn(
`Cannot render page with path "${pathname}", did you mean "/${pathname}"?. See more info here: https://nextjs.org/docs/messages/render-no-starting-slash`
)
}
if (
this.serverOptions.customServer &&
pathname === '/index' &&
!(await this.hasPage('/index'))
) {
// maintain backwards compatibility for custom server
// (see custom-server integration tests)
pathname = '/'
}
const ua = req.headers['user-agent'] || ''
this.renderOpts.botType = getBotType(ua)
// we allow custom servers to call render for all URLs
// so check if we need to serve a static _next file or not.
// we don't modify the URL for _next/data request but still
// call render so we special case this to prevent an infinite loop
if (
!internalRender &&
!this.minimalMode &&
!getRequestMeta(req, 'isNextDataReq') &&
(req.url?.match(/^\/_next\//) ||
(this.hasStaticDir && req.url!.match(/^\/static\//)))
) {
return this.handleRequest(req, res, parsedUrl)
}
if (isBlockedPage(pathname)) {
return this.render404(req, res, parsedUrl)
}
return this.pipe((ctx) => this.renderToResponse(ctx), {
req,
res,
pathname,
query,
})
}
protected async getStaticPaths({
pathname,
}: {
pathname: string
urlPathname: string
requestHeaders: import('./lib/incremental-cache').IncrementalCache['requestHeaders']
page: string
isAppPath: boolean
}): Promise<{
staticPaths?: string[]
fallbackMode?: FallbackMode
}> {
// Read whether or not fallback should exist from the manifest.
const fallbackField =
this.getPrerenderManifest().dynamicRoutes[pathname]?.fallback
return {
// `staticPaths` is intentionally set to `undefined` as it should've
// been caught when checking disk data.
staticPaths: undefined,
fallbackMode: parseFallbackField(fallbackField),
}
}
private async renderToResponseWithComponents(
requestContext: RequestContext<ServerRequest, ServerResponse>,
findComponentsResult: FindComponentsResult
): Promise<ResponsePayload | null> {
return getTracer().trace(
BaseServerSpan.renderToResponseWithComponents,
async () =>
this.renderToResponseWithComponentsImpl(
requestContext,
findComponentsResult
)
)
}
protected pathCouldBeIntercepted(resolvedPathname: string): boolean {
return (
isInterceptionRouteAppPath(resolvedPathname) ||
this.interceptionRoutePatterns.some((regexp) => {
return regexp.test(resolvedPathname)
})
)
}
protected setVaryHeader(
req: ServerRequest,
res: ServerResponse,
isAppPath: boolean,
resolvedPathname: string
): void {
const baseVaryHeader = `${RSC_HEADER}, ${NEXT_ROUTER_STATE_TREE_HEADER}, ${NEXT_ROUTER_PREFETCH_HEADER}, ${NEXT_ROUTER_SEGMENT_PREFETCH_HEADER}`
const isRSCRequest = getRequestMeta(req, 'isRSCRequest') ?? false
let addedNextUrlToVary = false
if (isAppPath && this.pathCouldBeIntercepted(resolvedPathname)) {
// Interception route responses can vary based on the `Next-URL` header.
// We use the Vary header to signal this behavior to the client to properly cache the response.
res.appendHeader('vary', `${baseVaryHeader}, ${NEXT_URL}`)
addedNextUrlToVary = true
} else if (isAppPath || isRSCRequest) {
// We don't need to include `Next-URL` in the Vary header for non-interception routes since it won't affect the response.
// We also set this header for pages to avoid caching issues when navigating between pages and app.
res.appendHeader('vary', baseVaryHeader)
}
if (!addedNextUrlToVary) {
// Remove `Next-URL` from the request headers we determined it wasn't necessary to include in the Vary header.
// This is to avoid any dependency on the `Next-URL` header being present when preparing the response.
delete req.headers[NEXT_URL]
}
}
private async renderToResponseWithComponentsImpl(
{
req,
res,
pathname,
renderOpts: opts,
}: RequestContext<ServerRequest, ServerResponse>,
{ components, query }: FindComponentsResult
): Promise<ResponsePayload | null> {
if (pathname === UNDERSCORE_NOT_FOUND_ROUTE) {
pathname = '/404'
}
const isErrorPathname = pathname === '/_error'
const is404Page =
pathname === '/404' || (isErrorPathname && res.statusCode === 404)
const is500Page =
pathname === '/500' || (isErrorPathname && res.statusCode === 500)
const isAppPath = components.isAppPath === true
const hasServerProps = !!components.getServerSideProps
const isPossibleServerAction = getIsPossibleServerAction(req)
let isSSG = !!components.getStaticProps
// NOTE: Don't delete headers[RSC] yet, it still needs to be used in renderToHTML later
const isRSCRequest = getRequestMeta(req, 'isRSCRequest') ?? false
// Not all CDNs respect the Vary header when caching. We must assume that
// only the URL is used to vary the responses. The Next client computes a
// hash of the header values and sends it as a search param. Before
// responding to a request, we must verify that the hash matches the
// expected value. Neglecting to do this properly can lead to cache
// poisoning attacks on certain CDNs.
if (
!this.minimalMode &&
this.nextConfig.experimental.validateRSCRequestHeaders &&
isRSCRequest
) {
const headers = req.headers
const expectedHash = computeCacheBustingSearchParam(
headers[NEXT_ROUTER_PREFETCH_HEADER.toLowerCase()],
headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER.toLowerCase()],
headers[NEXT_ROUTER_STATE_TREE_HEADER.toLowerCase()],
headers[NEXT_URL.toLowerCase()]
)
const actualHash =
getRequestMeta(req, 'cacheBustingSearchParam') ??
new URL(req.url || '', 'http://localhost').searchParams.get(
NEXT_RSC_UNION_QUERY
)
if (expectedHash !== actualHash) {
// The hash sent by the client does not match the expected value.
// Redirect to the URL with the correct cache-busting search param.
// This prevents cache poisoning attacks on CDNs that don't respect Vary headers.
// Note: When no headers are present, expectedHash is empty string and client
// must send `_rsc` param, otherwise actualHash is null and hash check fails.
const url = new URL(req.url || '', 'http://localhost')
setCacheBustingSearchParamWithHash(url, expectedHash)
res.statusCode = 307
res.setHeader('location', `${url.pathname}${url.search}`)
res.body('').send()
return null
}
}
// Compute the iSSG cache key. We use the rewroteUrl since
// pages with fallback: false are allowed to be rewritten to
// and we need to look up the path by the rewritten path
let urlPathname = parseUrl(req.url || '').pathname || '/'
let resolvedUrlPathname = getRequestMeta(req, 'rewroteURL') || urlPathname
this.setVaryHeader(req, res, isAppPath, resolvedUrlPathname)
let staticPaths: string[] | undefined
let hasFallback = false
const prerenderManifest = this.getPrerenderManifest()
if (
hasFallback ||
staticPaths?.includes(resolvedUrlPathname) ||
// this signals revalidation in deploy environments
// TODO: make this more generic
req.headers['x-now-route-matches']
) {
isSSG = true
} else if (!this.renderOpts.dev) {
isSSG ||= !!prerenderManifest.routes[toRoute(pathname)]
}
// Toggle whether or not this is a Data request
const isNextDataRequest =
!!(
getRequestMeta(req, 'isNextDataReq') ||
(req.headers['x-nextjs-data'] &&
(this.serverOptions as any).webServerConfig)
) &&
(isSSG || hasServerProps)
// when we are handling a middleware prefetch and it doesn't
// resolve to a static data route we bail early to avoid
// unexpected SSR invocations
if (
!isSSG &&
req.headers['x-middleware-prefetch'] &&
!(is404Page || pathname === '/_error')
) {
res.setHeader(MATCHED_PATH_HEADER, pathname)
res.setHeader('x-middleware-skip', '1')
res.setHeader(
'cache-control',
'private, no-cache, no-store, max-age=0, must-revalidate'
)
res.body('{}').send()
return null
}
// normalize req.url for SSG paths as it is not exposed
// to getStaticProps and the asPath should not expose /_next/data
if (
isSSG &&
this.minimalMode &&
req.headers[MATCHED_PATH_HEADER] &&
req.url.startsWith('/_next/data')
) {
req.url = this.stripNextDataPath(req.url)
}
const locale = getRequestMeta(req, 'locale')
if (
!!req.headers['x-nextjs-data'] &&
(!res.statusCode || res.statusCode === 200)
) {
res.setHeader(
'x-nextjs-matched-path',
`${locale ? `/${locale}` : ''}${pathname}`
)
}
let routeModule: RouteModule | undefined
if (components.routeModule) {
routeModule = components.routeModule
}
/**
* 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 =
this.isAppPPREnabled &&
typeof routeModule !== 'undefined' &&
isAppPageRouteModule(routeModule)
// 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
// 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[pathname] ??
prerenderManifest.dynamicRoutes[pathname]
)?.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 &&
(this.renderOpts.dev === true ||
this.experimentalTestProxy === true)))
// 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
? getRequestMeta(req, 'postponed')
: undefined
// we need to ensure the status code if /404 is visited directly
if (is404Page && !isNextDataRequest && !isRSCRequest) {
res.statusCode = 404
}
// ensure correct status is set when visiting a status page
// directly e.g. /500
if (STATIC_STATUS_PAGES.includes(pathname)) {
res.statusCode = parseInt(pathname.slice(1), 10)
}
if (
// Server actions can use non-GET/HEAD methods.
!isPossibleServerAction &&
// Resume can use non-GET/HEAD methods.
!minimalPostponed &&
!is404Page &&
!is500Page &&
pathname !== '/_error' &&
req.method !== 'HEAD' &&
req.method !== 'GET' &&
(typeof components.Component === 'string' || isSSG)
) {
res.statusCode = 405
res.setHeader('Allow', ['GET', 'HEAD'])
res.body('Method Not Allowed').send()
return null
}
// handle static page
if (typeof components.Component === 'string') {
return {
body: RenderResult.fromStatic(
components.Component,
HTML_CONTENT_TYPE_HEADER
),
}
}
// Ensure that if the `amp` query parameter is falsy that we remove it from
// the query object. This ensures it won't be found by the `in` operator.
if ('amp' in query && !query.amp) delete query.amp
if (opts.supportsDynamicResponse === true) {
const ua = req.headers['user-agent'] || ''
const isBotRequest = isBot(ua)
const isSupportedDocument =
typeof components.Document?.getInitialProps !== 'function' ||
// The built-in `Document` component also supports dynamic HTML for concurrent mode.
NEXT_BUILTIN_DOCUMENT in components.Document
// Disable dynamic HTML in cases that we know it won't be generated,
// so that we can continue generating a cache key when possible.
// TODO-APP: should the first render for a dynamic app path
// be static so we can collect revalidate and populate the
// cache if there are no dynamic data requirements
opts.supportsDynamicResponse =
!isSSG && !isBotRequest && !query.amp && isSupportedDocument
}
// In development, we always want to generate dynamic HTML.
if (!isNextDataRequest && isAppPath && opts.dev) {
opts.supportsDynamicResponse = true
}
if (isSSG && this.minimalMode && req.headers[MATCHED_PATH_HEADER]) {
// the url value is already correct when the matched-path header is set
resolvedUrlPathname = urlPathname
}
urlPathname = removeTrailingSlash(urlPathname)
resolvedUrlPathname = removeTrailingSlash(resolvedUrlPathname)
if (this.localeNormalizer) {
resolvedUrlPathname = this.localeNormalizer.normalize(resolvedUrlPathname)
}
// remove /_next/data prefix from urlPathname so it matches
// for direct page visit and /_next/data visit
if (isNextDataRequest) {
resolvedUrlPathname = this.stripNextDataPath(resolvedUrlPathname)
urlPathname = this.stripNextDataPath(urlPathname)
}
// use existing incrementalCache instance if available
const incrementalCache: import('./lib/incremental-cache').IncrementalCache =
await this.getIncrementalCache({
requestHeaders: Object.assign({}, req.headers),
})
// TODO: investigate, this is not safe across multiple concurrent requests
incrementalCache.resetRequestCache()
if (
routeModule?.isDev &&
isDynamicRoute(pathname) &&
(components.getStaticPaths || isAppPath)
) {
await this.getStaticPaths({
pathname,
urlPathname,
requestHeaders: req.headers,
page: components.page,
isAppPath,
})
}
// An OPTIONS request to a page handler is invalid.
if (
req.method === 'OPTIONS' &&
!is404Page &&
(!routeModule || !isAppRouteRouteModule(routeModule))
) {
await sendResponse(req, res, new Response(null, { status: 400 }))
return null
}
const request = isNodeNextRequest(req) ? req.originalRequest : req
const response = isNodeNextResponse(res) ? res.originalResponse : res
const parsedInitUrl = parseUrl(getRequestMeta(req, 'initURL') || req.url)
let initPathname = parsedInitUrl.pathname || '/'
for (const normalizer of [
this.normalizers.segmentPrefetchRSC,
this.normalizers.prefetchRSC,
this.normalizers.rsc,
]) {
if (normalizer?.match(initPathname)) {
initPathname = normalizer.normalize(initPathname)
}
}
request.url = `${initPathname}${parsedInitUrl.search || ''}`
// propagate the request context for dev
setRequestMeta(request, getRequestMeta(req))
addRequestMeta(request, 'distDir', this.distDir)
addRequestMeta(request, 'query', query)
addRequestMeta(request, 'params', opts.params)
addRequestMeta(request, 'ampValidator', this.renderOpts.ampValidator)
addRequestMeta(request, 'minimalMode', this.minimalMode)
if (opts.err) {
addRequestMeta(request, 'invokeError', opts.err)
}
const handler: (
req: ServerRequest | IncomingMessage,
res: ServerResponse | HTTPServerResponse,
ctx: {
waitUntil: ReturnType<Server['getWaitUntil']>
}
) => Promise<void> = components.ComponentMod.handler
const maybeDevRequest =
// we need to capture fetch metrics when they are set
// and can't wait for handler to resolve as the fetch
// metrics are logged on response close which happens
// before handler resolves
process.env.NODE_ENV === 'development'
? new Proxy(request, {
get(target: any, prop) {
if (typeof target[prop] === 'function') {
return target[prop].bind(target)
}
return target[prop]
},
set(target: any, prop, value) {
if (prop === 'fetchMetrics') {
;(req as any).fetchMetrics = value
}
target[prop] = value
return true
},
})
: request
await handler(maybeDevRequest, response, {
waitUntil: this.getWaitUntil(),
})
// response is handled fully in handler
return null
}
private stripNextDataPath(path: string, stripLocale = true) {
if (path.includes(this.buildId)) {
const splitPath = path.substring(
path.indexOf(this.buildId) + this.buildId.length
)
path = denormalizePagePath(splitPath.replace(/\.json$/, ''))
}
if (this.localeNormalizer && stripLocale) {
return this.localeNormalizer.normalize(path)
}
return path
}
// map the route to the actual bundle name
protected getOriginalAppPaths(route: string) {
if (this.enabledDirectories.app) {
const originalAppPath = this.appPathRoutes?.[route]
if (!originalAppPath) {
return null
}
return originalAppPath
}
return null
}
protected async renderPageComponent(
ctx: RequestContext<ServerRequest, ServerResponse>,
bubbleNoFallback: boolean
) {
const { query, pathname } = ctx
const appPaths = this.getOriginalAppPaths(pathname)
const isAppPath = Array.isArray(appPaths)
let page = pathname
if (isAppPath) {
// the last item in the array is the root page, if there are parallel routes
page = appPaths[appPaths.length - 1]
}
const result = await this.findPageComponents({
locale: getRequestMeta(ctx.req, 'locale'),
page,
query,
params: ctx.renderOpts.params || {},
isAppPath,
sriEnabled: !!this.nextConfig.experimental.sri?.algorithm,
appPaths,
// Ensuring for loading page component routes is done via the matcher.
shouldEnsure: false,
})
if (result) {
getTracer().setRootSpanAttribute('next.route', pathname)
try {
return await this.renderToResponseWithComponents(ctx, result)
} catch (err) {
const isNoFallbackError = err instanceof NoFallbackError
if (!isNoFallbackError || (isNoFallbackError && bubbleNoFallback)) {
throw err
}
}
}
return false
}
private async renderToResponse(
ctx: RequestContext<ServerRequest, ServerResponse>
): Promise<ResponsePayload | null> {
return getTracer().trace(
BaseServerSpan.renderToResponse,
{
spanName: `rendering page`,
attributes: {
'next.route': ctx.pathname,
},
},
async () => {
return this.renderToResponseImpl(ctx)
}
)
}
protected abstract getMiddleware(): Promise<MiddlewareRoutingItem | undefined>
protected abstract getFallbackErrorComponents(
url?: string
): Promise<LoadComponentsReturnType | null>
protected abstract getRoutesManifest(): NormalizedRouteManifest | undefined
private async renderToResponseImpl(
ctx: RequestContext<ServerRequest, ServerResponse>
): Promise<ResponsePayload | null> {
const { req, res, query, pathname } = ctx
let page = pathname
const bubbleNoFallback =
getRequestMeta(ctx.req, 'bubbleNoFallback') ?? false
if (
!this.minimalMode &&
this.nextConfig.experimental.validateRSCRequestHeaders
) {
addRequestMeta(
ctx.req,
'cacheBustingSearchParam',
query[NEXT_RSC_UNION_QUERY]
)
}
delete query[NEXT_RSC_UNION_QUERY]
const options: MatchOptions = {
i18n: this.i18nProvider?.fromRequest(req, pathname),
}
try {
for await (const match of this.matchers.matchAll(pathname, options)) {
// when a specific invoke-output is meant to be matched
// ensure a prior dynamic route/page doesn't take priority
const invokeOutput = getRequestMeta(ctx.req, 'invokeOutput')
if (
!this.minimalMode &&
typeof invokeOutput === 'string' &&
isDynamicRoute(invokeOutput || '') &&
invokeOutput !== match.definition.pathname
) {
continue
}
const result = await this.renderPageComponent(
{
...ctx,
pathname: match.definition.pathname,
renderOpts: {
...ctx.renderOpts,
params: match.params,
},
},
bubbleNoFallback
)
if (result !== false) return result
}
// currently edge functions aren't receiving the x-matched-path
// header so we need to fallback to matching the current page
// when we weren't able to match via dynamic route to handle
// the rewrite case
// @ts-expect-error extended in child class web-server
if (this.serverOptions.webServerConfig) {
// @ts-expect-error extended in child class web-server
ctx.pathname = this.serverOptions.webServerConfig.page
const result = await this.renderPageComponent(ctx, bubbleNoFallback)
if (result !== false) return result
}
} catch (error) {
const err = getProperError(error)
if (error instanceof MissingStaticPage) {
console.error(
'Invariant: failed to load static page',
JSON.stringify(
{
page,
url: ctx.req.url,
matchedPath: ctx.req.headers[MATCHED_PATH_HEADER],
initUrl: getRequestMeta(ctx.req, 'initURL'),
didRewrite: !!getRequestMeta(ctx.req, 'rewroteURL'),
rewroteUrl: getRequestMeta(ctx.req, 'rewroteURL'),
},
null,
2
)
)
throw err
}
if (err instanceof NoFallbackError && bubbleNoFallback) {
throw err
}
if (err instanceof DecodeError || err instanceof NormalizeError) {
res.statusCode = 400
return await this.renderErrorToResponse(ctx, err)
}
res.statusCode = 500
// if pages/500 is present we still need to trigger
// /_error `getInitialProps` to allow reporting error
if (await this.hasPage('/500')) {
addRequestMeta(ctx.req, 'customErrorRender', true)
await this.renderErrorToResponse(ctx, err)
removeRequestMeta(ctx.req, 'customErrorRender')
}
const isWrappedError = err instanceof WrappedBuildError
if (!isWrappedError) {
if (this.minimalMode || this.renderOpts.dev) {
if (isError(err)) err.page = page
throw err
}
this.logError(getProperError(err))
}
const response = await this.renderErrorToResponse(
ctx,
isWrappedError ? (err as WrappedBuildError).innerError : err
)
return response
}
const middleware = await this.getMiddleware()
if (
middleware &&
!!ctx.req.headers['x-nextjs-data'] &&
(!res.statusCode || res.statusCode === 200 || res.statusCode === 404)
) {
const locale = getRequestMeta(req, 'locale')
res.setHeader(
'x-nextjs-matched-path',
`${locale ? `/${locale}` : ''}${pathname}`
)
res.statusCode = 200
res.setHeader('Content-Type', JSON_CONTENT_TYPE_HEADER)
res.body('{}')
res.send()
return null
}
res.statusCode = 404
return this.renderErrorToResponse(ctx, null)
}
public async renderToHTML(
req: ServerRequest,
res: ServerResponse,
pathname: string,
query: ParsedUrlQuery = {}
): Promise<string | null> {
return getTracer().trace(BaseServerSpan.renderToHTML, async () => {
return this.renderToHTMLImpl(req, res, pathname, query)
})
}
private async renderToHTMLImpl(
req: ServerRequest,
res: ServerResponse,
pathname: string,
query: ParsedUrlQuery = {}
): Promise<string | null> {
return this.getStaticHTML((ctx) => this.renderToResponse(ctx), {
req,
res,
pathname,
query,
})
}
public async renderError(
err: Error | null,
req: ServerRequest,
res: ServerResponse,
pathname: string,
query: NextParsedUrlQuery = {},
setHeaders = true
): Promise<void> {
return getTracer().trace(BaseServerSpan.renderError, async () => {
return this.renderErrorImpl(err, req, res, pathname, query, setHeaders)
})
}
private async renderErrorImpl(
err: Error | null,
req: ServerRequest,
res: ServerResponse,
pathname: string,
query: NextParsedUrlQuery = {},
setHeaders = true
): Promise<void> {
if (setHeaders) {
res.setHeader(
'Cache-Control',
'private, no-cache, no-store, max-age=0, must-revalidate'
)
}
return this.pipe(
async (ctx) => {
const response = await this.renderErrorToResponse(ctx, err)
if (this.minimalMode && res.statusCode === 500) {
throw err
}
return response
},
{ req, res, pathname, query }
)
}
private customErrorNo404Warn = execOnce(() => {
Log.warn(
`You have added a custom /_error page without a custom /404 page. This prevents the 404 page from being auto statically optimized.\nSee here for info: https://nextjs.org/docs/messages/custom-error-no-custom-404`
)
})
private async renderErrorToResponse(
ctx: RequestContext<ServerRequest, ServerResponse>,
err: Error | null
): Promise<ResponsePayload | null> {
return getTracer().trace(BaseServerSpan.renderErrorToResponse, async () => {
return this.renderErrorToResponseImpl(ctx, err)
})
}
protected async renderErrorToResponseImpl(
ctx: RequestContext<ServerRequest, ServerResponse>,
err: Error | null
): Promise<ResponsePayload | null> {
// Short-circuit favicon.ico in development to avoid compiling 404 page when the app has no favicon.ico.
// Since favicon.ico is automatically requested by the browser.
if (this.renderOpts.dev && ctx.pathname === '/favicon.ico') {
return {
body: RenderResult.EMPTY,
}
}
const { res, query } = ctx
try {
let result: null | FindComponentsResult = null
const is404 = res.statusCode === 404
let using404Page = false
if (is404) {
if (this.enabledDirectories.app) {
// Use the not-found entry in app directory
result = await this.findPageComponents({
locale: getRequestMeta(ctx.req, 'locale'),
page: UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,
query,
params: {},
isAppPath: true,
shouldEnsure: true,
url: ctx.req.url,
})
using404Page = result !== null
}
if (!result && (await this.hasPage('/404'))) {
result = await this.findPageComponents({
locale: getRequestMeta(ctx.req, 'locale'),
page: '/404',
query,
params: {},
isAppPath: false,
// Ensuring can't be done here because you never "match" a 404 route.
shouldEnsure: true,
url: ctx.req.url,
})
using404Page = result !== null
}
}
let statusPage = `/${res.statusCode}`
if (
!getRequestMeta(ctx.req, 'customErrorRender') &&
!result &&
STATIC_STATUS_PAGES.includes(statusPage)
) {
// skip ensuring /500 in dev mode as it isn't used and the
// dev overlay is used instead
if (statusPage !== '/500' || !this.renderOpts.dev) {
result = await this.findPageComponents({
locale: getRequestMeta(ctx.req, 'locale'),
page: statusPage,
query,
params: {},
isAppPath: false,
// Ensuring can't be done here because you never "match" a 500
// route.
shouldEnsure: true,
url: ctx.req.url,
})
}
}
if (!result) {
result = await this.findPageComponents({
locale: getRequestMeta(ctx.req, 'locale'),
page: '/_error',
query,
params: {},
isAppPath: false,
// Ensuring can't be done here because you never "match" an error
// route.
shouldEnsure: true,
url: ctx.req.url,
})
statusPage = '/_error'
}
if (
process.env.NODE_ENV !== 'production' &&
!using404Page &&
(await this.hasPage('/_error')) &&
!(await this.hasPage('/404'))
) {
this.customErrorNo404Warn()
}
if (!result) {
// this can occur when a project directory has been moved/deleted
// which is handled in the parent process in development
if (this.renderOpts.dev) {
return {
// wait for dev-server to restart before refreshing
body: RenderResult.fromStatic(
`
<pre>missing required error components, refreshing...</pre>
<script>
async function check() {
const res = await fetch(location.href).catch(() => ({}))
if (res.status === 200) {
location.reload()
} else {
setTimeout(check, 1000)
}
}
check()
</script>`,
HTML_CONTENT_TYPE_HEADER
),
}
}
throw new WrappedBuildError(
new Error('missing required error components')
)
}
// If the page has a route module, use it for the new match. If it doesn't
// have a route module, remove the match.
if (result.components.routeModule) {
addRequestMeta(ctx.req, 'match', {
definition: result.components.routeModule.definition,
params: undefined,
})
} else {
removeRequestMeta(ctx.req, 'match')
}
try {
return await this.renderToResponseWithComponents(
{
...ctx,
pathname: statusPage,
renderOpts: {
...ctx.renderOpts,
err,
},
},
result
)
} catch (maybeFallbackError) {
if (maybeFallbackError instanceof NoFallbackError) {
throw new Error('invariant: failed to render error page')
}
throw maybeFallbackError
}
} catch (error) {
const renderToHtmlError = getProperError(error)
const isWrappedError = renderToHtmlError instanceof WrappedBuildError
if (!isWrappedError) {
this.logError(renderToHtmlError)
}
res.statusCode = 500
const fallbackComponents = await this.getFallbackErrorComponents(
ctx.req.url
)
if (fallbackComponents) {
// There was an error, so use it's definition from the route module
// to add the match to the request.
addRequestMeta(ctx.req, 'match', {
definition: fallbackComponents.routeModule!.definition,
params: undefined,
})
return this.renderToResponseWithComponents(
{
...ctx,
pathname: '/_error',
renderOpts: {
...ctx.renderOpts,
// We render `renderToHtmlError` here because `err` is
// already captured in the stacktrace.
err: isWrappedError
? renderToHtmlError.innerError
: renderToHtmlError,
},
},
{
query,
components: fallbackComponents,
}
)
}
return {
body: RenderResult.fromStatic('Internal Server Error', 'text/plain'),
}
}
}
public async renderErrorToHTML(
err: Error | null,
req: ServerRequest,
res: ServerResponse,
pathname: string,
query: ParsedUrlQuery = {}
): Promise<string | null> {
return this.getStaticHTML((ctx) => this.renderErrorToResponse(ctx, err), {
req,
res,
pathname,
query,
})
}
public async render404(
req: ServerRequest,
res: ServerResponse,
parsedUrl?: Pick<NextUrlWithParsedQuery, 'pathname' | 'query'>,
setHeaders = true
): Promise<void> {
const { pathname, query } = parsedUrl ? parsedUrl : parseUrl(req.url!, true)
// Ensure the locales are provided on the request meta.
if (this.nextConfig.i18n) {
if (!getRequestMeta(req, 'locale')) {
addRequestMeta(req, 'locale', this.nextConfig.i18n.defaultLocale)
}
addRequestMeta(req, 'defaultLocale', this.nextConfig.i18n.defaultLocale)
}
res.statusCode = 404
return this.renderError(null, req, res, pathname!, query, setHeaders)
}
}
|