Clean output directory before build to prevent recursive bundling #953
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.
This PR fixes the bug where subsequent builds would cause the
.open-next
output directory to be recursively bundled within itself, leading to exponential growth in bundle size and slow build times.What the issue is
I used OpenNext to build my Nextjs app with Prisma a couple times until I got an error:
rm -rf .next .open-next
thennpx --yes @opennextjs/aws@latest build
first for a clean build, there is no issue.Now, run the build command again without deleting the
.open-next
directory. This will trigger the bug..next/server/app/page.js.nft.json
(for the root App Router page).next/server/pages/api/some-route.js.nft.json
(for a Pages Router API route)It will contain a JSON object with a
files
array. This array lists all the file paths that Next.js determined are dependencies.Search for the string
.open-next
inside this file.On the first (clean) build, I will NOT see any paths containing
.open-next
. The paths will correctly point to the source code ornode_modules
, like this:On the second build, I WILL see paths that point into the previous build's output directory:
This issue is not exclusive to Prisma. It can occur with any library or tool that requires access to local source code files at runtime and is used in server-side code.
The key conditions are:
The Simple Fix
The core of the problem was a feedback loop in the build process.
Before the Fix (Incorrect Order):
After the Fix (Correct Order):
While it is possible to fix it with this flag in
next.config.ts
below. It is still a workaround and adds config debt so I think changing the building step order is a more ideal fix.#951
Issue I Submitted
Reproduction Repo