Commit bab6f0fd authored by Tobias Koppers's avatar Tobias Koppers Committed by Tobias Koppers

fix: auto-restart dev server when .next directory is deleted

Detect .next directory deletion at request time and trigger an automatic
restart using the existing exit-code-77 restart mechanism, instead of
serving broken pages with cryptic ENOENT errors.
parent 7e1f36c6
...@@ -7,6 +7,7 @@ import type { NextUrlWithParsedQuery, RequestMeta } from '../request-meta' ...@@ -7,6 +7,7 @@ import type { NextUrlWithParsedQuery, RequestMeta } from '../request-meta'
import '../node-environment' import '../node-environment'
import '../require-hook' import '../require-hook'
import { existsSync } from 'fs'
import url from 'url' import url from 'url'
import path from 'path' import path from 'path'
import loadConfig, { type ConfiguredExperimentalFeature } from '../config' import loadConfig, { type ConfiguredExperimentalFeature } from '../config'
...@@ -60,6 +61,7 @@ import { ...@@ -60,6 +61,7 @@ import {
isChromeDevtoolsWorkspaceUrl, isChromeDevtoolsWorkspaceUrl,
} from './chrome-devtools-workspace' } from './chrome-devtools-workspace'
import { getNextConfigRuntime, type NextConfigComplete } from '../config-shared' import { getNextConfigRuntime, type NextConfigComplete } from '../config-shared'
import { RESTART_EXIT_CODE } from './utils'
const debug = setupDebug('next:router-server:main') const debug = setupDebug('next:router-server:main')
const isNextFont = (pathname: string | null) => const isNextFont = (pathname: string | null) =>
...@@ -224,6 +226,15 @@ export async function initialize(opts: { ...@@ -224,6 +226,15 @@ export async function initialize(opts: {
require('./render-server') as typeof import('./render-server') require('./render-server') as typeof import('./render-server')
const requestHandlerImpl: WorkerRequestHandler = async (req, res) => { const requestHandlerImpl: WorkerRequestHandler = async (req, res) => {
// If the distDir was deleted, restart the dev server instead of
// serving broken pages with cryptic ENOENT errors.
if (opts.dev && !existsSync(path.join(opts.dir, config.distDir))) {
Log.warn(
`The ${(config as NextConfigComplete).distDirRoot || config.distDir} directory was removed while the dev server was running. Restarting...`
)
process.exit(RESTART_EXIT_CODE)
}
addRequestMeta(req, 'relativeProjectDir', relativeProjectDir) addRequestMeta(req, 'relativeProjectDir', relativeProjectDir)
// internal headers should not be honored by the request handler // internal headers should not be honored by the request handler
......
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils' import { retry } from 'next-test-utils'
import path from 'path'
// Path to the `packages/next` directory, used to normalize
// environment-specific absolute paths in error stack traces.
const nextPkgDir = path.dirname(require.resolve('next/package.json'))
function escapeRegExp(str: string): string {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}
/**
* Normalize environment-specific paths and non-deterministic content
* from CLI output so snapshots are stable across machines and runs.
*/
function normalizeOutput(output: string, testDir: string): string {
return output
.replace(new RegExp(escapeRegExp(testDir), 'g'), 'TEST_DIR')
.replace(new RegExp(escapeRegExp(nextPkgDir), 'g'), 'NEXT_DIR')
.replace(/\.tmp\.[a-z0-9]+/g, '.tmp.RANDOM')
}
/**
* Extract unique error messages from CLI output.
* Returns sorted, deduplicated error message strings (first line only).
*/
function extractUniqueErrorMessages(output: string): string[] {
const pattern = /(?:⨯ )?(Error: .+)/g
const messages = new Set<string>()
let match: RegExpExecArray | null
while ((match = pattern.exec(output)) !== null) {
messages.add(match[1])
}
return [...messages].sort()
}
describe('delete-dot-next-dir', () => { describe('delete-dot-next-dir', () => {
const { next } = nextTestSetup({ const { next } = nextTestSetup({
...@@ -54,7 +20,7 @@ describe('delete-dot-next-dir', () => { ...@@ -54,7 +20,7 @@ describe('delete-dot-next-dir', () => {
await next.clean() await next.clean()
}) })
it('should show error after .next is deleted (app router)', async () => { it('should recover after .next is deleted (app router)', async () => {
// 1. Verify app route loads correctly before deletion // 1. Verify app route loads correctly before deletion
await retry(async () => { await retry(async () => {
const res = await next.fetch('/app') const res = await next.fetch('/app')
...@@ -62,41 +28,30 @@ describe('delete-dot-next-dir', () => { ...@@ -62,41 +28,30 @@ describe('delete-dot-next-dir', () => {
expect(await res.text()).toContain('app page') expect(await res.text()).toContain('app page')
}, 30000) }, 30000)
// 2. Record CLI output position before deletion // 2. Delete the .next directory while dev server is running
const outputIndex = next.cliOutput.length
// 3. Delete the .next directory while dev server is running
await next.deleteFile('.next') await next.deleteFile('.next')
// 4. Navigate to a different app route to trigger the error // 3. Fetch a page — this triggers error detection and restart
const resAfterDelete = await next.fetch('/app/other') await next.fetch('/app/other').catch(() => {})
expect(resAfterDelete.status).toBe(500)
// 5. Wait for errors to appear in CLI output, then wait 5s for // 4. Wait for the dev server to restart and become ready
// persistent cache read/write errors to settle.
await retry(async () => { await retry(async () => {
const cliOutput = next.cliOutput.slice(outputIndex) const cliOutput = next.cliOutput
expect(cliOutput).toContain('Error') expect(cliOutput).toContain(
}, 10000) 'The .next directory was removed while the dev server was running. Restarting...'
await new Promise((resolve) => setTimeout(resolve, 5000)) )
expect(cliOutput).toContain('Ready in')
// 6. Snapshot unique error messages }, 30000)
const cliOutput = next.cliOutput.slice(outputIndex)
const errors = extractUniqueErrorMessages(
normalizeOutput(cliOutput, next.testDir)
)
expect(errors).toMatchInlineSnapshot(` // 5. After restart, pages should render normally
[ await retry(async () => {
"Error: Cannot find module '../chunks/ssr/[turbopack]_runtime.js'", const res = await next.fetch('/app')
"Error: ENOENT: no such file or directory, open 'TEST_DIR/.next/dev/routes-manifest.json'", expect(res.status).toBe(200)
"Error: ENOENT: no such file or directory, open 'TEST_DIR/.next/dev/server/pages-manifest.json'", expect(await res.text()).toContain('app page')
"Error: ENOENT: no such file or directory, open 'TEST_DIR/.next/dev/static/development/_buildManifest.js.tmp.RANDOM'", }, 30000)
]
`)
}) })
it('should show error after .next is deleted (pages router)', async () => { it('should recover after .next is deleted (pages router)', async () => {
// 1. Verify pages route loads correctly before deletion // 1. Verify pages route loads correctly before deletion
await retry(async () => { await retry(async () => {
const res = await next.fetch('/pages') const res = await next.fetch('/pages')
...@@ -104,34 +59,26 @@ describe('delete-dot-next-dir', () => { ...@@ -104,34 +59,26 @@ describe('delete-dot-next-dir', () => {
expect(await res.text()).toContain('pages page') expect(await res.text()).toContain('pages page')
}, 30000) }, 30000)
// 2. Record CLI output position before deletion // 2. Delete the .next directory while dev server is running
const outputIndex = next.cliOutput.length
// 3. Delete the .next directory while dev server is running
await next.deleteFile('.next') await next.deleteFile('.next')
// 4. Navigate to a different pages route to trigger the error // 3. Fetch a page — this triggers error detection and restart
const resAfterDelete = await next.fetch('/pages/other') await next.fetch('/pages/other').catch(() => {})
expect(resAfterDelete.status).toBe(500)
// 5. Wait for errors to appear in CLI output, then wait 5s for // 4. Wait for the dev server to restart and become ready
// persistent cache read/write errors to settle.
await retry(async () => { await retry(async () => {
const cliOutput = next.cliOutput.slice(outputIndex) const cliOutput = next.cliOutput
expect(cliOutput).toContain('Error') expect(cliOutput).toContain(
}, 10000) 'The .next directory was removed while the dev server was running. Restarting...'
await new Promise((resolve) => setTimeout(resolve, 5000)) )
expect(cliOutput).toContain('Ready in')
// 6. Snapshot unique error messages }, 30000)
const cliOutput = next.cliOutput.slice(outputIndex)
const errors = extractUniqueErrorMessages(
normalizeOutput(cliOutput, next.testDir)
)
expect(errors).toMatchInlineSnapshot(` // 5. After restart, pages should render normally
[ await retry(async () => {
"Error: ENOENT: no such file or directory, open 'TEST_DIR/.next/dev/server/pages/_app/build-manifest.json'", const res = await next.fetch('/pages')
] expect(res.status).toBe(200)
`) expect(await res.text()).toContain('pages page')
}, 30000)
}) })
}) })
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