kit
kit copied to clipboard
`$env/dynamic/public` isn't available in `hooks.client.js` in prod
Describe the bug
Values from env
from $env/dynamic/public
should be available in hooks.client.js
after build just like in other client-side code, but env
is empty {}
.
Reproduction
https://stackblitz.com/edit/sveltejs-kit-template-default-yf9uq9?file=src/hooks.server.js
- Open browser terminal.
- Run
npm run build && npm run preview
in stackblitz project terminal; - View into browser console.
Expected:
hooks.server.js: dynamic.PUBLIC_VARIABLE = value ✅
hooks.server.js: static.PUBLIC_VARIABLE = value ✅
hooks.client.js: dynamic.PUBLIC_VARIABLE = value ❌ // undefined
hooks.client.js: static.PUBLIC_VARIABLE = value ✅
Logs
hooks.server.js: dynamic.PUBLIC_VARIABLE = value
hooks.server.js: static.PUBLIC_VARIABLE = value
hooks.client.js: dynamic.PUBLIC_VARIABLE = undefined
hooks.client.js: static.PUBLIC_VARIABLE = value
System Info
System:
OS: Linux 5.0 undefined
CPU: (7) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
Memory: 0 Bytes / 0 Bytes
Shell: 1.0 - /bin/jsh
Binaries:
Node: 16.14.2 - /usr/local/bin/node
Yarn: 1.22.19 - /usr/local/bin/yarn
npm: 7.17.0 - /usr/local/bin/npm
npmPackages:
@sveltejs/adapter-auto: ^1.0.0 => 1.0.0
@sveltejs/kit: ^1.0.0 => 1.0.11
svelte: ^3.54.0 => 3.55.1
vite: ^4.0.0 => 4.0.4
Severity
annoyance
Additional Information
Workaround is accessing env
inside root layout script.
I fear we can't do much about this. Accessing env
eagerly in the root means that it wasn't set at that time yet. If you do it lazily or inside a setTimeout
you'll see it's defined then.
I tend to make this a documentation issue. An alternative solution could be to use await
to import the client code dynamically after setting the environment. I'm not sure how much this has an impact on startup time thought, and if it's worth it fixing this.
I think we probably could fix it, no? We just need to set the env before importing the hooks. Adds some complexity but feels doable
Go go merge ranger!