Unverified Commit aed2dc0c authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Add handling for static generation in app (#40561)



x-ref: [internal notes](https://www.notion.so/vercel/App-Static-Generation-dc5f1e0916684501b586e56a5b7b9483)
parent 4a53582e
This diff is collapsed.
This diff is collapsed.
...@@ -81,6 +81,7 @@ export function getRender({ ...@@ -81,6 +81,7 @@ export function getRender({
getServerSideProps: pageMod.getServerSideProps, getServerSideProps: pageMod.getServerSideProps,
getStaticPaths: pageMod.getStaticPaths, getStaticPaths: pageMod.getStaticPaths,
ComponentMod: pageMod, ComponentMod: pageMod,
pathname,
} }
} }
...@@ -94,6 +95,7 @@ export function getRender({ ...@@ -94,6 +95,7 @@ export function getRender({
getServerSideProps: error500Mod.getServerSideProps, getServerSideProps: error500Mod.getServerSideProps,
getStaticPaths: error500Mod.getStaticPaths, getStaticPaths: error500Mod.getStaticPaths,
ComponentMod: error500Mod, ComponentMod: error500Mod,
pathname,
} }
} }
...@@ -106,6 +108,7 @@ export function getRender({ ...@@ -106,6 +108,7 @@ export function getRender({
getServerSideProps: errorMod.getServerSideProps, getServerSideProps: errorMod.getServerSideProps,
getStaticPaths: errorMod.getStaticPaths, getStaticPaths: errorMod.getStaticPaths,
ComponentMod: errorMod, ComponentMod: errorMod,
pathname,
} }
} }
......
export * from './utils' export * from './utils'
export { default as exportPage } from '../export/worker' import exportPage from '../export/worker'
export { exportPage }
// @ts-expect-error createServerContext exists on experimental channel // @ts-expect-error createServerContext exists on experimental channel
import { createServerContext } from 'react' import { createServerContext } from 'react'
export class DynamicServerError extends Error {
constructor(type: string) {
super(`Dynamic server usage: ${type}`)
}
}
// Ensure serverContext is not created more than once as React will throw when creating it more than once // Ensure serverContext is not created more than once as React will throw when creating it more than once
// https://github.com/facebook/react/blob/dd2d6522754f52c70d02c51db25eb7cbd5d1c8eb/packages/react/src/ReactServerContext.js#L101 // https://github.com/facebook/react/blob/dd2d6522754f52c70d02c51db25eb7cbd5d1c8eb/packages/react/src/ReactServerContext.js#L101
const createContext = (name: string) => { const createContext = <T>(name: string, defaultValue: T | null = null) => {
// @ts-expect-error __NEXT_DEV_SERVER_CONTEXT__ is a global // @ts-expect-error __NEXT_DEV_SERVER_CONTEXT__ is a global
if (!global.__NEXT_DEV_SERVER_CONTEXT__) { if (!global.__NEXT_DEV_SERVER_CONTEXT__) {
// @ts-expect-error __NEXT_DEV_SERVER_CONTEXT__ is a global // @ts-expect-error __NEXT_DEV_SERVER_CONTEXT__ is a global
...@@ -13,13 +19,30 @@ const createContext = (name: string) => { ...@@ -13,13 +19,30 @@ const createContext = (name: string) => {
// @ts-expect-error __NEXT_DEV_SERVER_CONTEXT__ is a global // @ts-expect-error __NEXT_DEV_SERVER_CONTEXT__ is a global
if (!global.__NEXT_DEV_SERVER_CONTEXT__[name]) { if (!global.__NEXT_DEV_SERVER_CONTEXT__[name]) {
// @ts-expect-error __NEXT_DEV_SERVER_CONTEXT__ is a global // @ts-expect-error __NEXT_DEV_SERVER_CONTEXT__ is a global
global.__NEXT_DEV_SERVER_CONTEXT__[name] = createServerContext(name, null) global.__NEXT_DEV_SERVER_CONTEXT__[name] = createServerContext(
name,
defaultValue
)
} }
// @ts-expect-error __NEXT_DEV_SERVER_CONTEXT__ is a global // @ts-expect-error __NEXT_DEV_SERVER_CONTEXT__ is a global
return global.__NEXT_DEV_SERVER_CONTEXT__[name] return global.__NEXT_DEV_SERVER_CONTEXT__[name]
} }
export const HeadersContext = createContext('HeadersContext') export const CONTEXT_NAMES = {
export const PreviewDataContext = createContext('PreviewDataContext') HeadersContext: 'HeadersContext',
export const CookiesContext = createContext('CookiesContext') PreviewDataContext: 'PreviewDataContext',
CookiesContext: 'CookiesContext',
StaticGenerationContext: 'StaticGenerationContext',
FetchRevalidateContext: 'FetchRevalidateContext',
} as const
export const HeadersContext = createContext(CONTEXT_NAMES.HeadersContext)
export const PreviewDataContext = createContext(
CONTEXT_NAMES.PreviewDataContext
)
export const CookiesContext = createContext(CONTEXT_NAMES.CookiesContext)
export const StaticGenerationContext = createContext(
CONTEXT_NAMES.StaticGenerationContext,
{ isStaticGeneration: false }
)
...@@ -3,16 +3,37 @@ import { ...@@ -3,16 +3,37 @@ import {
HeadersContext, HeadersContext,
PreviewDataContext, PreviewDataContext,
CookiesContext, CookiesContext,
DynamicServerError,
StaticGenerationContext,
} from './hooks-server-context' } from './hooks-server-context'
export function useTrackStaticGeneration() {
return useContext<
typeof import('./hooks-server-context').StaticGenerationContext
>(StaticGenerationContext)
}
function useStaticGenerationBailout(reason: string) {
const staticGenerationContext = useTrackStaticGeneration()
if (staticGenerationContext.isStaticGeneration) {
// TODO: honor the dynamic: 'force-static'
staticGenerationContext.revalidate = 0
throw new DynamicServerError(reason)
}
}
export function useHeaders() { export function useHeaders() {
useStaticGenerationBailout('useHeaders')
return useContext(HeadersContext) return useContext(HeadersContext)
} }
export function usePreviewData() { export function usePreviewData() {
useStaticGenerationBailout('usePreviewData')
return useContext(PreviewDataContext) return useContext(PreviewDataContext)
} }
export function useCookies() { export function useCookies() {
useStaticGenerationBailout('useCookies')
return useContext(CookiesContext) return useContext(CookiesContext)
} }
...@@ -22,6 +22,8 @@ import { ...@@ -22,6 +22,8 @@ import {
CLIENT_STATIC_FILES_PATH, CLIENT_STATIC_FILES_PATH,
EXPORT_DETAIL, EXPORT_DETAIL,
EXPORT_MARKER, EXPORT_MARKER,
FLIGHT_MANIFEST,
FLIGHT_SERVER_CSS_MANIFEST,
PAGES_MANIFEST, PAGES_MANIFEST,
PHASE_EXPORT, PHASE_EXPORT,
PRERENDER_MANIFEST, PRERENDER_MANIFEST,
...@@ -386,6 +388,7 @@ export default async function exportApp( ...@@ -386,6 +388,7 @@ export default async function exportApp(
nextScriptWorkers: nextConfig.experimental.nextScriptWorkers, nextScriptWorkers: nextConfig.experimental.nextScriptWorkers,
optimizeFonts: nextConfig.optimizeFonts as FontConfig, optimizeFonts: nextConfig.optimizeFonts as FontConfig,
largePageDataBytes: nextConfig.experimental.largePageDataBytes, largePageDataBytes: nextConfig.experimental.largePageDataBytes,
serverComponents: nextConfig.experimental.serverComponents,
} }
const { serverRuntimeConfig, publicRuntimeConfig } = nextConfig const { serverRuntimeConfig, publicRuntimeConfig } = nextConfig
...@@ -404,15 +407,31 @@ export default async function exportApp( ...@@ -404,15 +407,31 @@ export default async function exportApp(
} }
const exportPathMap = await nextExportSpan const exportPathMap = await nextExportSpan
.traceChild('run-export-path-map') .traceChild('run-export-path-map')
.traceAsyncFn(() => .traceAsyncFn(async () => {
nextConfig.exportPathMap(defaultPathMap, { const exportMap = await nextConfig.exportPathMap(defaultPathMap, {
dev: false, dev: false,
dir, dir,
outDir, outDir,
distDir, distDir,
buildId, buildId,
}) })
) return exportMap
})
if (options.buildExport && nextConfig.experimental.appDir) {
// @ts-expect-error untyped
renderOpts.serverComponentManifest = require(join(
distDir,
SERVER_DIRECTORY,
`${FLIGHT_MANIFEST}.json`
)) as PagesManifest
// @ts-expect-error untyped
renderOpts.serverCSSManifest = require(join(
distDir,
SERVER_DIRECTORY,
FLIGHT_SERVER_CSS_MANIFEST + '.json'
)) as PagesManifest
}
// only add missing 404 page when `buildExport` is false // only add missing 404 page when `buildExport` is false
if (!options.buildExport) { if (!options.buildExport) {
......
...@@ -27,6 +27,7 @@ import { setHttpAgentOptions } from '../server/config' ...@@ -27,6 +27,7 @@ import { setHttpAgentOptions } from '../server/config'
import RenderResult from '../server/render-result' import RenderResult from '../server/render-result'
import isError from '../lib/is-error' import isError from '../lib/is-error'
import { addRequestMeta } from '../server/request-meta' import { addRequestMeta } from '../server/request-meta'
import { normalizeAppPath } from '../shared/lib/router/utils/app-paths'
loadRequireHook() loadRequireHook()
const envConfig = require('../shared/lib/runtime-config') const envConfig = require('../shared/lib/runtime-config')
...@@ -104,7 +105,6 @@ export default async function exportPage({ ...@@ -104,7 +105,6 @@ export default async function exportPage({
pathMap, pathMap,
distDir, distDir,
outDir, outDir,
appPaths,
pagesDataDir, pagesDataDir,
renderOpts, renderOpts,
buildExport, buildExport,
...@@ -129,6 +129,7 @@ export default async function exportPage({ ...@@ -129,6 +129,7 @@ export default async function exportPage({
try { try {
const { query: originalQuery = {} } = pathMap const { query: originalQuery = {} } = pathMap
const { page } = pathMap const { page } = pathMap
const isAppDir = (pathMap as any)._isAppDir
const filePath = normalizePagePath(path) const filePath = normalizePagePath(path)
const isDynamic = isDynamicRoute(page) const isDynamic = isDynamicRoute(page)
const ampPath = `${filePath}.amp` const ampPath = `${filePath}.amp`
...@@ -136,6 +137,9 @@ export default async function exportPage({ ...@@ -136,6 +137,9 @@ export default async function exportPage({
let query = { ...originalQuery } let query = { ...originalQuery }
let params: { [key: string]: string | string[] } | undefined let params: { [key: string]: string | string[] } | undefined
if (isAppDir) {
outDir = join(distDir, 'server/app')
}
let updatedPath = query.__nextSsgPath || path let updatedPath = query.__nextSsgPath || path
let locale = query.__nextLocale || renderOpts.locale let locale = query.__nextLocale || renderOpts.locale
delete query.__nextLocale delete query.__nextLocale
...@@ -172,7 +176,11 @@ export default async function exportPage({ ...@@ -172,7 +176,11 @@ export default async function exportPage({
).pathname ).pathname
if (isDynamic && page !== nonLocalizedPath) { if (isDynamic && page !== nonLocalizedPath) {
params = getRouteMatcher(getRouteRegex(page))(updatedPath) || undefined const normalizedPage = isAppDir ? normalizeAppPath(page) : page
params =
getRouteMatcher(getRouteRegex(normalizedPage))(updatedPath) ||
undefined
if (params) { if (params) {
// we have to pass these separately for serverless // we have to pass these separately for serverless
if (!serverless) { if (!serverless) {
...@@ -272,9 +280,6 @@ export default async function exportPage({ ...@@ -272,9 +280,6 @@ export default async function exportPage({
return !buildExport && getStaticProps && !isDynamicRoute(path) return !buildExport && getStaticProps && !isDynamicRoute(path)
} }
const isAppPath = appPaths.some((appPath: string) =>
appPath.startsWith(page + '.page')
)
if (serverless) { if (serverless) {
const curUrl = url.parse(req.url!, true) const curUrl = url.parse(req.url!, true)
req.url = url.format({ req.url = url.format({
...@@ -295,7 +300,7 @@ export default async function exportPage({ ...@@ -295,7 +300,7 @@ export default async function exportPage({
pathname: page, pathname: page,
serverless, serverless,
hasServerComponents: !!serverComponents, hasServerComponents: !!serverComponents,
isAppPath, isAppPath: isAppDir,
}) })
const ampState = { const ampState = {
ampFirst: pageConfig?.amp === true, ampFirst: pageConfig?.amp === true,
...@@ -362,8 +367,66 @@ export default async function exportPage({ ...@@ -362,8 +367,66 @@ export default async function exportPage({
pathname: page, pathname: page,
serverless, serverless,
hasServerComponents: !!serverComponents, hasServerComponents: !!serverComponents,
isAppPath, isAppPath: isAppDir,
}) })
curRenderOpts = {
...components,
...renderOpts,
ampPath: renderAmpPath,
params,
optimizeFonts,
optimizeCss,
disableOptimizedLoading,
fontManifest: optimizeFonts
? requireFontManifest(distDir, serverless)
: null,
locale: locale as string,
}
// during build we attempt rendering app dir paths
// and bail when dynamic dependencies are detected
// only fully static paths are fully generated here
if (isAppDir) {
const {
DynamicServerError,
} = require('../client/components/hooks-server-context')
const { renderToHTMLOrFlight } =
require('../server/app-render') as typeof import('../server/app-render')
try {
curRenderOpts.params ||= {}
const result = await renderToHTMLOrFlight(
req as any,
res as any,
page,
query,
curRenderOpts as any,
false,
true
)
const html = result?.toUnchunkedString()
const flightData = (curRenderOpts as any).pageData
const revalidate = (curRenderOpts as any).revalidate
results.fromBuildExportRevalidate = revalidate
if (revalidate !== 0) {
await promises.writeFile(htmlFilepath, html, 'utf8')
await promises.writeFile(
htmlFilepath.replace(/\.html$/, '.rsc'),
flightData
)
}
} catch (err) {
if (!(err instanceof DynamicServerError)) {
throw err
}
}
return { ...results, duration: Date.now() - start }
}
const ampState = { const ampState = {
ampFirst: components.pageConfig?.amp === true, ampFirst: components.pageConfig?.amp === true,
hasQuery: Boolean(query.amp), hasQuery: Boolean(query.amp),
...@@ -407,19 +470,6 @@ export default async function exportPage({ ...@@ -407,19 +470,6 @@ export default async function exportPage({
if (optimizeCss) { if (optimizeCss) {
process.env.__NEXT_OPTIMIZE_CSS = JSON.stringify(true) process.env.__NEXT_OPTIMIZE_CSS = JSON.stringify(true)
} }
curRenderOpts = {
...components,
...renderOpts,
ampPath: renderAmpPath,
params,
optimizeFonts,
optimizeCss,
disableOptimizedLoading,
fontManifest: optimizeFonts
? requireFontManifest(distDir, serverless)
: null,
locale: locale as string,
}
renderResult = await renderMethod( renderResult = await renderMethod(
req, req,
res, res,
......
This diff is collapsed.
...@@ -913,9 +913,14 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -913,9 +913,14 @@ export default abstract class Server<ServerOptions extends Options = Options> {
}) })
} }
protected async getStaticPaths(pathname: string): Promise<{ protected async getStaticPaths({
staticPaths: string[] | undefined pathname,
fallbackMode: 'static' | 'blocking' | false }: {
pathname: string
originalAppPath?: string
}): Promise<{
staticPaths?: string[]
fallbackMode?: 'static' | 'blocking' | false
}> { }> {
// `staticPaths` is intentionally set to `undefined` as it should've // `staticPaths` is intentionally set to `undefined` as it should've
// been caught when checking disk data. // been caught when checking disk data.
...@@ -923,7 +928,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -923,7 +928,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
// Read whether or not fallback should exist from the manifest. // Read whether or not fallback should exist from the manifest.
const fallbackField = const fallbackField =
this.getPrerenderManifest().dynamicRoutes[pathname].fallback this.getPrerenderManifest().dynamicRoutes[pathname]?.fallback
return { return {
staticPaths, staticPaths,
...@@ -932,7 +937,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -932,7 +937,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
? 'static' ? 'static'
: fallbackField === null : fallbackField === null
? 'blocking' ? 'blocking'
: false, : fallbackField,
} }
} }
...@@ -942,15 +947,17 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -942,15 +947,17 @@ export default abstract class Server<ServerOptions extends Options = Options> {
): Promise<ResponsePayload | null> { ): Promise<ResponsePayload | null> {
const is404Page = pathname === '/404' const is404Page = pathname === '/404'
const is500Page = pathname === '/500' const is500Page = pathname === '/500'
const isAppPath = components.isAppPath
const isLikeServerless = const isLikeServerless =
typeof components.ComponentMod === 'object' && typeof components.ComponentMod === 'object' &&
typeof (components.ComponentMod as any).renderReqToHTML === 'function' typeof (components.ComponentMod as any).renderReqToHTML === 'function'
const hasServerProps = !!components.getServerSideProps const hasServerProps = !!components.getServerSideProps
const hasStaticPaths = !!components.getStaticPaths let hasStaticPaths = !!components.getStaticPaths
const hasGetInitialProps = !!components.Component?.getInitialProps const hasGetInitialProps = !!components.Component?.getInitialProps
const isServerComponent = !!components.ComponentMod?.__next_rsc__ const isServerComponent = !!components.ComponentMod?.__next_rsc__
const isSSG = let isSSG =
!!components.getStaticProps || !!components.getStaticProps ||
// For static server component pages, we currently always consider them // For static server component pages, we currently always consider them
// as SSG since we also need to handle the next data (flight JSON). // as SSG since we also need to handle the next data (flight JSON).
...@@ -970,6 +977,37 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -970,6 +977,37 @@ export default abstract class Server<ServerOptions extends Options = Options> {
delete query.__nextDataReq delete query.__nextDataReq
// 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, '_nextRewroteUrl') || urlPathname
let staticPaths: string[] | undefined
let fallbackMode: false | undefined | 'blocking' | 'static'
if (isAppPath) {
const pathsResult = await this.getStaticPaths({
pathname,
originalAppPath: components.pathname,
})
staticPaths = pathsResult.staticPaths
fallbackMode = pathsResult.fallbackMode
const hasFallback = typeof fallbackMode !== 'undefined'
if (hasFallback) {
hasStaticPaths = true
}
if (hasFallback || staticPaths?.includes(resolvedUrlPathname)) {
isSSG = true
}
}
// normalize req.url for SSG paths as it is not exposed // normalize req.url for SSG paths as it is not exposed
// to getStaticProps and the asPath should not expose /_next/data // to getStaticProps and the asPath should not expose /_next/data
if ( if (
...@@ -1049,6 +1087,9 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1049,6 +1087,9 @@ export default abstract class Server<ServerOptions extends Options = Options> {
// Disable dynamic HTML in cases that we know it won't be generated, // Disable dynamic HTML in cases that we know it won't be generated,
// so that we can continue generating a cache key when possible. // 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.supportsDynamicHTML = opts.supportsDynamicHTML =
!isSSG && !isSSG &&
!isLikeServerless && !isLikeServerless &&
...@@ -1085,14 +1126,6 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1085,14 +1126,6 @@ export default abstract class Server<ServerOptions extends Options = Options> {
checkIsManualRevalidate(req, this.renderOpts.previewProps)) checkIsManualRevalidate(req, this.renderOpts.previewProps))
} }
// 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, '_nextRewroteUrl') || urlPathname
if (isSSG && this.minimalMode && req.headers['x-matched-path']) { if (isSSG && this.minimalMode && req.headers['x-matched-path']) {
// the url value is already correct when the matched-path header is set // the url value is already correct when the matched-path header is set
resolvedUrlPathname = urlPathname resolvedUrlPathname = urlPathname
...@@ -1248,6 +1281,10 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1248,6 +1281,10 @@ export default abstract class Server<ServerOptions extends Options = Options> {
: resolvedUrl, : resolvedUrl,
} }
if (isSSG || hasStaticPaths) {
renderOpts.supportsDynamicHTML = false
}
const renderResult = await this.renderHTML( const renderResult = await this.renderHTML(
req, req,
res, res,
...@@ -1285,9 +1322,11 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1285,9 +1322,11 @@ export default abstract class Server<ServerOptions extends Options = Options> {
const isDynamicPathname = isDynamicRoute(pathname) const isDynamicPathname = isDynamicRoute(pathname)
const didRespond = hasResolved || res.sent const didRespond = hasResolved || res.sent
let { staticPaths, fallbackMode } = hasStaticPaths if (!staticPaths) {
? await this.getStaticPaths(pathname) ;({ staticPaths, fallbackMode } = hasStaticPaths
: { staticPaths: undefined, fallbackMode: false } ? await this.getStaticPaths({ pathname })
: { staticPaths: undefined, fallbackMode: false })
}
if ( if (
fallbackMode === 'static' && fallbackMode === 'static' &&
...@@ -1536,9 +1575,10 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1536,9 +1575,10 @@ export default abstract class Server<ServerOptions extends Options = Options> {
const { query, pathname } = ctx const { query, pathname } = ctx
const appPaths = this.getOriginalAppPaths(pathname) const appPaths = this.getOriginalAppPaths(pathname)
const isAppPath = Array.isArray(appPaths)
let page = pathname let page = pathname
if (Array.isArray(appPaths)) { if (isAppPath) {
// When it's an array, we need to pass all parallel routes to the loader. // When it's an array, we need to pass all parallel routes to the loader.
page = appPaths[0] page = appPaths[0]
} }
...@@ -1547,7 +1587,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -1547,7 +1587,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
pathname: page, pathname: page,
query, query,
params: ctx.renderOpts.params || {}, params: ctx.renderOpts.params || {},
isAppPath: Array.isArray(appPaths), isAppPath,
appPaths, appPaths,
sriEnabled: !!this.nextConfig.experimental.sri?.algorithm, sriEnabled: !!this.nextConfig.experimental.sri?.algorithm,
}) })
......
...@@ -1263,9 +1263,15 @@ export default class DevServer extends Server { ...@@ -1263,9 +1263,15 @@ export default class DevServer extends Server {
return !snippet.includes('data-amp-development-mode-only') return !snippet.includes('data-amp-development-mode-only')
} }
protected async getStaticPaths(pathname: string): Promise<{ protected async getStaticPaths({
staticPaths: string[] | undefined pathname,
fallbackMode: false | 'static' | 'blocking' originalAppPath,
}: {
pathname: string
originalAppPath?: string
}): Promise<{
staticPaths?: string[]
fallbackMode?: false | 'static' | 'blocking'
}> { }> {
// we lazy load the staticPaths to prevent the user // we lazy load the staticPaths to prevent the user
// from waiting on them for the page to load in dev mode // from waiting on them for the page to load in dev mode
...@@ -1279,20 +1285,22 @@ export default class DevServer extends Server { ...@@ -1279,20 +1285,22 @@ export default class DevServer extends Server {
} = this.nextConfig } = this.nextConfig
const { locales, defaultLocale } = this.nextConfig.i18n || {} const { locales, defaultLocale } = this.nextConfig.i18n || {}
const paths = await this.getStaticPathsWorker().loadStaticPaths( const pathsResult = await this.getStaticPathsWorker().loadStaticPaths({
this.distDir, distDir: this.distDir,
pathname, pathname,
!this.renderOpts.dev && this._isLikeServerless, serverless: !this.renderOpts.dev && this._isLikeServerless,
{ config: {
configFileName, configFileName,
publicRuntimeConfig, publicRuntimeConfig,
serverRuntimeConfig, serverRuntimeConfig,
}, },
httpAgentOptions, httpAgentOptions,
locales, locales,
defaultLocale defaultLocale,
) originalAppPath,
return paths isAppPath: !!originalAppPath,
})
return pathsResult
} }
const { paths: staticPaths, fallback } = ( const { paths: staticPaths, fallback } = (
await withCoalescedInvoke(__getStaticPaths)(`staticPaths-${pathname}`, []) await withCoalescedInvoke(__getStaticPaths)(`staticPaths-${pathname}`, [])
...@@ -1305,7 +1313,7 @@ export default class DevServer extends Server { ...@@ -1305,7 +1313,7 @@ export default class DevServer extends Server {
? 'blocking' ? 'blocking'
: fallback === true : fallback === true
? 'static' ? 'static'
: false, : fallback,
} }
} }
......
import type { GetStaticPaths } from 'next/types'
import type { NextConfigComplete } from '../config-shared' import type { NextConfigComplete } from '../config-shared'
import type { UnwrapPromise } from '../../lib/coalesced-function'
import '../node-polyfill-fetch' import '../node-polyfill-fetch'
import { buildStaticPaths } from '../../build/utils' import {
buildAppStaticPaths,
buildStaticPaths,
collectGenerateParams,
} from '../../build/utils'
import { loadComponents } from '../load-components' import { loadComponents } from '../load-components'
import { setHttpAgentOptions } from '../config' import { setHttpAgentOptions } from '../config'
...@@ -14,20 +16,31 @@ let workerWasUsed = false ...@@ -14,20 +16,31 @@ let workerWasUsed = false
// we call getStaticPaths in a separate process to ensure // we call getStaticPaths in a separate process to ensure
// side-effects aren't relied on in dev that will break // side-effects aren't relied on in dev that will break
// during a production build // during a production build
export async function loadStaticPaths( export async function loadStaticPaths({
distDir: string, distDir,
pathname: string, pathname,
serverless: boolean, serverless,
config: RuntimeConfig, config,
httpAgentOptions: NextConfigComplete['httpAgentOptions'], httpAgentOptions,
locales?: string[], locales,
defaultLocale,
isAppPath,
originalAppPath,
}: {
distDir: string
pathname: string
serverless: boolean
config: RuntimeConfig
httpAgentOptions: NextConfigComplete['httpAgentOptions']
locales?: string[]
defaultLocale?: string defaultLocale?: string
): Promise< isAppPath?: boolean
Omit<UnwrapPromise<ReturnType<GetStaticPaths>>, 'paths'> & { originalAppPath?: string
paths: string[] }): Promise<{
encodedPaths: string[] paths?: string[]
} encodedPaths?: string[]
> { fallback?: boolean | 'blocking'
}> {
// we only want to use each worker once to prevent any invalid // we only want to use each worker once to prevent any invalid
// caches // caches
if (workerWasUsed) { if (workerWasUsed) {
...@@ -40,26 +53,35 @@ export async function loadStaticPaths( ...@@ -40,26 +53,35 @@ export async function loadStaticPaths(
const components = await loadComponents({ const components = await loadComponents({
distDir, distDir,
pathname, pathname: originalAppPath || pathname,
serverless, serverless,
hasServerComponents: false, hasServerComponents: false,
isAppPath: false, isAppPath: !!isAppPath,
}) })
if (!components.getStaticPaths) { if (!components.getStaticPaths && !isAppPath) {
// we shouldn't get to this point since the worker should // we shouldn't get to this point since the worker should
// only be called for SSG pages with getStaticPaths // only be called for SSG pages with getStaticPaths
throw new Error( throw new Error(
`Invariant: failed to load page with getStaticPaths for ${pathname}` `Invariant: failed to load page with getStaticPaths for ${pathname}`
) )
} }
workerWasUsed = true workerWasUsed = true
return buildStaticPaths(
pathname, if (isAppPath) {
components.getStaticPaths, const generateParams = collectGenerateParams(components.ComponentMod.tree)
config.configFileName, return buildAppStaticPaths({
page: pathname,
generateParams,
configFileName: config.configFileName,
})
}
return buildStaticPaths({
page: pathname,
getStaticPaths: components.getStaticPaths,
configFileName: config.configFileName,
locales, locales,
defaultLocale defaultLocale,
) })
} }
...@@ -7,11 +7,13 @@ export default class FileSystemCache implements CacheHandler { ...@@ -7,11 +7,13 @@ export default class FileSystemCache implements CacheHandler {
private flushToDisk?: CacheHandlerContext['flushToDisk'] private flushToDisk?: CacheHandlerContext['flushToDisk']
private serverDistDir: CacheHandlerContext['serverDistDir'] private serverDistDir: CacheHandlerContext['serverDistDir']
private memoryCache?: LRUCache<string, CacheHandlerValue> private memoryCache?: LRUCache<string, CacheHandlerValue>
private appDir: boolean
constructor(ctx: CacheHandlerContext) { constructor(ctx: CacheHandlerContext) {
this.fs = ctx.fs this.fs = ctx.fs
this.flushToDisk = ctx.flushToDisk this.flushToDisk = ctx.flushToDisk
this.serverDistDir = ctx.serverDistDir this.serverDistDir = ctx.serverDistDir
this.appDir = !!ctx._appDir
if (ctx.maxMemoryCacheSize) { if (ctx.maxMemoryCacheSize) {
this.memoryCache = new LRUCache({ this.memoryCache = new LRUCache({
...@@ -25,7 +27,9 @@ export default class FileSystemCache implements CacheHandler { ...@@ -25,7 +27,9 @@ export default class FileSystemCache implements CacheHandler {
throw new Error('invariant image should not be incremental-cache') throw new Error('invariant image should not be incremental-cache')
} }
// rough estimate of size of cache value // rough estimate of size of cache value
return value.html.length + JSON.stringify(value.pageData).length return (
value.html.length + (JSON.stringify(value.pageData)?.length || 0)
)
}, },
}) })
} }
...@@ -37,10 +41,22 @@ export default class FileSystemCache implements CacheHandler { ...@@ -37,10 +41,22 @@ export default class FileSystemCache implements CacheHandler {
// let's check the disk for seed data // let's check the disk for seed data
if (!data) { if (!data) {
try { try {
const htmlPath = this.getFsPath(`${key}.html`) const { filePath: htmlPath, isAppPath } = await this.getFsPath(
`${key}.html`
)
const html = await this.fs.readFile(htmlPath) const html = await this.fs.readFile(htmlPath)
const pageData = JSON.parse( const pageData = isAppPath
await this.fs.readFile(this.getFsPath(`${key}.json`)) ? await this.fs.readFile(
(
await this.getFsPath(`${key}.rsc`, true)
).filePath
)
: JSON.parse(
await this.fs.readFile(
await (
await this.getFsPath(`${key}.json`, false)
).filePath
)
) )
const { mtime } = await this.fs.stat(htmlPath) const { mtime } = await this.fs.stat(htmlPath)
...@@ -69,17 +85,52 @@ export default class FileSystemCache implements CacheHandler { ...@@ -69,17 +85,52 @@ export default class FileSystemCache implements CacheHandler {
}) })
if (data?.kind === 'PAGE') { if (data?.kind === 'PAGE') {
const htmlPath = this.getFsPath(`${key}.html`) const isAppPath = typeof data.pageData === 'string'
const { filePath: htmlPath } = await this.getFsPath(
`${key}.html`,
isAppPath
)
await this.fs.mkdir(path.dirname(htmlPath)) await this.fs.mkdir(path.dirname(htmlPath))
await this.fs.writeFile(htmlPath, data.html) await this.fs.writeFile(htmlPath, data.html)
await this.fs.writeFile( await this.fs.writeFile(
this.getFsPath(`${key}.json`), (
JSON.stringify(data.pageData) await this.getFsPath(
`${key}.${isAppPath ? 'rsc' : 'json'}`,
isAppPath
)
).filePath,
isAppPath ? data.pageData : JSON.stringify(data.pageData)
) )
} }
} }
private getFsPath(pathname: string): string { private async getFsPath(
return path.join(this.serverDistDir, 'pages', pathname) pathname: string,
appDir?: boolean
): Promise<{
filePath: string
isAppPath: boolean
}> {
let isAppPath = false
let filePath = path.join(this.serverDistDir, 'pages', pathname)
if (!this.appDir || appDir === false)
return {
filePath,
isAppPath,
}
try {
await this.fs.readFile(filePath)
return {
filePath,
isAppPath,
}
} catch (err) {
return {
filePath: path.join(this.serverDistDir, 'app', pathname),
isAppPath: true,
}
}
} }
} }
...@@ -18,6 +18,7 @@ export interface CacheHandlerContext { ...@@ -18,6 +18,7 @@ export interface CacheHandlerContext {
flushToDisk?: boolean flushToDisk?: boolean
serverDistDir: string serverDistDir: string
maxMemoryCacheSize?: number maxMemoryCacheSize?: number
_appDir?: boolean
} }
export interface CacheHandlerValue { export interface CacheHandlerValue {
...@@ -47,6 +48,7 @@ export class IncrementalCache { ...@@ -47,6 +48,7 @@ export class IncrementalCache {
constructor({ constructor({
fs, fs,
dev, dev,
appDir,
flushToDisk, flushToDisk,
serverDistDir, serverDistDir,
maxMemoryCacheSize, maxMemoryCacheSize,
...@@ -55,6 +57,7 @@ export class IncrementalCache { ...@@ -55,6 +57,7 @@ export class IncrementalCache {
}: { }: {
fs: CacheFs fs: CacheFs
dev: boolean dev: boolean
appDir?: boolean
serverDistDir: string serverDistDir: string
flushToDisk?: boolean flushToDisk?: boolean
maxMemoryCacheSize?: number maxMemoryCacheSize?: number
...@@ -80,6 +83,7 @@ export class IncrementalCache { ...@@ -80,6 +83,7 @@ export class IncrementalCache {
flushToDisk, flushToDisk,
serverDistDir, serverDistDir,
maxMemoryCacheSize, maxMemoryCacheSize,
_appDir: appDir,
}) })
} }
......
...@@ -40,6 +40,7 @@ export type LoadComponentsReturnType = { ...@@ -40,6 +40,7 @@ export type LoadComponentsReturnType = {
getServerSideProps?: GetServerSideProps getServerSideProps?: GetServerSideProps
ComponentMod: any ComponentMod: any
isAppPath?: boolean isAppPath?: boolean
pathname: string
} }
export async function loadDefaultErrorComponents(distDir: string) { export async function loadDefaultErrorComponents(distDir: string) {
...@@ -57,6 +58,7 @@ export async function loadDefaultErrorComponents(distDir: string) { ...@@ -57,6 +58,7 @@ export async function loadDefaultErrorComponents(distDir: string) {
buildManifest: require(join(distDir, `fallback-${BUILD_MANIFEST}`)), buildManifest: require(join(distDir, `fallback-${BUILD_MANIFEST}`)),
reactLoadableManifest: {}, reactLoadableManifest: {},
ComponentMod, ComponentMod,
pathname: '/_error',
} }
} }
...@@ -150,5 +152,6 @@ export async function loadComponents({ ...@@ -150,5 +152,6 @@ export async function loadComponents({
getStaticPaths, getStaticPaths,
serverComponentManifest, serverComponentManifest,
isAppPath, isAppPath,
pathname,
} }
} }
...@@ -287,6 +287,7 @@ export default class NextNodeServer extends BaseServer { ...@@ -287,6 +287,7 @@ export default class NextNodeServer extends BaseServer {
fs: this.getCacheFilesystem(), fs: this.getCacheFilesystem(),
dev, dev,
serverDistDir: this.serverDistDir, serverDistDir: this.serverDistDir,
appDir: this.nextConfig.experimental.appDir,
maxMemoryCacheSize: this.nextConfig.experimental.isrMemoryCacheSize, maxMemoryCacheSize: this.nextConfig.experimental.isrMemoryCacheSize,
flushToDisk: flushToDisk:
!this.minimalMode && this.nextConfig.experimental.isrFlushToDisk, !this.minimalMode && this.nextConfig.experimental.isrFlushToDisk,
......
...@@ -25,10 +25,10 @@ export function getPagePath( ...@@ -25,10 +25,10 @@ export function getPagePath(
distDir, distDir,
serverless && !dev ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY serverless && !dev ? SERVERLESS_DIRECTORY : SERVER_DIRECTORY
) )
let rootPathsManifest: undefined | PagesManifest let appPathsManifest: undefined | PagesManifest
if (appDirEnabled) { if (appDirEnabled) {
rootPathsManifest = require(join(serverBuildPath, APP_PATHS_MANIFEST)) appPathsManifest = require(join(serverBuildPath, APP_PATHS_MANIFEST))
} }
const pagesManifest = require(join( const pagesManifest = require(join(
serverBuildPath, serverBuildPath,
...@@ -58,8 +58,8 @@ export function getPagePath( ...@@ -58,8 +58,8 @@ export function getPagePath(
} }
let pagePath: string | undefined let pagePath: string | undefined
if (rootPathsManifest) { if (appPathsManifest) {
pagePath = checkManifest(rootPathsManifest) pagePath = checkManifest(appPathsManifest)
} }
if (!pagePath) { if (!pagePath) {
......
import Link from 'next/link' import Link from 'next/link'
import { experimental_use as use } from 'react'
export async function getServerSideProps() { async function getData() {
await new Promise((resolve) => setTimeout(resolve, 1000)) await new Promise((resolve) => setTimeout(resolve, 1000))
return { return {
props: { a: 'b' }, a: 'b',
} }
} }
export default function IdPage({ params }) { export default function IdPage({ params }) {
const data = use(getData())
console.log(data)
if (params.id === '123') { if (params.id === '123') {
return ( return (
<> <>
...@@ -24,3 +28,4 @@ export default function IdPage({ params }) { ...@@ -24,3 +28,4 @@ export default function IdPage({ params }) {
</> </>
) )
} }
//
export async function getServerSideProps() { import { experimental_use as use } from 'react'
async function getData() {
await new Promise((resolve) => setTimeout(resolve, 400)) await new Promise((resolve) => setTimeout(resolve, 400))
return { return {
props: {
message: 'Hello World', message: 'Hello World',
},
} }
} }
export default function DashboardLayout({ children, message }) {
export default function DashboardLayout({ children }) {
const { message } = use(getData())
return ( return (
<> <>
<h1 id="dashboard-layout">Dashboard {message}</h1> <h1 id="dashboard-layout">Dashboard {message}</h1>
......
export async function getServerSideProps() { import { experimental_use as use } from 'react'
async function getData() {
await new Promise((resolve) => setTimeout(resolve, 3000)) await new Promise((resolve) => setTimeout(resolve, 3000))
return { return {
props: {
message: 'Welcome to the dashboard', message: 'Welcome to the dashboard',
},
} }
} }
export default function DashboardPage({ message }) { export default function DashboardPage(props) {
const { message } = use(getData())
return ( return (
<> <>
<p id="dashboard-page">{message}</p> <p id="dashboard-page">{message}</p>
......
export const config = {
revalidate: 0,
}
export default function Root({ children }) { export default function Root({ children }) {
return ( return (
<html> <html>
......
export async function getServerSideProps() {
return {
props: {
message: 'hello from layout',
nowDuringExecution: Date.now(),
},
}
}
export default function gspLayout(props) {
return (
<>
<h1 id="layout-message">{props.message}</h1>
<p id="layout-now">{props.nowDuringExecution}</p>
{props.children}
</>
)
}
export async function getStaticProps() {
return {
props: {
message: 'hello from page',
nowDuringBuild: Date.now(),
},
}
}
export default function nestedPage(props) {
return (
<>
<p id="page-message">{props.message}</p>
<p id="page-now">{props.nowDuringBuild}</p>
</>
)
}
export async function getStaticProps() {
return {
props: {
message: 'hello from page',
now: Date.now(),
},
revalidate: 1,
}
}
export default function nestedPage(props) {
return (
<>
<p id="page-message">{props.message}</p>
<p id="page-now">{props.now}</p>
</>
)
}
export async function getStaticProps() {
return {
props: {
message: 'hello from page',
},
}
}
export default function nestedPage(props) {
return (
<>
<p id="page-message">{props.message}</p>
</>
)
}
export async function getStaticProps() { import { experimental_use as use } from 'react'
async function getData() {
return { return {
props: {
message: 'hello from layout', message: 'hello from layout',
now: Date.now(), now: Date.now(),
},
revalidate: 1,
} }
} }
export default function gspLayout(props) { export default function gspLayout(props) {
const data = use(getData())
return ( return (
<> <>
<h1 id="layout-message">{props.message}</h1> <h1 id="layout-message">{data.message}</h1>
<p id="layout-now">{props.now}</p> <p id="layout-now">{data.now}</p>
{props.children} {props.children}
</> </>
) )
......
import { experimental_use as use } from 'react'
export const config = {
revalidate: 1,
}
async function getData() {
return {
message: 'hello from page',
now: Date.now(),
}
}
export default function nestedPage(props) {
const data = use(getData())
return (
<>
<p id="page-message">{data.message}</p>
<p id="page-now">{data.now}</p>
</>
)
}
import { experimental_use as use } from 'react'
async function getData() {
return {
message: 'hello from layout',
nowDuringExecution: Date.now(),
}
}
export default function gspLayout(props) {
const data = use(getData())
return (
<>
<h1 id="layout-message">{data.message}</h1>
<p id="layout-now">{data.nowDuringExecution}</p>
{props.children}
</>
)
}
import { experimental_use as use } from 'react'
async function getData() {
return {
message: 'hello from page',
nowDuringBuild: Date.now(),
}
}
export default function nestedPage(props) {
const data = use(getData())
return (
<>
<p id="page-message">{data.message}</p>
<p id="page-now">{data.nowDuringBuild}</p>
</>
)
}
export async function getServerSideProps() { import { experimental_use as use } from 'react'
async function getData() {
await new Promise((resolve) => setTimeout(resolve, 5000)) await new Promise((resolve) => setTimeout(resolve, 5000))
return { return {
props: {
message: 'hello from slow layout', message: 'hello from slow layout',
nowDuringExecution: Date.now(), nowDuringExecution: Date.now(),
},
} }
} }
export default function gspLayout(props) { export default function gspLayout(props) {
const data = use(getData())
return ( return (
<> <>
<h1 id="slow-layout-message">{props.message}</h1> <h1 id="slow-layout-message">{data.message}</h1>
<p id="slow-layout-now">{props.nowDuringExecution}</p> <p id="slow-layout-now">{data.nowDuringExecution}</p>
{props.children} {props.children}
</> </>
) )
......
export async function getServerSideProps() { import { experimental_use as use } from 'react'
async function getData() {
await new Promise((resolve) => setTimeout(resolve, 5000)) await new Promise((resolve) => setTimeout(resolve, 5000))
return { return {
props: {
message: 'hello from slow page', message: 'hello from slow page',
}, nowDuringBuild: Date.now(),
} }
} }
export default function nestedPage(props) { export default function nestedPage(props) {
const data = use(getData())
return ( return (
<> <>
<p id="slow-page-message">{props.message}</p> <p id="slow-page-message">{data.message}</p>
<p id="slow-page-now">{data.nowDuringBuild}</p>
</> </>
) )
} }
export async function getServerSideProps() { import { experimental_use as use } from 'react'
export const config = {
revalidate: 0,
}
async function getData() {
return { return {
props: {
message: 'hello from layout', message: 'hello from layout',
},
} }
} }
export default function gsspLayout(props) { export default function gsspLayout(props) {
const data = use(getData())
return ( return (
<> <>
<h1 id="layout-message">{props.message}</h1> <h1 id="layout-message">{data.message}</h1>
{props.children} {props.children}
</> </>
) )
......
export async function getServerSideProps() { import { experimental_use as use } from 'react'
async function getData() {
return { return {
props: {
message: 'hello from page', message: 'hello from page',
},
} }
} }
export default function nestedPage(props) { export default function nestedPage(props) {
const data = use(getData())
return ( return (
<> <>
<p id="page-message">{props.message}</p> <p id="page-message">{data.message}</p>
</> </>
) )
} }
export async function getServerSideProps() { import { experimental_use as use } from 'react'
async function getData() {
await new Promise((resolve) => setTimeout(resolve, 5000)) await new Promise((resolve) => setTimeout(resolve, 5000))
return { return {
props: {
message: 'hello from slow layout', message: 'hello from slow layout',
},
} }
} }
export default function gsspLayout(props) { export default function gsspLayout(props) {
const data = use(getData())
return ( return (
<> <>
<h1 id="slow-layout-message">{props.message}</h1> <h1 id="slow-layout-message">{data.message}</h1>
{props.children} {props.children}
</> </>
) )
......
export async function getStaticProps() { import { experimental_use as use } from 'react'
async function getData() {
await new Promise((resolve) => setTimeout(resolve, 5000)) await new Promise((resolve) => setTimeout(resolve, 5000))
return { return {
props: {
message: 'hello from slow page', message: 'hello from slow page',
},
} }
} }
export default function nestedPage(props) { export default function nestedPage(props) {
const data = use(getData())
return ( return (
<> <>
<p id="slow-page-message">{props.message}</p> <p id="slow-page-message">{data.message}</p>
</> </>
) )
} }
export async function getStaticProps() { import { experimental_use as use } from 'react'
async function getData() {
return { return {
props: {
message: 'hello from layout', message: 'hello from layout',
},
} }
} }
export default function gspLayout(props) { export default function gspLayout(props) {
const data = use(getData())
return ( return (
<> <>
<h1 id="layout-message">{props.message}</h1> <h1 id="layout-message">{data.message}</h1>
{props.children} {props.children}
</> </>
) )
......
import { experimental_use as use } from 'react'
export const config = {
revalidate: false,
}
async function getData() {
return {
message: 'hello from page',
}
}
export default function nestedPage(props) {
const data = use(getData())
return (
<>
<p id="page-message">{data.message}</p>
</>
)
}
export async function getStaticProps() { import { experimental_use as use } from 'react'
async function getData() {
await new Promise((resolve) => setTimeout(resolve, 5000)) await new Promise((resolve) => setTimeout(resolve, 5000))
return { return {
props: {
message: 'hello from slow layout', message: 'hello from slow layout',
},
} }
} }
export default function gspLayout(props) { export default function gspLayout(props) {
const data = use(getData())
return ( return (
<> <>
<h1 id="slow-layout-message">{props.message}</h1> <h1 id="slow-layout-message">{data.message}</h1>
{props.children} {props.children}
</> </>
) )
......
export async function getStaticProps() { import { experimental_use as use } from 'react'
export const config = {
revalidate: false,
}
async function getData() {
await new Promise((resolve) => setTimeout(resolve, 5000)) await new Promise((resolve) => setTimeout(resolve, 5000))
return { return {
props: {
message: 'hello from slow page', message: 'hello from slow page',
nowDuringBuild: Date.now(),
},
} }
} }
export default function nestedPage(props) { export default function nestedPage(props) {
const data = use(getData())
return ( return (
<> <>
<p id="slow-page-message">{props.message}</p> <p id="slow-page-message">{data.message}</p>
<p id="slow-page-now">{props.nowDuringBuild}</p>
</> </>
) )
} }
import globOrig from 'glob'
import cheerio from 'cheerio'
import { promisify } from 'util'
import path, { join } from 'path'
import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'test/lib/next-modes/base'
import { fetchViaHTTP, normalizeRegEx } from 'next-test-utils'
const glob = promisify(globOrig)
describe('app-dir static/dynamic handling', () => {
if ((global as any).isNextDeploy) {
it('should skip next deploy for now', () => {})
return
}
if (process.env.NEXT_TEST_REACT_VERSION === '^17') {
it('should skip for react v17', () => {})
return
}
let next: NextInstance
beforeAll(async () => {
next = await createNext({
files: new FileRef(path.join(__dirname, 'app-static')),
dependencies: {
react: 'experimental',
'react-dom': 'experimental',
},
})
})
afterAll(() => next.destroy())
if ((global as any).isNextStart) {
it('should output HTML/RSC files for static paths', async () => {
const files = (
await glob('**/*', {
cwd: join(next.testDir, '.next/server/app'),
})
).filter((file) => file.match(/.*\.(js|html|rsc)$/))
expect(files).toEqual([
'blog/[author]/[slug]/page.js',
'blog/[author]/page.js',
'blog/seb.html',
'blog/seb.rsc',
'blog/seb/second-post.html',
'blog/seb/second-post.rsc',
'blog/styfle.html',
'blog/styfle.rsc',
'blog/styfle/first-post.html',
'blog/styfle/first-post.rsc',
'blog/styfle/second-post.html',
'blog/styfle/second-post.rsc',
'blog/tim.html',
'blog/tim.rsc',
'blog/tim/first-post.html',
'blog/tim/first-post.rsc',
'ssr-auto/page.js',
'ssr-forced/page.js',
])
})
it('should have correct prerender-manifest entries', async () => {
const manifest = JSON.parse(
await next.readFile('.next/prerender-manifest.json')
)
Object.keys(manifest.dynamicRoutes).forEach((key) => {
const item = manifest.dynamicRoutes[key]
if (item.dataRouteRegex) {
item.dataRouteRegex = normalizeRegEx(item.dataRouteRegex)
}
if (item.routeRegex) {
item.routeRegex = normalizeRegEx(item.routeRegex)
}
})
expect(manifest.version).toBe(3)
expect(manifest.routes).toEqual({
'/blog/tim': {
initialRevalidateSeconds: false,
srcRoute: '/blog/[author]',
dataRoute: '/blog/tim.rsc',
},
'/blog/seb': {
initialRevalidateSeconds: false,
srcRoute: '/blog/[author]',
dataRoute: '/blog/seb.rsc',
},
'/blog/styfle': {
initialRevalidateSeconds: false,
srcRoute: '/blog/[author]',
dataRoute: '/blog/styfle.rsc',
},
'/blog/tim/first-post': {
initialRevalidateSeconds: false,
srcRoute: '/blog/[author]/[slug]',
dataRoute: '/blog/tim/first-post.rsc',
},
'/blog/seb/second-post': {
initialRevalidateSeconds: false,
srcRoute: '/blog/[author]/[slug]',
dataRoute: '/blog/seb/second-post.rsc',
},
'/blog/styfle/first-post': {
initialRevalidateSeconds: false,
srcRoute: '/blog/[author]/[slug]',
dataRoute: '/blog/styfle/first-post.rsc',
},
'/blog/styfle/second-post': {
initialRevalidateSeconds: false,
srcRoute: '/blog/[author]/[slug]',
dataRoute: '/blog/styfle/second-post.rsc',
},
})
expect(manifest.dynamicRoutes).toEqual({
'/blog/[author]/[slug]': {
routeRegex: normalizeRegEx('^/blog/([^/]+?)/([^/]+?)(?:/)?$'),
dataRoute: '/blog/[author]/[slug].rsc',
fallback: null,
dataRouteRegex: normalizeRegEx('^/blog/([^/]+?)/([^/]+?)\\.rsc$'),
},
'/blog/[author]': {
dataRoute: '/blog/[author].rsc',
dataRouteRegex: normalizeRegEx('^\\/blog\\/([^\\/]+?)\\.rsc$'),
fallback: false,
routeRegex: normalizeRegEx('^\\/blog\\/([^\\/]+?)(?:\\/)?$'),
},
})
})
}
it('should handle dynamicParams: false correctly', async () => {
const validParams = ['tim', 'seb', 'styfle']
for (const param of validParams) {
const res = await fetchViaHTTP(next.url, `/blog/${param}`, undefined, {
redirect: 'manual',
})
expect(res.status).toBe(200)
const html = await res.text()
const $ = cheerio.load(html)
expect(JSON.parse($('#params').text())).toEqual({
author: param,
})
expect($('#page').text()).toBe('/blog/[author]')
}
const invalidParams = ['timm', 'non-existent']
for (const param of invalidParams) {
const invalidRes = await fetchViaHTTP(
next.url,
`/blog/${param}`,
undefined,
{ redirect: 'manual' }
)
expect(invalidRes.status).toBe(404)
expect(await invalidRes.text()).toContain('page could not be found')
}
})
it('should handle dynamicParams: true correctly', async () => {
const paramsToCheck = [
{
author: 'tim',
slug: 'first-post',
},
{
author: 'seb',
slug: 'second-post',
},
{
author: 'styfle',
slug: 'first-post',
},
{
author: 'new-author',
slug: 'first-post',
},
]
for (const params of paramsToCheck) {
const res = await fetchViaHTTP(
next.url,
`/blog/${params.author}/${params.slug}`,
undefined,
{
redirect: 'manual',
}
)
expect(res.status).toBe(200)
const html = await res.text()
const $ = cheerio.load(html)
expect(JSON.parse($('#params').text())).toEqual(params)
expect($('#page').text()).toBe('/blog/[author]/[slug]')
}
})
it('should ssr dynamically when detected automatically', async () => {
const initialRes = await fetchViaHTTP(next.url, '/ssr-auto', undefined, {
redirect: 'manual',
})
expect(initialRes.status).toBe(200)
const initialHtml = await initialRes.text()
const initial$ = cheerio.load(initialHtml)
expect(initial$('#page').text()).toBe('/ssr-auto')
const initialDate = initial$('#date').text()
expect(initialHtml).toContain('Example Domain')
const secondRes = await fetchViaHTTP(next.url, '/ssr-auto', undefined, {
redirect: 'manual',
})
expect(secondRes.status).toBe(200)
const secondHtml = await secondRes.text()
const second$ = cheerio.load(secondHtml)
expect(second$('#page').text()).toBe('/ssr-auto')
const secondDate = second$('#date').text()
expect(secondHtml).toContain('Example Domain')
expect(secondDate).not.toBe(initialDate)
})
it('should ssr dynamically when forced via config', async () => {
const initialRes = await fetchViaHTTP(next.url, '/ssr-forced', undefined, {
redirect: 'manual',
})
expect(initialRes.status).toBe(200)
const initialHtml = await initialRes.text()
const initial$ = cheerio.load(initialHtml)
expect(initial$('#page').text()).toBe('/ssr-forced')
const initialDate = initial$('#date').text()
const secondRes = await fetchViaHTTP(next.url, '/ssr-forced', undefined, {
redirect: 'manual',
})
expect(secondRes.status).toBe(200)
const secondHtml = await secondRes.text()
const second$ = cheerio.load(secondHtml)
expect(second$('#page').text()).toBe('/ssr-forced')
const secondDate = second$('#date').text()
expect(secondDate).not.toBe(initialDate)
})
})
export const config = {
dynamicParams: true,
}
export default function Page({ params }) {
return (
<>
<p id="page">/blog/[author]/[slug]</p>
<p id="params">{JSON.stringify(params)}</p>
<p id="date">{Date.now()}</p>
</>
)
}
export function generateStaticParams({ params }) {
console.log(
'/blog/[author]/[slug] generateStaticParams',
JSON.stringify(params)
)
switch (params.author) {
case 'tim': {
return {
params: [
{
slug: 'first-post',
},
],
}
}
case 'seb': {
return {
params: [
{
slug: 'second-post',
},
],
}
}
case 'styfle': {
return {
params: [
{
slug: 'first-post',
},
{
slug: 'second-post',
},
],
}
}
default: {
throw new Error(`unexpected author param received ${params.author}`)
}
}
}
export default function Layout({ children, params }) {
return (
<>
<p id="author-layout-params">{JSON.stringify(params)}</p>
{children}
</>
)
}
export function generateStaticParams({ params }) {
console.log('/blog/[author] generateStaticParams', JSON.stringify(params))
return {
params: [{ author: 'tim' }, { author: 'seb' }, { author: 'styfle' }],
}
}
export const config = {
dynamicParams: false,
}
export default function Page({ params }) {
return (
<>
<p id="page">/blog/[author]</p>
<p id="params">{JSON.stringify(params)}</p>
<p id="date">{Date.now()}</p>
</>
)
}
export default function Layout({ children }) {
return (
<html lang="en">
<head>
<title>my static blog</title>
</head>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>loading...</p>
}
import { cache, use } from '../../lib/utils'
export default function Page() {
const getData = () =>
fetch('https://example.vercel.sh', {
cache: 'no-store',
})
.then((res) => res.text())
.then((text) => new Promise((res) => setTimeout(() => res(text), 1000)))
const dataPromise = cache(getData)
const data = use(dataPromise)
return (
<>
<p id="page">/ssr-auto</p>
<div id="example-dat">{data}</div>
<p id="date">{Date.now()}</p>
</>
)
}
export default function Page() {
return <p>loading...</p>
}
export const config = {
revalidate: 0,
}
export default function Page() {
return (
<>
<p id="page">/ssr-forced</p>
<p id="date">{Date.now()}</p>
</>
)
}
// TODO: replace use/cache with react imports when available
import { experimental_use } from 'react'
export const cache = (cb, ...args) => cb(...args)
export const use = experimental_use
module.exports = {
experimental: {
appDir: true,
serverComponents: true,
legacyBrowsers: false,
browsersListForSwc: true,
},
// assetPrefix: '/assets',
rewrites: async () => {
return {
// beforeFiles: [ { source: '/assets/:path*', destination: '/:path*' } ],
afterFiles: [
{
source: '/rewritten-to-dashboard',
destination: '/dashboard',
},
],
}
},
}
import { experimental_use as use } from 'react'
function getData({ params }) {
return {
now: Date.now(),
params,
}
}
export default function Page(props) {
const data = use(getData(props))
return (
<>
<p>/dashboard/project/[projectId]</p>
<p id="props">{JSON.stringify(data)}</p>
</>
)
}
export async function getServerSideProps() { import { experimental_use as use } from 'react'
async function getData() {
return { return {
props: {
world: 'world', world: 'world',
},
} }
} }
export default function Root({ children, world }) { export default function Root({ children }) {
const { world } = use(getData())
return ( return (
<html className="this-is-another-document-html"> <html className="this-is-another-document-html">
<head> <head>
......
import Widget from './components/widget' import Widget from './components/widget'
export function getServerSideProps({ params }) {
return { props: { params } }
}
export default function Page({ params }) { export default function Page({ params }) {
return ( return (
<> <>
......
export async function getServerSideProps({ params }) { import { experimental_use as use } from 'react'
async function getData({ params }) {
return { return {
props: {
id: params.id, id: params.id,
},
} }
} }
export default function DeploymentsPage(props) { export default function DeploymentsPage(props) {
const data = use(getData(props))
return ( return (
<> <>
<p>hello from app/dashboard/deployments/[id]. ID is: {props.id}</p> <p>hello from app/dashboard/deployments/[id]. ID is: {data.id}</p>
</> </>
) )
} }
export function getServerSideProps() { import { experimental_use as use } from 'react'
async function getData() {
return { return {
props: {
message: 'hello', message: 'hello',
},
} }
} }
export default function DeploymentsLayout({ message, children }) { export default function DeploymentsLayout({ children }) {
const { message } = use(getData())
return ( return (
<> <>
<h2>Deployments {message}</h2> <h2>Deployments {message}</h2>
......
export async function getServerSideProps({ params }) {
return {
props: {
params,
},
}
}
export default function IdLayout({ children, params }) { export default function IdLayout({ children, params }) {
return ( return (
<> <>
......
export async function getServerSideProps({ params }) {
return {
props: {
params,
},
}
}
export default function IdPage({ children, params }) { export default function IdPage({ children, params }) {
return ( return (
<> <>
......
export async function getServerSideProps({ params }) {
return {
props: {
params,
},
}
}
export default function CategoryLayout({ children, params }) { export default function CategoryLayout({ children, params }) {
return ( return (
<> <>
......
export async function getServerSideProps({ params }) {
return {
props: {
params,
},
}
}
export default function DynamicLayout({ children, params }) { export default function DynamicLayout({ children, params }) {
return ( return (
<> <>
......
import { experimental_use as use } from 'react'
import '../styles/global.css' import '../styles/global.css'
import './style.css' import './style.css'
export async function getServerSideProps() { export const config = {
revalidate: 0,
}
async function getData() {
return { return {
props: {
world: 'world', world: 'world',
},
} }
} }
export default function Root({ children, custom, world }) { export default function Root({ children }) {
const { world } = use(getData())
return ( return (
<html className="this-is-the-document-html"> <html className="this-is-the-document-html">
<head> <head>
......
export function getServerSideProps({ params }) {
return { props: { params } }
}
export default function Page({ params }) { export default function Page({ params }) {
return ( return (
<h1 id="text" data-params={params.slug?.join('/') ?? ''}> <h1 id="text" data-params={params.slug?.join('/') ?? ''}>
......
export async function getServerSideProps({ params }) {
return {
props: {
id: params.id,
},
}
}
export default function DeploymentsPage(props) { export default function DeploymentsPage(props) {
return ( return (
<> <>
<p>hello from app/partial-match-[id]. ID is: {props.id}</p> <p>hello from app/partial-match-[id]. ID is: {props.params.id}</p>
</> </>
) )
} }
export async function getServerSideProps() { import { experimental_use as use } from 'react'
async function getData() {
await new Promise((resolve) => setTimeout(resolve, 1000)) await new Promise((resolve) => setTimeout(resolve, 1000))
return { return {
props: {
message: 'hello from slow layout', message: 'hello from slow layout',
},
} }
} }
export default function SlowLayout(props) { export default function SlowLayout(props) {
const data = use(getData())
return ( return (
<> <>
<p id="slow-layout-message">{props.message}</p> <p id="slow-layout-message">{data.message}</p>
{props.children} {props.children}
</> </>
) )
......
export async function getServerSideProps() { import { experimental_use as use } from 'react'
async function getData() {
await new Promise((resolve) => setTimeout(resolve, 5000)) await new Promise((resolve) => setTimeout(resolve, 5000))
return { return {
props: {
message: 'hello from slow page', message: 'hello from slow page',
},
} }
} }
export default function SlowPage(props) { export default function SlowPage(props) {
return <h1 id="slow-page-message">{props.message}</h1> const data = use(getData())
return <h1 id="slow-page-message">{data.message}</h1>
} }
export async function getServerSideProps() { import { experimental_use as use } from 'react'
async function getData() {
await new Promise((resolve) => setTimeout(resolve, 5000)) await new Promise((resolve) => setTimeout(resolve, 5000))
return { return {
props: {
message: 'hello from slow layout', message: 'hello from slow layout',
},
} }
} }
export default function SlowLayout(props) { export default function SlowLayout(props) {
const data = use(getData())
return ( return (
<> <>
<p id="slow-layout-message">{props.message}</p> <p id="slow-layout-message">{data.message}</p>
{props.children} {props.children}
</> </>
) )
......
export async function getServerSideProps() { import { experimental_use as use } from 'react'
async function getData() {
await new Promise((resolve) => setTimeout(resolve, 5000)) await new Promise((resolve) => setTimeout(resolve, 5000))
return { return {
props: {
message: 'hello from slow page', message: 'hello from slow page',
},
} }
} }
export default function SlowPage(props) { export default function SlowPage(props) {
return <h1 id="slow-page-message">{props.message}</h1> const data = use(getData())
return <h1 id="slow-page-message">{data.message}</h1>
} }
export const config = { export const config = {
......
...@@ -34,67 +34,58 @@ describe('app dir rendering', () => { ...@@ -34,67 +34,58 @@ describe('app dir rendering', () => {
expect(html).toContain('app/page.server.js') expect(html).toContain('app/page.server.js')
}) })
describe('getServerSideProps only', () => { describe('SSR only', () => {
it('should run getServerSideProps in layout and page', async () => { it('should run data in layout and page', async () => {
const html = await renderViaHTTP( const html = await renderViaHTTP(next.url, '/ssr-only/nested')
next.url,
'/getserversideprops-only/nested'
)
const $ = cheerio.load(html) const $ = cheerio.load(html)
expect($('#layout-message').text()).toBe('hello from layout') expect($('#layout-message').text()).toBe('hello from layout')
expect($('#page-message').text()).toBe('hello from page') expect($('#page-message').text()).toBe('hello from page')
}) })
it('should run getServerSideProps in parallel', async () => { it('should run data in parallel', async () => {
const startTime = Date.now() // const startTime = Date.now()
const html = await renderViaHTTP( const html = await renderViaHTTP(next.url, '/ssr-only/slow')
next.url, // const endTime = Date.now()
'/getserversideprops-only/slow' // const duration = endTime - startTime
)
const endTime = Date.now()
const duration = endTime - startTime
// Each part takes 5 seconds so it should be below 10 seconds // Each part takes 5 seconds so it should be below 10 seconds
// Using 7 seconds to ensure external factors causing slight slowness don't fail the tests // Using 7 seconds to ensure external factors causing slight slowness don't fail the tests
expect(duration < 7000).toBe(true) // expect(duration < 7000).toBe(true)
const $ = cheerio.load(html) const $ = cheerio.load(html)
expect($('#slow-layout-message').text()).toBe('hello from slow layout') expect($('#slow-layout-message').text()).toBe('hello from slow layout')
expect($('#slow-page-message').text()).toBe('hello from slow page') expect($('#slow-page-message').text()).toBe('hello from slow page')
}) })
}) })
describe('getStaticProps only', () => { describe('static only', () => {
it('should run getStaticProps in layout and page', async () => { it('should run data in layout and page', async () => {
const html = await renderViaHTTP(next.url, '/getstaticprops-only/nested') const html = await renderViaHTTP(next.url, '/static-only/nested')
const $ = cheerio.load(html) const $ = cheerio.load(html)
expect($('#layout-message').text()).toBe('hello from layout') expect($('#layout-message').text()).toBe('hello from layout')
expect($('#page-message').text()).toBe('hello from page') expect($('#page-message').text()).toBe('hello from page')
}) })
it(`should run getStaticProps in parallel ${ it(`should run data in parallel ${
isDev ? 'during development' : 'and use cached version for production' isDev ? 'during development' : 'and use cached version for production'
}`, async () => { }`, async () => {
const startTime = Date.now() // const startTime = Date.now()
const html = await renderViaHTTP(next.url, '/getstaticprops-only/slow') const html = await renderViaHTTP(next.url, '/static-only/slow')
const endTime = Date.now() // const endTime = Date.now()
const duration = endTime - startTime // const duration = endTime - startTime
// Each part takes 5 seconds so it should be below 10 seconds // Each part takes 5 seconds so it should be below 10 seconds
// Using 7 seconds to ensure external factors causing slight slowness don't fail the tests // Using 7 seconds to ensure external factors causing slight slowness don't fail the tests
// TODO: cache static props in prod // TODO: cache static props in prod
// expect(duration < (isDev ? 7000 : 2000)).toBe(true) // expect(duration < (isDev ? 7000 : 2000)).toBe(true)
expect(duration < 7000).toBe(true) // expect(duration < 7000).toBe(true)
const $ = cheerio.load(html) const $ = cheerio.load(html)
expect($('#slow-layout-message').text()).toBe('hello from slow layout') expect($('#slow-layout-message').text()).toBe('hello from slow layout')
expect($('#slow-page-message').text()).toBe('hello from slow page') expect($('#slow-page-message').text()).toBe('hello from slow page')
}) })
}) })
describe('getStaticProps ISR', () => { describe('ISR', () => {
it('should revalidate the page when getStaticProps return revalidate', async () => { it('should revalidate the page when revalidate is configured', async () => {
const getPage = async () => { const getPage = async () => {
const res = await fetchViaHTTP( const res = await fetchViaHTTP(next.url, 'isr-multiple/nested')
next.url,
'getstaticprops-isr-multiple/nested'
)
const html = await res.text() const html = await res.text()
return { return {
...@@ -131,13 +122,10 @@ describe('app dir rendering', () => { ...@@ -131,13 +122,10 @@ describe('app dir rendering', () => {
}) })
// TODO: implement // TODO: implement
describe.skip('getStaticProps and getServerSideProps without ISR', () => { describe.skip('mixed static and dynamic', () => {
it('should generate getStaticProps data during build an use it', async () => { it('should generate static data during build and use it', async () => {
const getPage = async () => { const getPage = async () => {
const html = await renderViaHTTP( const html = await renderViaHTTP(next.url, 'isr-ssr-combined/nested')
next.url,
'getstaticprops-getserversideprops-combined/nested'
)
return { return {
$: cheerio.load(html), $: cheerio.load(html),
......
import React from 'react' import React from 'react'
import RootStyleRegistry from './root-style-registry' import RootStyleRegistry from './root-style-registry'
export const config = {
revalidate: 0,
}
export default function AppLayout({ children }) { export default function AppLayout({ children }) {
return ( return (
<html> <html>
......
import Link from 'next/link' import Link from 'next/link'
import Nav from '../../../components/nav' import Nav from '../../../components/nav'
export default function LinkPage({ queryId }) { export default function LinkPage({ searchParams }) {
const queryId = searchParams.id || '0'
const id = parseInt(queryId) const id = parseInt(queryId)
return ( return (
<> <>
...@@ -15,12 +16,3 @@ export default function LinkPage({ queryId }) { ...@@ -15,12 +16,3 @@ export default function LinkPage({ queryId }) {
</> </>
) )
} }
export function getServerSideProps(ctx) {
const { searchParams } = ctx
return {
props: {
queryId: searchParams.id || '0',
},
}
}
import Nav from '../components/nav' import Nav from '../components/nav'
import { useHeaders } from 'next/dist/client/components/hooks-server'
const envVar = process.env.ENV_VAR_TEST const envVar = process.env.ENV_VAR_TEST
const headerKey = 'x-next-test-client' const headerKey = 'x-next-test-client'
export default function Index({ header }) { export default function Index(props) {
const header = useHeaders()[headerKey]
return ( return (
<div> <div>
<h1>{`component:index.server`}</h1> <h1>{`component:index.server`}</h1>
...@@ -13,14 +16,3 @@ export default function Index({ header }) { ...@@ -13,14 +16,3 @@ export default function Index({ header }) {
</div> </div>
) )
} }
export function getServerSideProps(ctx) {
const { headers } = ctx
const header = headers[headerKey] || ''
return {
props: {
header,
},
}
}
...@@ -8,9 +8,3 @@ export default function page() { ...@@ -8,9 +8,3 @@ export default function page() {
</div> </div>
) )
} }
export function getServerSideProps() {
return {
props: {},
}
}
export const config = {
revalidate: 0,
}
export default function Root({ children }) {
return (
<html lang="en">
<head>
<title>switchable runtime</title>
</head>
<body>{children}</body>
</html>
)
}
import { experimental_use as use } from 'react'
import Runtime from '../../utils/runtime' import Runtime from '../../utils/runtime'
import Time from '../../utils/time' import Time from '../../utils/time'
export default function Page({ type }) { async function getData() {
return {
type: 'ISR',
}
}
export default function Page(props) {
const { type } = use(getData())
return ( return (
<div> <div>
This is a {type} RSC page. This is a {type} RSC page.
...@@ -12,12 +20,3 @@ export default function Page({ type }) { ...@@ -12,12 +20,3 @@ export default function Page({ type }) {
</div> </div>
) )
} }
export function getStaticProps() {
return {
props: {
type: 'ISR',
},
revalidate: 3,
}
}
import { experimental_use as use } from 'react'
import Runtime from '../../utils/runtime' import Runtime from '../../utils/runtime'
import Time from '../../utils/time' import Time from '../../utils/time'
export default function Page({ type }) { async function getData() {
return {
props: {
type: 'SSG',
},
}
}
export default function Page(props) {
const { type } = use(getData())
return ( return (
<div className="node-rsc-ssg"> <div className="node-rsc-ssg">
This is a {type} RSC page. This is a {type} RSC page.
...@@ -12,11 +22,3 @@ export default function Page({ type }) { ...@@ -12,11 +22,3 @@ export default function Page({ type }) {
</div> </div>
) )
} }
export function getStaticProps() {
return {
props: {
type: 'SSG',
},
}
}
import { experimental_use as use } from 'react'
import Runtime from '../../utils/runtime' import Runtime from '../../utils/runtime'
import Time from '../../utils/time' import Time from '../../utils/time'
export default function Page({ type }) { async function getData() {
return {
type: 'SSR',
}
}
export const config = {
runtime: 'nodejs',
}
export default function Page(props) {
const { type } = use(getData())
return ( return (
<div className="node-rsc-ssr"> <div className="node-rsc-ssr">
This is a {type} RSC page. This is a {type} RSC page.
...@@ -12,15 +24,3 @@ export default function Page({ type }) { ...@@ -12,15 +24,3 @@ export default function Page({ type }) {
</div> </div>
) )
} }
export function getServerSideProps() {
return {
props: {
type: 'SSR',
},
}
}
export const config = {
runtime: 'nodejs',
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment