Unverified Commit fd2bd295 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Move Ready in time before handler initialization (#88235)

## Move "Ready in X" log before config loading and eliminate duplicate
`loadConfig` calls

### What?

Reorder the dev server startup flow so the "Ready in X" log appears
before loading the user's `next.config.js`, and eliminate duplicate
`loadConfig` calls in both dev and build paths.

### Why?

Previously, the "Ready in X" time included the time spent loading and
evaluating the user's `next.config.js` file. This made the framework
appear slower than it actually is, especially for projects with complex
config files or slow config evaluation.

Additionally, config was being loaded twice:
- **Dev server**: Once in `getStartServerInfo()` just for logging, then
again in `getRequestHandlers()`
- **Build**: Once for the main build, then again in
`getStartServerInfo()` just for logging

### How?

**Before:**
```
1. getStartServerInfo() → loadConfig #1 (slow - blocks on next.config.js)
2. logStartInfo() → logs version, URLs, experimental features
3. "Ready in X" ← time includes config loading
4. getRequestHandlers() → loadConfig #2
```

**After:**
```
1. logStartInfo() → logs version, URLs, envInfo (no config needed)
2. "Ready in X" ← reflects actual framework startup time
3. getRequestHandlers() → loadConfig (once)
4. logExperimentalInfo() → logs experimental features
```

**Changes:**

- Split `logStartInfo` into two functions:
- `logStartInfo()` - basic info (version, URLs, env) - no config needed
  - `logExperimentalInfo()` - experimental features and cacheComponents
- Removed `getStartServerInfo()` which was loading config unnecessarily
- Added `experimentalFeatures` and `cacheComponents` to
`ServerInitResult` so they can be passed back after config loads
- In build, added `reportExperimentalFeatures` callback to the existing
`loadConfig` call instead of loading config twice

---------
Co-authored-by: 's avatarVercel <vercel[bot]@users.noreply.github.com>
parent 586c1ed7
......@@ -49,8 +49,7 @@ if (
process.exit(1)
}
// Start performance profiling after Node.js version is checked
performance.mark('next-start')
process.env.NEXT_PRIVATE_START_TIME = Date.now().toString()
for (const dependency of ['react', 'react-dom']) {
try {
......
......@@ -187,7 +187,12 @@ import {
updateBuildDiagnostics,
recordFetchMetrics,
} from '../diagnostics/build-diagnostics'
import { getStartServerInfo, logStartInfo } from '../server/lib/app-info-log'
import {
getEnvInfo,
logExperimentalInfo,
logStartInfo,
type ConfiguredExperimentalFeature,
} from '../server/lib/app-info-log'
import type { NextEnabledDirectories } from '../server/base-server'
import { hasCustomExportOutput } from '../export/utils'
import { traceMemoryUsage } from '../lib/memory/trace'
......@@ -931,6 +936,7 @@ export default async function build(
NextBuildContext.loadedEnvFiles = loadedEnvFiles
const turborepoAccessTraceResult = new TurborepoAccessTraceResult()
let experimentalFeatures: ConfiguredExperimentalFeature[] = []
const config: NextConfigComplete = await nextBuildSpan
.traceChild('load-next-config')
.traceAsyncFn(() =>
......@@ -941,6 +947,11 @@ export default async function build(
silent: false,
reactProductionProfiling,
debugPrerender,
reportExperimentalFeatures(features) {
experimentalFeatures = features.toSorted(
({ key: a }, { key: b }) => a.localeCompare(b)
)
},
}),
turborepoAccessTraceResult
)
......@@ -1117,20 +1128,18 @@ export default async function build(
)
// Always log next version first then start rest jobs
const { envInfo, experimentalFeatures, cacheComponents } =
await getStartServerInfo({
dir,
dev: false,
debugPrerender,
})
const envInfo = getEnvInfo(dir)
logStartInfo({
networkUrl: null,
appUrl: null,
envInfo,
experimentalFeatures,
logBundler: true,
cacheComponents,
})
logExperimentalInfo({
experimentalFeatures,
cacheComponents: !!config.cacheComponents,
})
const typeCheckingOptions: Parameters<typeof startTypeChecking>[0] = {
......
......@@ -305,6 +305,7 @@ const nextDev = async (
env: {
...defaultEnv,
...(isTurbopack ? { TURBOPACK: process.env.TURBOPACK } : undefined),
NEXT_PRIVATE_START_TIME: process.env.NEXT_PRIVATE_START_TIME,
NEXT_PRIVATE_WORKER: '1',
NEXT_PRIVATE_TRACE_ID: traceId,
NODE_EXTRA_CA_CERTS: startServerOptions.selfSignedCertificate
......
......@@ -2,27 +2,26 @@ import { loadEnvConfig } from '@next/env'
import * as inspector from 'inspector'
import * as Log from '../../build/output/log'
import { bold, purple, strikethrough } from '../../lib/picocolors'
import {
PHASE_DEVELOPMENT_SERVER,
PHASE_PRODUCTION_BUILD,
} from '../../shared/lib/constants'
import loadConfig, { type ConfiguredExperimentalFeature } from '../config'
import type { ConfiguredExperimentalFeature } from '../config'
import { experimentalSchema } from '../config-schema'
// Re-export the type for consumers
export type { ConfiguredExperimentalFeature }
/**
* Logs basic startup info that doesn't require config.
* Called before "Ready in X" to show immediate feedback.
*/
export function logStartInfo({
networkUrl,
appUrl,
envInfo,
experimentalFeatures,
logBundler,
cacheComponents,
}: {
networkUrl: string | null
appUrl: string | null
envInfo?: string[]
experimentalFeatures?: ConfiguredExperimentalFeature[]
logBundler: boolean
cacheComponents?: boolean
}) {
let versionSuffix = ''
const parts = []
......@@ -37,10 +36,6 @@ export function logStartInfo({
}
}
if (cacheComponents) {
parts.push('Cache Components')
}
if (parts.length > 0) {
versionSuffix = ` (${parts.join(', ')})`
}
......@@ -66,6 +61,22 @@ export function logStartInfo({
Log.bootstrap(`- Debugger port: ${debugPort}`)
}
if (envInfo?.length) Log.bootstrap(`- Environments: ${envInfo.join(', ')}`)
}
/**
* Logs experimental features and config-dependent info.
* Called after getRequestHandlers completes.
*/
export function logExperimentalInfo({
experimentalFeatures,
cacheComponents,
}: {
experimentalFeatures?: ConfiguredExperimentalFeature[]
cacheComponents?: boolean
}) {
if (cacheComponents) {
Log.bootstrap(`- Cache Components enabled`)
}
if (experimentalFeatures?.length) {
Log.bootstrap(`- Experiments (use with caution):`)
......@@ -102,49 +113,10 @@ export function logStartInfo({
Log.info('')
}
export async function getStartServerInfo({
dir,
dev,
debugPrerender,
}: {
dir: string
dev: boolean
debugPrerender?: boolean
}): Promise<{
envInfo?: string[]
experimentalFeatures?: ConfiguredExperimentalFeature[]
cacheComponents?: boolean
}> {
let experimentalFeatures: ConfiguredExperimentalFeature[] = []
let cacheComponents = false
const config = await loadConfig(
dev ? PHASE_DEVELOPMENT_SERVER : PHASE_PRODUCTION_BUILD,
dir,
{
reportExperimentalFeatures(features) {
experimentalFeatures = features.sort(({ key: a }, { key: b }) =>
a.localeCompare(b)
)
},
debugPrerender,
silent: false,
}
)
cacheComponents = !!config.cacheComponents
// we need to reset env if we are going to create
// the worker process with the esm loader so that the
// initial env state is correct
let envInfo: string[] = []
/**
* Gets environment info for logging. Fast operation that doesn't require config.
*/
export function getEnvInfo(dir: string): string[] {
const { loadedEnvFiles } = loadEnvConfig(dir, true, console, false)
if (loadedEnvFiles.length > 0) {
envInfo = loadedEnvFiles.map((f) => f.path)
}
return {
envInfo,
experimentalFeatures,
cacheComponents,
}
return loadedEnvFiles.map((f) => f.path)
}
......@@ -8,6 +8,7 @@ import type { ServerResponse } from 'http'
import type { OnCacheEntryHandler } from '../request-meta'
import { interopDefault } from '../../lib/interop-default'
import { formatDynamicImportPath } from '../../lib/format-dynamic-import-path'
import type { ConfiguredExperimentalFeature } from '../config'
export type ServerInitResult = {
requestHandler: RequestHandler
......@@ -17,6 +18,10 @@ export type ServerInitResult = {
closeUpgraded: () => void
// The distDir from config, used by the parent process for telemetry/trace
distDir: string
// Experimental features from config, used for logging after server is ready
experimentalFeatures: ConfiguredExperimentalFeature[]
// Whether cache components is enabled
cacheComponents: boolean
}
let initializations: Record<string, Promise<ServerInitResult> | undefined> = {}
......@@ -94,6 +99,8 @@ async function initializeImpl(opts: {
quiet?: boolean
onDevServerCleanup: ((listener: () => Promise<void>) => void) | undefined
distDir: string
experimentalFeatures: ConfiguredExperimentalFeature[]
cacheComponents: boolean
}): Promise<ServerInitResult> {
const type = process.env.__NEXT_PRIVATE_RENDER_WORKER
if (type) {
......@@ -170,6 +177,8 @@ async function initializeImpl(opts: {
opts.bundlerService?.close()
},
distDir: opts.distDir,
experimentalFeatures: opts.experimentalFeatures,
cacheComponents: opts.cacheComponents,
}
}
......
......@@ -9,7 +9,7 @@ import '../require-hook'
import url from 'url'
import path from 'path'
import loadConfig from '../config'
import loadConfig, { type ConfiguredExperimentalFeature } from '../config'
import { serveStatic } from '../serve-static'
import setupDebug from 'next/dist/compiled/debug'
import * as Log from '../../build/output/log'
......@@ -98,10 +98,18 @@ export async function initialize(opts: {
process.env.NODE_ENV = opts.dev ? 'development' : 'production'
}
let experimentalFeatures: ConfiguredExperimentalFeature[] = []
const config = await loadConfig(
opts.dev ? PHASE_DEVELOPMENT_SERVER : PHASE_PRODUCTION_SERVER,
opts.dir,
{ silent: false }
{
silent: false,
reportExperimentalFeatures(features) {
experimentalFeatures = features.toSorted(({ key: a }, { key: b }) =>
a.localeCompare(b)
)
},
}
)
let compress: ReturnType<typeof setupCompression> | undefined
......@@ -728,6 +736,8 @@ export async function initialize(opts: {
quiet: opts.quiet,
onDevServerCleanup: opts.onDevServerCleanup,
distDir: config.distDir,
experimentalFeatures,
cacheComponents: config.cacheComponents,
}
renderServerOpts.serverFields.routerServerHandler = requestHandlerImpl
......@@ -900,5 +910,7 @@ export async function initialize(opts: {
development?.bundler?.hotReloader?.close()
},
distDir: config.distDir,
experimentalFeatures,
cacheComponents: config.cacheComponents,
}
}
......@@ -29,13 +29,13 @@ import {
CONFIG_FILES,
PHASE_DEVELOPMENT_SERVER,
} from '../../shared/lib/constants'
import { getStartServerInfo, logStartInfo } from './app-info-log'
import { getEnvInfo, logExperimentalInfo, logStartInfo } from './app-info-log'
import { validateTurboNextConfig } from '../../lib/turbopack-warning'
import { type Span, trace, flushAllTraces } from '../../trace'
import { isIPv6 } from './is-ipv6'
import { AsyncCallbackSet } from './async-callback-set'
import type { NextServer } from '../next'
import type { ConfiguredExperimentalFeature } from '../config'
import { durationToString } from '../../build/duration-to-string'
const debug = setupDebug('next:start-server')
let startServerSpan: Span | undefined
......@@ -358,28 +358,30 @@ export async function startServer(
process.env.__NEXT_EXPERIMENTAL_HTTPS = '1'
}
// Only load env and config in dev to for logging purposes
let envInfo: string[] | undefined
let experimentalFeatures: ConfiguredExperimentalFeature[] | undefined
let cacheComponents: boolean | undefined
try {
if (isDev) {
const startServerInfo = await getStartServerInfo({ dir, dev: isDev })
envInfo = startServerInfo.envInfo
cacheComponents = startServerInfo.cacheComponents
experimentalFeatures = startServerInfo.experimentalFeatures
}
logStartInfo({
networkUrl,
appUrl,
envInfo,
experimentalFeatures,
cacheComponents,
logBundler: isDev,
})
// Get env info first (fast, doesn't require config)
const envInfo = isDev ? getEnvInfo(dir) : undefined
// Log basic startup info immediately (before loading config)
logStartInfo({
networkUrl,
appUrl,
envInfo,
logBundler: isDev,
})
// Calculate and log "Ready in X" before loading config
// so it reflects actual framework startup time
const startTime = parseInt(process.env.NEXT_PRIVATE_START_TIME || '0', 10)
const endTime = Date.now()
const startServerProcessDurationMs = endTime - startTime
Log.event(`Starting...`)
const formattedStartDuration = durationToString(
startServerProcessDurationMs / 1000
)
Log.event(`Ready in ${formattedStartDuration}`)
try {
let cleanupStarted = false
let closeUpgraded: (() => void) | null = null
const cleanup = () => {
......@@ -446,6 +448,7 @@ export async function startServer(
process.on('SIGTERM', cleanup)
}
// Now load config via getRequestHandlers (single loadConfig call)
const initResult = await getRequestHandlers({
dir,
port,
......@@ -464,21 +467,15 @@ export async function startServer(
nextServer = initResult.server
closeUpgraded = initResult.closeUpgraded
const startServerProcessDuration =
performance.mark('next-start-end') &&
performance.measure(
'next-start-duration',
'next-start',
'next-start-end'
).duration
// Log experimental features after config is loaded
if (isDev) {
logExperimentalInfo({
experimentalFeatures: initResult.experimentalFeatures,
cacheComponents: initResult.cacheComponents,
})
}
handlersReady()
const formatDurationText =
startServerProcessDuration > 2000
? `${Math.round(startServerProcessDuration / 100) / 10}s`
: `${Math.round(startServerProcessDuration)}ms`
Log.event(`Ready in ${formatDurationText}`)
if (process.env.TURBOPACK && isDev) {
await validateTurboNextConfig({
......
import { nextTestSetup } from 'e2e-utils'
const { version: nextVersion } = require('next/package.json')
import { retry } from 'next-test-utils'
const cacheComponentsEnabled = process.env.__NEXT_CACHE_COMPONENTS === 'true'
......@@ -9,42 +9,30 @@ describe('dev-output', () => {
})
it('shows Cache Components indicator when enabled', async () => {
const preamble = getPreambleOutput(next.cliOutput)
if (cacheComponentsEnabled) {
if (isTurbopack) {
expect(preamble).toContain('Next.js')
expect(preamble).toContain('Turbopack')
expect(preamble).toContain('Cache Components')
} else {
expect(preamble).toContain('Next.js')
expect(preamble).toContain('webpack')
expect(preamble).toContain('Cache Components')
}
} else {
// When cache components env is not set, should not show the indicator
expect(preamble).toContain('Next.js')
if (isTurbopack) {
expect(preamble).toContain('Turbopack')
await next.fetch('/')
await retry(async () => {
const output = next.cliOutput
if (cacheComponentsEnabled) {
if (isTurbopack) {
expect(output).toContain('Next.js')
expect(output).toContain('Turbopack')
expect(output).toContain('Cache Components')
} else {
expect(output).toContain('Next.js')
expect(output).toContain('webpack')
expect(output).toContain('Cache Components')
}
} else {
expect(preamble).toContain('webpack')
// When cache components env is not set, should not show the indicator
expect(output).toContain('Next.js')
if (isTurbopack) {
expect(output).toContain('Turbopack')
} else {
expect(output).toContain('webpack')
}
expect(output).not.toContain('Cache Components')
}
expect(preamble).not.toContain('Cache Components')
}
})
})
})
function getPreambleOutput(cliOutput: string): string {
const lines: string[] = []
for (const line of cliOutput.split('\n')) {
// Capture lines up to and including the "Local:" line
lines.push(line.replace(nextVersion, 'x.y.z'))
if (line.includes('Local:')) {
break
}
}
return lines.join('\n').trim()
}
......@@ -7,8 +7,10 @@ describe('isolated-dev-build', () => {
})
it('should create dev artifacts in .next/dev/ directory', async () => {
expect(await next.hasFile('.next/dev')).toBe(true)
expect(await next.hasFile('.next/server')).toBe(false)
await retry(async () => {
expect(await next.hasFile('.next/dev')).toBe(true)
expect(await next.hasFile('.next/server')).toBe(false)
})
})
it('should work with HMR', async () => {
......
......@@ -57,7 +57,7 @@ describe('server-components-hmr-cache', () => {
it('should use cached fetch calls for fast refresh requests', async () => {
const browser = await next.browser(`/${runtime}`)
const valueBeforePatch = getLoggedAfterValue()
const valueBeforePatch = await retry(() => getLoggedAfterValue())
cliOutputLength = next.cliOutput.length
await next.patchFile(
......@@ -70,7 +70,7 @@ describe('server-components-hmr-cache', () => {
// TODO: remove custom duration in case we increase the default.
}, 5000)
const valueAfterPatch = getLoggedAfterValue()
const valueAfterPatch = await retry(() => getLoggedAfterValue())
expect(valueBeforePatch).toEqual(valueAfterPatch)
}
)
......@@ -148,6 +148,8 @@ describe('server-components-hmr-cache', () => {
describe('with experimental.serverComponentsHmrCache disabled', () => {
beforeAll(async () => {
// Wait for server to be ready
await next.fetch('/404')
await next.patchFile('next.config.js', (content) =>
content.replace(
'// serverComponentsHmrCache: false,',
......
......@@ -6,7 +6,7 @@ describe('next start without next build', () => {
files: __dirname,
skipStart: true,
startCommand: `pnpm next start`,
serverReadyPattern: /✓ Starting.../,
serverReadyPattern: /Local:/,
})
await next.start()
......
......@@ -10,9 +10,11 @@ describe('app-dir with middleware', () => {
})
it('should warn when deprecated middleware file is used', async () => {
expect(next.cliOutput).toContain(
'The "middleware" file convention is deprecated. Please use "proxy" instead.'
)
await retry(async () => {
expect(next.cliOutput).toContain(
'The "middleware" file convention is deprecated. Please use "proxy" instead.'
)
})
})
it('should filter correctly after middleware rewrite', async () => {
......
import { isNextDev, nextTestSetup } from 'e2e-utils'
import { getPrerenderOutput } from './utils'
import stripAnsi from 'strip-ansi'
import { retry } from 'next-test-utils'
describe('Cache Components Errors', () => {
const { next, isTurbopack, isNextStart, skipped } = nextTestSetup({
......@@ -32,16 +32,19 @@ describe('Cache Components Errors', () => {
describe('Console Patching', () => {
if (isNextDev) {
it('does not warn about sync IO if console.log is patched to call new Date() internally', async () => {
await next.browser('/')
let output = stripAnsi(next.cliOutput)
await next.fetch('/404')
// Wait for after 404 is rendered to the console.
await retry(async () => {
expect(next.cliOutput).toContain('GET /404 404')
})
// trim off Next.js's startup logs
const compilationMarker = /Ready in.*(\n.*Compiling.*)?/
expect(output).toMatch(compilationMarker)
const match = compilationMarker.exec(output)
output = output.slice(match.index + match[0].length).trim()
const from = next.cliOutput.length
await next.browser('/')
// trim off any logs after the HTTP request finished
const output = next.cliOutput.slice(from)
expect(output).toContain('GET / 200')
const snapshot = output.slice(0, output.indexOf('GET / 200')).trim()
......
......@@ -12,6 +12,8 @@ describe('Cache Components Errors', () => {
describe('Warning for Bypassing Caches in Dev', () => {
if (isNextDev) {
it('warns if you render with cache-control: no-cache in dev on initial page load', async () => {
// Wait for pages to be loaded to ensure the logging for the test page is the only thing that can be logged.
await next.fetch('/404')
const from = next.cliOutput.length
await next.fetch('/', {
......@@ -26,6 +28,8 @@ describe('Cache Components Errors', () => {
})
it('warns if you render with cache-control: no-cache in dev on client navigation', async () => {
// Wait for pages to be loaded to ensure the logging for the test page is the only thing that can be logged.
await next.fetch('/404')
const from = next.cliOutput.length
await next.fetch('/other', {
......@@ -40,6 +44,8 @@ describe('Cache Components Errors', () => {
})
it('does not warn if you render without cache-control: no-cache in dev on initial page load', async () => {
// Wait for pages to be loaded to ensure the logging for the test page is the only thing that can be logged.
await next.fetch('/404')
const from = next.cliOutput.length
await next.fetch('/')
......@@ -50,6 +56,8 @@ describe('Cache Components Errors', () => {
})
it('does not warn if you render without cache-control: no-cache in dev on client navigation', async () => {
// Wait for pages to be loaded to ensure the logging for the test page is the only thing that can be logged.
await next.fetch('/404')
const from = next.cliOutput.length
await next.fetch('/', {
......@@ -62,6 +70,8 @@ describe('Cache Components Errors', () => {
})
} else {
it('does not warn if you render with cache-control: no-cache in dev on initial page load', async () => {
// Wait for pages to be loaded to ensure the logging for the test page is the only thing that can be logged.
await next.fetch('/404')
const from = next.cliOutput.length
await next.fetch('/', {
......@@ -74,6 +84,8 @@ describe('Cache Components Errors', () => {
})
it('does not warn if you render with cache-control: no-cache in dev on client navigation', async () => {
// Wait for pages to be loaded to ensure the logging for the test page is the only thing that can be logged.
await next.fetch('/404')
const from = next.cliOutput.length
await next.fetch('/', {
......@@ -86,6 +98,8 @@ describe('Cache Components Errors', () => {
})
it('does not warn if you render without cache-control: no-cache in dev on initial page load in start', async () => {
// Wait for pages to be loaded to ensure the logging for the test page is the only thing that can be logged.
await next.fetch('/404')
const from = next.cliOutput.length
await next.fetch('/')
......@@ -96,6 +110,8 @@ describe('Cache Components Errors', () => {
})
it('does not warn if you render without cache-control: no-cache in dev on client navigation in start', async () => {
// Wait for pages to be loaded to ensure the logging for the test page is the only thing that can be logged.
await next.fetch('/404')
const from = next.cliOutput.length
await next.fetch('/', {
......
......@@ -3,6 +3,7 @@
// @ts-ignore
import { nextTestSetup } from 'e2e-utils'
import cheerio from 'cheerio'
import { retry } from 'next-test-utils'
const { i18n } = require('./next.config')
......@@ -53,9 +54,11 @@ describe('i18n-hybrid', () => {
})
it('should warn about i18n in app dir', async () => {
expect(next.cliOutput).toContain(
'i18n configuration in next.config.js is unsupported in App Router.'
)
await retry(async () => {
expect(next.cliOutput).toContain(
'i18n configuration in next.config.js is unsupported in App Router.'
)
})
})
it.each(urls.filter((url) => !url.expected))(
......
......@@ -11,7 +11,9 @@ describe('instrumentation-order', () => {
await next.fetch('/')
await retry(async () => {
const serverLog = next.cliOutput.split('Starting...')[1]
// `next.cliOutput` includes both `next build` and `next start` in the production test run
// Because of that we have to split the output by `Ready in` and get the second part only
const serverLog = next.cliOutput.split('Ready in')[1]
const cliOutputLines = serverLog.split('\n')
const ORDERED_LOGS = [
......
......@@ -67,7 +67,8 @@ describe('log-file', () => {
return normalizeLogContent(newContent)
}
beforeEach(() => {
beforeEach(async () => {
await next.fetch('/404')
// Reset log tracking at the start of each test to only capture new logs
previousLogContent = readLogFile()
})
......
import { join } from 'path'
import { FileRef, nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('multiple-lockfiles', () => {
const { next, skipped, isTurbopack } = nextTestSetup({
......@@ -23,18 +24,20 @@ describe('multiple-lockfiles', () => {
}
it('should have multiple lockfiles warnings', async () => {
expect(next.cliOutput).toMatch(
/We detected multiple lockfiles and selected the directory of .+ as the root directory\./
)
if (isTurbopack) {
expect(next.cliOutput).toMatch(
/To silence this warning, set `turbopack\.root` in your Next\.js config, or consider removing one of the lockfiles if it's not needed\./
)
} else {
await retry(async () => {
expect(next.cliOutput).toMatch(
/To silence this warning, set `outputFileTracingRoot` in your Next\.js config, or consider removing one of the lockfiles if it's not needed\./
/We detected multiple lockfiles and selected the directory of .+ as the root directory\./
)
}
if (isTurbopack) {
expect(next.cliOutput).toMatch(
/To silence this warning, set `turbopack\.root` in your Next\.js config, or consider removing one of the lockfiles if it's not needed\./
)
} else {
expect(next.cliOutput).toMatch(
/To silence this warning, set `outputFileTracingRoot` in your Next\.js config, or consider removing one of the lockfiles if it's not needed\./
)
}
})
})
})
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('proxy-with-middleware', () => {
const { next, isNextDev, skipped } = nextTestSetup({
......@@ -17,7 +18,9 @@ describe('proxy-with-middleware', () => {
if (isNextDev) {
await next.start().catch(() => {})
expect(next.cliOutput).toContain(message)
await retry(async () => {
expect(next.cliOutput).toContain(message)
})
} else {
const { cliOutput } = await next.build()
expect(cliOutput).toContain(message)
......
......@@ -18,6 +18,7 @@ describe('typed-routes-validator', () => {
it('should generate route validation correctly', async () => {
if (isNextDev) {
await next.start()
await next.fetch('/')
} else {
await next.build()
}
......
......@@ -49,9 +49,11 @@ describe('Build Activity Indicator', () => {
expect(result.exitCode).toBe(1)
}
expect(next.cliOutput).toContain(
`Invalid "devIndicator.position" provided, expected one of top-left, top-right, bottom-left, bottom-right, received ttop-leff`
)
await retry(async () => {
expect(next.cliOutput).toContain(
`Invalid "devIndicator.position" provided, expected one of top-left, top-right, bottom-left, bottom-right, received ttop-leff`
)
})
})
})
......
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
import path from 'path'
describe('deprecation-warnings', () => {
......@@ -27,28 +28,32 @@ describe('deprecation-warnings', () => {
it('should emit deprecation warnings for explicitly configured deprecated options', async () => {
await next.start()
const logs = next.cliOutput
await retry(async () => {
const logs = next.cliOutput
// Should warn about experimental.instrumentationHook
expect(logs).toContain('experimental.instrumentationHook')
expect(logs).toContain('no longer needed')
// Should warn about experimental.instrumentationHook
expect(logs).toContain('experimental.instrumentationHook')
expect(logs).toContain('no longer needed')
// Should warn about middleware config options
expect(logs).toContain('experimental.middlewarePrefetch')
expect(logs).toContain('Please use `experimental.proxyPrefetch` instead')
// Should warn about middleware config options
expect(logs).toContain('experimental.middlewarePrefetch')
expect(logs).toContain(
'Please use `experimental.proxyPrefetch` instead'
)
expect(logs).toContain('experimental.middlewareClientMaxBodySize')
expect(logs).toContain(
'Please use `experimental.proxyClientMaxBodySize` instead'
)
expect(logs).toContain('experimental.middlewareClientMaxBodySize')
expect(logs).toContain(
'Please use `experimental.proxyClientMaxBodySize` instead'
)
expect(logs).toContain('experimental.externalMiddlewareRewritesResolve')
expect(logs).toContain(
'Please use `experimental.externalProxyRewritesResolve` instead'
)
expect(logs).toContain('experimental.externalMiddlewareRewritesResolve')
expect(logs).toContain(
'Please use `experimental.externalProxyRewritesResolve` instead'
)
expect(logs).toContain('skipMiddlewareUrlNormalize')
expect(logs).toContain('Please use `skipProxyUrlNormalize` instead')
expect(logs).toContain('skipMiddlewareUrlNormalize')
expect(logs).toContain('Please use `skipProxyUrlNormalize` instead')
})
})
})
})
......@@ -23,6 +23,9 @@ describe('next-phase', () => {
if (skipped) return
it('should render page with next phase correctly', async () => {
await next.fetch('/')
await next.fetch('/foo')
const phases = {
dev: 'phase-development-server',
build: 'phase-production-build',
......@@ -34,9 +37,6 @@ describe('next-phase', () => {
expect(next.cliOutput).toContain(currentPhase)
expect(next.cliOutput).not.toContain(nonExistedPhase)
await next.fetch('/')
await next.fetch('/foo')
if (isNextDev) {
expect(next.cliOutput).not.toContain(phases.start)
} else {
......
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
const CASES = [
[
......@@ -47,8 +48,10 @@ describe('persistent-caching-migration', () => {
})
} else {
it('error on old option in dev', async () => {
await expect(next.start()).toReject()
expect(next.cliOutput).toContain(error)
await next.start()
await retry(async () => {
expect(next.cliOutput).toContain(error)
})
})
}
})
......
......@@ -27,6 +27,8 @@ async function collectStdoutFromDev(appDir) {
stdout += msg
},
})
await fetch(`http://localhost:${port}`)
return stdout
}
......@@ -114,7 +116,7 @@ describe('Config Experimental Warning', () => {
configFile.write(`
module.exports = (phase) => ({
experimental: {
workerThreads: false
workerThreads: false,
// We enable this by default in CI
strictRouteTypes: false,
}
......@@ -253,7 +255,7 @@ describe('Config Experimental Warning', () => {
},
})
await retry(() => {
await retry(async () => {
const cliOutput = stripAnsi(stdout)
const cliOutputErr = stripAnsi(stderr)
expect(cliOutput).not.toContain(experimentalHeader)
......
......@@ -8,6 +8,7 @@ import {
getRedboxHeader,
killApp,
launchApp,
retry,
} from 'next-test-utils'
import webdriver from 'next-webdriver'
import { join } from 'path'
......@@ -17,7 +18,7 @@ import type { Response } from 'node-fetch'
const appDir = join(__dirname, '../')
const nextConfig = new File(join(appDir, 'next.config.js'))
let app
const runDev = async (config: any) => {
const runDev = async (config: any, shouldWaitForReady = true) => {
await nextConfig.write(`module.exports = ${JSON.stringify(config)}`)
const port = await findPort()
const obj = { port, stdout: '', stderr: '' }
......@@ -31,6 +32,9 @@ const runDev = async (config: any) => {
obj.stderr += msg || ''
},
})
if (shouldWaitForReady) {
await fetch(`http://localhost:${port}`)
}
return obj
}
......@@ -53,16 +57,22 @@ describe('config-output-export', () => {
})
it('should error with "i18n" config', async () => {
const { stderr } = await runDev({
output: 'export',
i18n: {
locales: ['en'],
defaultLocale: 'en',
const data = await runDev(
{
output: 'export',
i18n: {
locales: ['en'],
defaultLocale: 'en',
},
},
})
expect(stderr).toContain(
'Specified "i18n" cannot be used with "output: export".'
false
)
await retry(() => {
expect(data.stderr).toContain(
'Specified "i18n" cannot be used with "output: export".'
)
})
})
describe('when hasNextSupport = false', () => {
......
......@@ -2,7 +2,7 @@
import fs from 'fs-extra'
import { join } from 'path'
import { launchApp, findPort, nextBuild } from 'next-test-utils'
import { launchApp, findPort, nextBuild, retry } from 'next-test-utils'
let appDir = join(__dirname, '..')
const nextConfigPath = join(appDir, 'next.config.js')
......@@ -33,11 +33,13 @@ const runTests = () => {
],
'headers'
)
const stderr = await getStderr()
await retry(async () => {
const stderr = await getStderr()
expect(stderr).toContain(
'`headers` field cannot be empty for route {"source":"/:path*"'
)
expect(stderr).toContain(
'`headers` field cannot be empty for route {"source":"/:path*"'
)
})
})
it('should error when source and destination length is exceeded', async () => {
......@@ -137,61 +139,64 @@ const runTests = () => {
],
'redirects'
)
const stderr = await getStderr()
expect(stderr).toContain(
`\`destination\` is missing for route {"source":"/hello","permanent":false}`
)
expect(stderr).toContain(
`\`source\` is not a string for route {"source":123,"destination":"/another","permanent":false}`
)
expect(stderr).toContain(
`\`statusCode\` is not undefined or valid statusCode for route {"source":"/hello","destination":"/another","statusCode":"301"}`
)
expect(stderr).toContain(
`\`statusCode\` is not undefined or valid statusCode for route {"source":"/hello","destination":"/another","statusCode":404}`
)
expect(stderr).toContain(
`\`permanent\` is not set to \`true\` or \`false\` for route {"source":"/hello","destination":"/another","permanent":"yes"}`
)
expect(stderr).toContain(
`\`destination\` has unnamed params :0 for route {"source":"/hello/world/(.*)","destination":"/:0","permanent":true}`
)
expect(stderr).toContain(
`The route null is not a valid object with \`source\` and \`destination\``
)
expect(stderr).toContain(
`The route "string" is not a valid object with \`source\` and \`destination\``
)
expect(stderr).toContain('Invalid `has` item:')
expect(stderr).toContain(
`invalid type "cookiee" for {"type":"cookiee","key":"loggedIn"}`
)
expect(stderr).toContain(
`invalid \`has\` item found for route {"source":"/hello","destination":"/another","has":[{"type":"cookiee","key":"loggedIn"}],"permanent":false}`
)
expect(stderr).toContain('Invalid `has` items:')
expect(stderr).toContain(
`invalid type "headerr", invalid key "undefined" for {"type":"headerr"}`
)
expect(stderr).toContain(
`invalid type "queryr" for {"type":"queryr","key":"hello"}`
)
expect(stderr).toContain(
`invalid \`has\` items found for route {"source":"/hello","destination":"/another","permanent":false,"has":[{"type":"headerr"},{"type":"queryr","key":"hello"}]}`
)
expect(stderr).toContain(`Valid \`has\` object shape is {`)
expect(stderr).toContain('Invalid redirects found')
await retry(async () => {
const stderr = await getStderr()
expect(stderr).toContain(
`\`destination\` is missing for route {"source":"/hello","permanent":false}`
)
expect(stderr).toContain(
`\`source\` is not a string for route {"source":123,"destination":"/another","permanent":false}`
)
expect(stderr).toContain(
`\`statusCode\` is not undefined or valid statusCode for route {"source":"/hello","destination":"/another","statusCode":"301"}`
)
expect(stderr).toContain(
`\`statusCode\` is not undefined or valid statusCode for route {"source":"/hello","destination":"/another","statusCode":404}`
)
expect(stderr).toContain(
`\`permanent\` is not set to \`true\` or \`false\` for route {"source":"/hello","destination":"/another","permanent":"yes"}`
)
expect(stderr).toContain(
`\`destination\` has unnamed params :0 for route {"source":"/hello/world/(.*)","destination":"/:0","permanent":true}`
)
expect(stderr).toContain(
`The route null is not a valid object with \`source\` and \`destination\``
)
expect(stderr).toContain(
`The route "string" is not a valid object with \`source\` and \`destination\``
)
expect(stderr).toContain('Invalid `has` item:')
expect(stderr).toContain(
`invalid type "cookiee" for {"type":"cookiee","key":"loggedIn"}`
)
expect(stderr).toContain(
`invalid \`has\` item found for route {"source":"/hello","destination":"/another","has":[{"type":"cookiee","key":"loggedIn"}],"permanent":false}`
)
expect(stderr).toContain('Invalid `has` items:')
expect(stderr).toContain(
`invalid type "headerr", invalid key "undefined" for {"type":"headerr"}`
)
expect(stderr).toContain(
`invalid type "queryr" for {"type":"queryr","key":"hello"}`
)
expect(stderr).toContain(
`invalid \`has\` items found for route {"source":"/hello","destination":"/another","permanent":false,"has":[{"type":"headerr"},{"type":"queryr","key":"hello"}]}`
)
expect(stderr).toContain(`Valid \`has\` object shape is {`)
expect(stderr).toContain('Invalid redirects found')
})
})
it('should error during next build for invalid rewrites', async () => {
......
......@@ -65,6 +65,7 @@ describe('TypeScript Image Component', () => {
onStdout: handleOutput,
onStderr: handleOutput,
})
await fetch(`http://localhost:${appPort}`)
})
afterAll(() => killApp(app))
......@@ -96,7 +97,9 @@ describe('TypeScript Image Component', () => {
nextConfig,
content.replace('// disableStaticImages', 'disableStaticImages')
)
const app = await launchApp(appDir, await findPort())
const port = await findPort()
const app = await launchApp(appDir, port)
await fetch(`http://localhost:${port}`)
await killApp(app)
await fs.writeFile(nextConfig, content)
const envTypes = await fs.readFile(join(appDir, 'next-env.d.ts'), 'utf8')
......
......@@ -65,6 +65,7 @@ describe('TypeScript Image Component', () => {
onStdout: handleOutput,
onStderr: handleOutput,
})
await fetch(`http://localhost:${appPort}`)
})
afterAll(() => killApp(app))
......@@ -95,7 +96,9 @@ describe('TypeScript Image Component', () => {
nextConfig,
content.replace('// disableStaticImages', 'disableStaticImages')
)
const app = await launchApp(appDir, await findPort())
const port = await findPort()
const app = await launchApp(appDir, port)
await fetch(`http://localhost:${port}`)
await killApp(app)
await fs.writeFile(nextConfig, content)
const envTypes = await fs.readFile(join(appDir, 'next-env.d.ts'), 'utf8')
......
......@@ -42,6 +42,7 @@ describe('TypeScript App Type Declarations', () => {
let app
try {
app = await launchApp(appDir, appPort, {})
await fetch(`http://localhost:${appPort}`)
const content = await fs.readFile(appTypeDeclarations, 'utf8')
expect(content).toEqual(prevContent)
} finally {
......@@ -60,6 +61,7 @@ describe('TypeScript App Type Declarations', () => {
let app
try {
app = await launchApp(appDir, appPort, {})
await fetch(`http://localhost:${appPort}`)
const content = await fs.readFile(appTypeDeclarations, 'utf8')
expect(content).toEqual(prevContent)
} finally {
......
/* eslint-env jest */
import { join } from 'path'
import { launchApp, findPort, nextBuild } from 'next-test-utils'
import { launchApp, findPort, nextBuild, retry } from 'next-test-utils'
const appDir = join(__dirname, '../')
const expectedErr =
......@@ -33,7 +33,9 @@ const expectedErr =
},
})
expect(output).toMatch(expectedErr)
await retry(async () => {
expect(output).toMatch(expectedErr)
})
})
}
)
......@@ -26,7 +26,8 @@ describe('build-output-prerender', () => {
`)
} else {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"▲ Next.js x.y.z (webpack, Cache Components)
"▲ Next.js x.y.z (webpack)
- Cache Components enabled
- Experiments (use with caution):
✓ reactDebugChannel (enabled by \`__NEXT_EXPERIMENTAL_DEBUG_CHANNEL\`)"
`)
......@@ -48,7 +49,8 @@ describe('build-output-prerender', () => {
} else {
if (isTurbopack) {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"▲ Next.js x.y.z (Turbopack, Cache Components)
"▲ Next.js x.y.z (Turbopack)
- Cache Components enabled
- Experiments (use with caution):
✓ strictRouteTypes (enabled by \`__NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES\`)"
`)
......@@ -58,7 +60,8 @@ describe('build-output-prerender', () => {
`)
} else {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"▲ Next.js x.y.z (webpack, Cache Components)
"▲ Next.js x.y.z (webpack)
- Cache Components enabled
- Experiments (use with caution):
✓ strictRouteTypes (enabled by \`__NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES\`)"
`)
......@@ -122,7 +125,8 @@ describe('build-output-prerender', () => {
} else {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"⚠ Prerendering is running in debug mode. Note: This may affect performance and should not be used for production.
▲ Next.js x.y.z (webpack, Cache Components)
▲ Next.js x.y.z (webpack)
- Cache Components enabled
- Experiments (use with caution):
⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`)
✓ reactDebugChannel (enabled by \`__NEXT_EXPERIMENTAL_DEBUG_CHANNEL\`)
......@@ -156,7 +160,8 @@ describe('build-output-prerender', () => {
if (isTurbopack) {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"⚠ Prerendering is running in debug mode. Note: This may affect performance and should not be used for production.
▲ Next.js x.y.z (Turbopack, Cache Components)
▲ Next.js x.y.z (Turbopack)
- Cache Components enabled
- Experiments (use with caution):
⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`)
✓ serverSourceMaps (enabled by \`--debug-prerender\`)
......@@ -175,7 +180,8 @@ describe('build-output-prerender', () => {
} else {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"⚠ Prerendering is running in debug mode. Note: This may affect performance and should not be used for production.
▲ Next.js x.y.z (webpack, Cache Components)
▲ Next.js x.y.z (webpack)
- Cache Components enabled
- Experiments (use with caution):
⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`)
⨯ serverMinification (disabled by \`--debug-prerender\`)
......@@ -266,7 +272,8 @@ describe('build-output-prerender', () => {
`)
} else {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"▲ Next.js x.y.z (webpack, Cache Components)
"▲ Next.js x.y.z (webpack)
- Cache Components enabled
- Experiments (use with caution):
✓ reactDebugChannel (enabled by \`__NEXT_EXPERIMENTAL_DEBUG_CHANNEL\`)"
`)
......@@ -331,7 +338,8 @@ describe('build-output-prerender', () => {
} else {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"⚠ Prerendering is running in debug mode. Note: This may affect performance and should not be used for production.
▲ Next.js x.y.z (webpack, Cache Components)
▲ Next.js x.y.z (webpack)
- Cache Components enabled
- Experiments (use with caution):
⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`)
✓ reactDebugChannel (enabled by \`__NEXT_EXPERIMENTAL_DEBUG_CHANNEL\`)
......
......@@ -100,7 +100,7 @@ describe('Graceful Shutdown', () => {
appPort = await findPort()
app = await initNextServerScript(
serverFile,
/✓ Ready in \d+m?s/,
/✓ Ready in/,
{
...process.env,
NEXT_EXIT_TIMEOUT_MS: '10',
......
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