sveltejs / kit

web development, streamlined
https://svelte.dev/docs/kit
MIT License
18.68k stars 1.93k forks source link

Setting manualChunks configuration breaks $env/dynamic env handling #12581

Open khromov opened 2 months ago

khromov commented 2 months ago

Describe the bug

If you try to access $env/dynamic/private during application startup (for example at top level of hooks) then env is empty ({}) ONLY when manualChunks configuration is set.

Reproduction

Repo: https://github.com/khromov/env-var-manualchunks-repro

SvelteKit manualChunks bug explanation

Broken version:

npm run build && FOO=bar node build/index.js
🔥 Initializing Firebase Admin SDK
FOO ENV VAR IS undefined

FOO is undefined although we set it.

But when going to http://localhost:3000/ we get it:

Env vars {"env":"bar"}

Then, remove the manualChunks option from vite.config.ts and run again:

npm run build && FOO=bar node build/index.js

🔥 Initializing Firebase Admin SDK
FOO ENV VAR IS bar
Listening on 0.0.0.0:3000

Now FOO is set and works correctly both during init and on web.

Logs

No response

System Info

System:
    OS: macOS 14.6.1
    CPU: (8) arm64 Apple M2
    Memory: 140.56 MB / 16.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 22.1.0 - ~/.nvm/versions/node/v22.1.0/bin/node
    npm: 10.7.0 - ~/.nvm/versions/node/v22.1.0/bin/npm
    pnpm: 9.7.1 - ~/.nvm/versions/node/v22.1.0/bin/pnpm
    bun: 1.1.4 - ~/.bun/bin/bun
  Browsers:
    Chrome: 127.0.6533.120
    Chrome Canary: 129.0.6621.0
    Safari: 17.6
    Safari Technology Preview: 18.0
  npmPackages:
    @sveltejs/adapter-auto: ^3.0.0 => 3.2.4 
    @sveltejs/adapter-node: ^5.2.2 => 5.2.2 
    @sveltejs/kit: ^2.0.0 => 2.5.22 
    @sveltejs/vite-plugin-svelte: ^3.0.0 => 3.1.1 
    svelte: ^4.2.7 => 4.2.18 
    vite: ^5.0.3 => 5.4.1

Severity

serious, but I can work around it

Additional Information

No response

dummdidumm commented 2 months ago

I'm not sure if this is something we can fix, arguably it's a misconfiguration. IIRC we have some specific logic to ensure env variables are available before the rest which involves code splitting, and this may undo that logic

khromov commented 2 months ago

@dummdidumm I don't really have any interest in fiddling with the server builds, but I would like to reduce the amount of built client side JS files using this approach.

It was suggested to apply the manualChunks config conditionally to only client builds, but isSsrBuild flag is broken and always returns false, so it's not currently possible to do that.