vercel / next.js

The React Framework
https://nextjs.org
MIT License
127.26k stars 27.02k forks source link

Custom Server Not Bundled Correctly with Standalone Build, ESBuild, or Bun #71515

Open Kavian77 opened 1 month ago

Kavian77 commented 1 month ago

Link to the code that reproduces this issue

https://codesandbox.io/p/devbox/determined-shaw-nz95jm

To Reproduce

  1. Create a new Next.js application with a custom server, or use yours if you already have one.

    npx create-next-app --example custom-server custom-server-app
  2. Try to bundle the server using the following approaches:

Standalone Build:

// next.config.js
{
  output: "standalone"
}

While the build succeeds, it does not support custom servers properly, as mentioned in this existing discussion. As a result, the standalone build ignores the custom server, preventing full bundling.

ESBuild:

npx esbuild server.js --bundle --platform=node --log-limit=0 --log-level=error

This approach fails with dependency handling issues. Please find the logs here: esbuild.log

Bun:

npx bun build server.ts --outdir out/ --target node

Similar to ESBuild, this fails with dependency handling issues. Here is the output log: bun.log

Here are some of the common errors you can find in the logs linked above:

Current vs. Expected behavior

Current Behavior:

Bundlers or Build Tools (e.g. ESBuild and Bun): Fail due to dependency resolution issues. Likely related to how Next.js handles or manifests its internal dependencies or experimental forks of libraries. Standalone build: Does not support bundling of custom servers and ignores them during the build process.

Expected Behavior:

The build system should either:

Provide environment information

Operating System:
  Platform: darwin
  Arch: arm64
  Version: Darwin Kernel Version 23.5.0: Wed May  1 20:17:33 PDT 2024; root:xnu-10063.121.3~5/RELEASE_ARM64_T6031
  Available memory (MB): 65536
  Available CPU cores: 16
Binaries:
  Node: 20.18.0
  npm: 10.8.2
  Yarn: N/A
  pnpm: N/A
Relevant Packages:
  next: 14.2.15 // Latest available version is detected (14.2.15).
  eslint-config-next: N/A
  react: 18.3.1
  react-dom: 18.3.1
  typescript: 4.9.5
Next.js Config:
  output: N/A

Which area(s) are affected? (Select all that apply)

Not sure, Output (export/standalone)

Which stage(s) are affected? (Select all that apply)

next build (local)

Additional context

Bundling the entire application, including custom servers, is essential for production environments, especially when optimizing deployment artifacts such as Docker images. Proper bundling would allow removing the node_modules folder, greatly reducing the image size.

jburghardt commented 1 month ago

This would also help with https://github.com/vercel/next.js/discussions/46722#discussioncomment-10983611

this would be the preferred behaviour: Support custom servers natively in the standalone build (i.e., correctly bundle custom servers along with the app).