Dynamic `import()` function usage behaves strangely, prevents server-only code
Nobody has claimed this yet.
- Dominant language
- JavaScript
- Stars
- 142k
- Forks
- 32.4k
- Avg merge
- 2d 14h
- Merged PRs (30d)
- 351
Description
Link to the code that reproduces this issue
https://codesandbox.io/p/devbox/relaxed-gagarin-khcz7s
To Reproduce
The following code executes fine in Node, but it causes a "Module Not Found" error in Next.js:
export default function Home() {
return "Hello, world!";
}
// This function is never called
const example = () => {
return false;
// This code is inaccessible
import("any import, but for the sake of the demo, a path that doesn't exist");
};
Current vs. Expected behavior
You can copy the example function definition into Node and not only does the function get defined, but you can run it and you will get a false value in return. No errors, because we haven't done anything to trigger one. That is what I would expect to happen here.
What is actually instead is confusing, but I suspect is related to ensuring dynamically imported code is available client side. Unfortunately, this prevents the use of dynamic imports to split code in a way that allows me to keep server-only code server side because all dynamic imports are resolved and bundled by Next.js, even if there is a conditional guarding the import on the client.
Provide environment information
Node 20.x
Next 14.25 or 15 Canary
See reproduction for any other required details.
Which area(s) are affected? (Select all that apply)
Developer Experience, Lazy Loading, Module Resolution, Output (export/standalone), Pages Router
Which stage(s) are affected? (Select all that apply)
next dev (local), next build (local)
Additional context
No response
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by running the linked CodeSandbox reproduction with Node 20 and Next 14.25 or 15 Canary, then compare next dev and next build behavior for the unreachable dynamic import. Done means the example function can remain uncalled without a Module Not Found error while server-only dynamic imports are not unnecessarily bundled for the client.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript, next.js, node.js
- Domain
- backend, build-system
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100