Unverified Commit 1435de15 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Ensure component load order (#22731)

This ensures we load `_document` then `_app` and then the page's component in all cases which matches behavior between the serverless target and the default server target.  Additional tests to ensure this order is followed has been added to prevent regression. 

Fixes: https://github.com/vercel/next.js/issues/22732
parent e04d399a
...@@ -680,7 +680,8 @@ export default async function build( ...@@ -680,7 +680,8 @@ export default async function build(
) )
return staticCheckWorkers.isPageStatic( return staticCheckWorkers.isPageStatic(
page, page,
serverBundle, distDir,
isLikeServerless,
runtimeEnvConfig, runtimeEnvConfig,
config.i18n?.locales, config.i18n?.locales,
config.i18n?.defaultLocale, config.i18n?.defaultLocale,
......
...@@ -31,6 +31,7 @@ import { normalizeLocalePath } from '../next-server/lib/i18n/normalize-locale-pa ...@@ -31,6 +31,7 @@ import { normalizeLocalePath } from '../next-server/lib/i18n/normalize-locale-pa
import * as Log from './output/log' import * as Log from './output/log'
import opentelemetryApi from '@opentelemetry/api' import opentelemetryApi from '@opentelemetry/api'
import { tracer, traceAsyncFn } from './tracer' import { tracer, traceAsyncFn } from './tracer'
import { loadComponents } from '../next-server/server/load-components'
const fileGzipStats: { [k: string]: Promise<number> } = {} const fileGzipStats: { [k: string]: Promise<number> } = {}
const fsStatGzip = (file: string) => { const fsStatGzip = (file: string) => {
...@@ -713,7 +714,8 @@ export async function buildStaticPaths( ...@@ -713,7 +714,8 @@ export async function buildStaticPaths(
export async function isPageStatic( export async function isPageStatic(
page: string, page: string,
serverBundle: string, distDir: string,
serverless: boolean,
runtimeEnvConfig: any, runtimeEnvConfig: any,
locales?: string[], locales?: string[],
defaultLocale?: string, defaultLocale?: string,
...@@ -742,8 +744,9 @@ export async function isPageStatic( ...@@ -742,8 +744,9 @@ export async function isPageStatic(
require('../next-server/lib/runtime-config').setConfig( require('../next-server/lib/runtime-config').setConfig(
runtimeEnvConfig runtimeEnvConfig
) )
const mod = await require(serverBundle) const components = await loadComponents(distDir, page, serverless)
const Comp = await (mod.default || mod) const mod = components.ComponentMod
const Comp = mod.default || mod
if ( if (
!Comp || !Comp ||
......
...@@ -138,6 +138,8 @@ const nextServerlessLoader: webpack.loader.Loader = function () { ...@@ -138,6 +138,8 @@ const nextServerlessLoader: webpack.loader.Loader = function () {
} }
import { getPageHandler } from 'next/dist/build/webpack/loaders/next-serverless-loader/page-handler' import { getPageHandler } from 'next/dist/build/webpack/loaders/next-serverless-loader/page-handler'
const documentModule = require("${absoluteDocumentPath}")
const appMod = require('${absoluteAppPath}') const appMod = require('${absoluteAppPath}')
let App = appMod.default || appMod.then && appMod.then(mod => mod.default); let App = appMod.default || appMod.then && appMod.then(mod => mod.default);
...@@ -163,7 +165,7 @@ const nextServerlessLoader: webpack.loader.Loader = function () { ...@@ -163,7 +165,7 @@ const nextServerlessLoader: webpack.loader.Loader = function () {
pageComponent: Component, pageComponent: Component,
pageConfig: config, pageConfig: config,
appModule: App, appModule: App,
documentModule: require("${absoluteDocumentPath}"), documentModule: documentModule,
errorModule: require("${absoluteErrorPath}"), errorModule: require("${absoluteErrorPath}"),
notFoundModule: ${ notFoundModule: ${
absolute404Path ? `require("${absolute404Path}")` : undefined absolute404Path ? `require("${absolute404Path}")` : undefined
......
...@@ -2,6 +2,7 @@ import chalk from 'chalk' ...@@ -2,6 +2,7 @@ import chalk from 'chalk'
import findUp from 'next/dist/compiled/find-up' import findUp from 'next/dist/compiled/find-up'
import { basename, extname } from 'path' import { basename, extname } from 'path'
import * as Log from '../../build/output/log' import * as Log from '../../build/output/log'
import { hasNextSupport } from '../../telemetry/ci-info'
import { CONFIG_FILE } from '../lib/constants' import { CONFIG_FILE } from '../lib/constants'
import { execOnce } from '../lib/utils' import { execOnce } from '../lib/utils'
import { defaultConfig, normalizeConfig } from './config-shared' import { defaultConfig, normalizeConfig } from './config-shared'
...@@ -443,6 +444,10 @@ export default async function loadConfig( ...@@ -443,6 +444,10 @@ export default async function loadConfig(
) )
} }
if (hasNextSupport) {
userConfig.target = process.env.NEXT_PRIVATE_TARGET || 'server'
}
return assignDefaults({ return assignDefaults({
configOrigin: CONFIG_FILE, configOrigin: CONFIG_FILE,
configFile: path, configFile: path,
......
...@@ -32,6 +32,7 @@ export type LoadComponentsReturnType = { ...@@ -32,6 +32,7 @@ export type LoadComponentsReturnType = {
getStaticProps?: GetStaticProps getStaticProps?: GetStaticProps
getStaticPaths?: GetStaticPaths getStaticPaths?: GetStaticPaths
getServerSideProps?: GetServerSideProps getServerSideProps?: GetServerSideProps
ComponentMod: any
} }
export async function loadComponents( export async function loadComponents(
...@@ -54,14 +55,13 @@ export async function loadComponents( ...@@ -54,14 +55,13 @@ export async function loadComponents(
getStaticProps, getStaticProps,
getStaticPaths, getStaticPaths,
getServerSideProps, getServerSideProps,
ComponentMod: Component,
} as LoadComponentsReturnType } as LoadComponentsReturnType
} }
const [DocumentMod, AppMod, ComponentMod] = await Promise.all([ const DocumentMod = await requirePage('/_document', distDir, serverless)
requirePage('/_document', distDir, serverless), const AppMod = await requirePage('/_app', distDir, serverless)
requirePage('/_app', distDir, serverless), const ComponentMod = await requirePage(pathname, distDir, serverless)
requirePage(pathname, distDir, serverless),
])
const [ const [
buildManifest, buildManifest,
...@@ -86,6 +86,7 @@ export async function loadComponents( ...@@ -86,6 +86,7 @@ export async function loadComponents(
buildManifest, buildManifest,
reactLoadableManifest, reactLoadableManifest,
pageConfig: ComponentMod.config || {}, pageConfig: ComponentMod.config || {},
ComponentMod,
getServerSideProps, getServerSideProps,
getStaticProps, getStaticProps,
getStaticPaths, getStaticPaths,
......
let curConfig
const idk = Math.random()
export default () => {
console.log('returning config', idk, curConfig)
return curConfig
}
export function setConfig(configValue) {
curConfig = configValue
console.log('set config', idk, configValue)
}
module.exports = { module.exports = {
// ensure incorrect target is overridden by env
target: 'serverless',
rewrites() { rewrites() {
return [ return [
{ {
......
import { setConfig } from '../lib/config'
setConfig({ hello: 'world' })
export default function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
import { useRouter } from 'next/router' import { useRouter } from 'next/router'
import getConfig from '../lib/config'
const localConfig = getConfig()
if (localConfig.hello !== 'world') {
throw new Error('oof import order is wrong, _app comes first')
}
export const getServerSideProps = ({ req }) => { export const getServerSideProps = ({ req }) => {
return { return {
......
...@@ -25,7 +25,11 @@ let errors = [] ...@@ -25,7 +25,11 @@ let errors = []
describe('Required Server Files', () => { describe('Required Server Files', () => {
beforeAll(async () => { beforeAll(async () => {
await fs.remove(join(appDir, '.next')) await fs.remove(join(appDir, '.next'))
await nextBuild(appDir) await nextBuild(appDir, undefined, {
env: {
NOW_BUILDER: '1',
},
})
buildId = await fs.readFile(join(appDir, '.next/BUILD_ID'), 'utf8') buildId = await fs.readFile(join(appDir, '.next/BUILD_ID'), 'utf8')
requiredFilesManifest = await fs.readJSON( requiredFilesManifest = await fs.readJSON(
...@@ -88,6 +92,8 @@ describe('Required Server Files', () => { ...@@ -88,6 +92,8 @@ describe('Required Server Files', () => {
console.log('checking', file) console.log('checking', file)
expect(await fs.exists(join(appDir, file))).toBe(true) expect(await fs.exists(join(appDir, file))).toBe(true)
} }
expect(await fs.exists(join(appDir, '.next/server'))).toBe(true)
}) })
it('should render SSR page correctly', async () => { it('should render SSR page correctly', async () => {
......
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