feat: add validation for root-level files when src directory exists #235
+132
−0
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
What?
This PR adds validation to throw an error when root-level files (
middleware
andinstrumentation
) are found outside thesrc/
directory when asrc/
directory structure is being used.Why?
Currently, Next.js allows middleware and instrumentation files to exist at the project root even when using a
src/
directory structure. This can lead to confusion and inconsistent file organization. The Next.js documentation states that when using the src directory, middleware should be placed inside the src folder, but this wasn't enforced.How?
Added new error class:
SrcDirectoryError
inpackages/next/src/build/utils.ts
that provides clear error messaging and documentation linksAdded validation functions:
validateMiddlewareInSrcDir(fileName: string, isSrcDir: boolean)
validateInstrumentationInSrcDir(fileName: string, isSrcDir: boolean)
Integrated validation in two key locations:
packages/next/src/server/lib/router-utils/setup-dev-bundler.ts
- validates during dev server startuppackages/next/src/build/index.ts
- validates during production buildAdded test cases: Created
test/integration/src-dir-validation/
to verify the validation behaviorThe validation logic checks:
src/
directory structure is being used (isSrcDir
)src/
directorySrcDirectoryError
with helpful guidanceCritical items to verify:
fileName.startsWith('/src/')
correctly identifies files inside src directory for Next.js internal file pathstest/integration/src-dir-validation/
to ensure they work correctlytest/integration/middleware-src
)next dev
andnext build
scenariosBreaking Change Consideration: This introduces new fatal errors for previously "working" (but incorrectly organized) projects. Consider if this should be a warning first before becoming an error in a future version.
Link to Devin run: https://app.devin.ai/sessions/94e9f081963a4ec3bc8bc9c8c1ca8975
Requested by: @devjiwonchoi
🔄 This is a mirror of upstream PR #82514