Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

breaking: serve public env dynamically, prevent use of dynamic env vars during prerendering #11277

Merged
merged 29 commits into from
Dec 13, 2023

Conversation

Rich-Harris
Copy link
Member

@Rich-Harris Rich-Harris commented Dec 12, 2023

Fixes #10008. This does two things:

  • prevents the use of $env/dynamic/public while prerendering (use $env/static/public instead)
  • when landing on a prerendered page, populates $env/dynamic/public from a new dynamically rendered /_env.js module, instead of populating it with stale build-time values

TODO:

  • allow %sveltekit.env.PUBLIC_WHATEVER% to continue working (seems reasonable that this would be an exception to the 'you can't use dynamic public env vars during prerendering' rule)
  • nicer code
  • I guess it also makes sense to prevent use of $env/dynamic/private during prerendering
  • docs
  • preload _env.js when prerendering if we detect that $env/dynamic/public is used somewhere in the app
  • make _env.js configurable, via config.kit.env.publicModule
  • provide an API for adapter-static (and other adapters, if they want) to generate the _env.js module at build time
  • some tests, i guess

Please don't delete this checklist! Before submitting the PR, please make sure you do the following:

  • It's really useful if your PR references an issue where it is discussed ahead of time. In many cases, features are absent for a reason. For large changes, please create an RFC: https://github.com/sveltejs/rfcs
  • This message body should clearly illustrate what problems it solves.
  • Ideally, include a test that fails without this PR but passes with it.

Tests

  • Run the tests with pnpm test and lint the project with pnpm lint and pnpm check

Changesets

  • If your PR makes a change that should be noted in one or more packages' changelogs, generate a changeset by running pnpm changeset and following the prompts. Changesets that add features should be minor and those that fix bugs should be patch. Please prefix changeset messages with feat:, fix:, or chore:.

Copy link

changeset-bot bot commented Dec 12, 2023

🦋 Changeset detected

Latest commit: d4f7ce2

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 2 packages
Name Type
@sveltejs/kit Major
@sveltejs/adapter-static Major

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@dummdidumm
Copy link
Member

I just realized that the adapter-static case is a bit weird. So far we had minors for all the adapters to tell "hey we support SvelteKit 2.0 as well". adapter-static should also get that treatment for the current version, but that is swallowed by this major bump now. We should create a minor release for adapter-static from master to circumvent that.

@Rich-Harris
Copy link
Member Author

Is there much value in an adapter-static minor? If the only new feature is SvelteKit 2 support, why not just do a major version?

@dummdidumm
Copy link
Member

dummdidumm commented Dec 13, 2023

True, if someone upgrades to SvelteKit 2 they might as well upgrade to adapter-static v3. We should add that to the migration script though (auto-bump the adapter-static version)

Copy link
Member

@dummdidumm dummdidumm left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you want to do the _app change (and if it's easy) feel free to do so, else I think this is good to merge.

@CaptainCodeman
Copy link
Contributor

CaptainCodeman commented Dec 14, 2023

I guess it also makes sense to prevent use of $env/dynamic/private during prerendering

I think this might be incorrect. Even with prerendering disabled it now prevents any handle fn in hooks.server.ts from making use of dynamic env values, which might be needed at runtime.

My specific use-case is using the @sveltejs/adapter-node node adapter, and the env defines the 'ROOT_DOMAIN' that the site is serving, for instance .example.com, so that requests to site-one.example.com can load the appropriate site context by site ID, and redirect to the site's "proper" custom domain if it has one set. When the same request is made via the custom domain, it loads the site based on the domain name instead and doesn't redirect.

The ROOT_DOMAIN isn't known at build time - the same docker image can be deployed to environments that have different values (testing, staging, production).

The build initially compiles OK but then errors at the pre-render stage even with pre-rendering disabled:

+layout.server.ts:

export const prerender = false

Build output:

vite v5.0.9 building SSR bundle for production...
✓ 88 modules transformed.

vite v5.0.9 building for production...
✓ 62 modules transformed.
.svelte-kit/output/client/_app/version.json                                  0.03 kB │ gzip:  0.05 kB
.svelte-kit/output/client/.vite/manifest.json                                2.66 kB │ gzip:  0.53 kB
.svelte-kit/output/client/_app/immutable/chunks/stores.OXeE6BI3.js           0.24 kB │ gzip:  0.17 kB
.svelte-kit/output/client/_app/immutable/nodes/1.a7topCIA.js                 0.79 kB │ gzip:  0.50 kB
.svelte-kit/output/client/_app/immutable/nodes/0.VoE1dcHf.js                 0.89 kB │ gzip:  0.58 kB
.svelte-kit/output/client/_app/immutable/chunks/preload-helper.0HuHagjb.js   0.91 kB │ gzip:  0.56 kB
.svelte-kit/output/client/_app/immutable/chunks/scheduler.k-kUyWhY.js        2.16 kB │ gzip:  1.02 kB
.svelte-kit/output/client/_app/immutable/nodes/2.YZTI5OQK.js                 2.48 kB │ gzip:  1.24 kB
.svelte-kit/output/client/_app/immutable/chunks/singletons.i1C8PUYA.js       2.92 kB │ gzip:  1.48 kB
.svelte-kit/output/client/_app/immutable/entry/app.WtRj-Ezm.js               5.20 kB │ gzip:  1.97 kB
.svelte-kit/output/client/_app/immutable/chunks/index.wJJws_a0.js            5.24 kB │ gzip:  2.21 kB
.svelte-kit/output/client/_app/immutable/entry/start.OF9vDRZY.js            28.00 kB │ gzip: 11.17 kB
✓ built in 404ms

node:internal/event_target:1006
  process.nextTick(() => { throw err; });
                           ^
Error: Cannot read values from $env/dynamic/private while prerendering (attempted to read env.HOST_DOMAIN). Use $env/static/private instead
    at Object.get (file:///Users/simon/dev/temp/sk-envs/.svelte-kit/output/server/index.js:3664:11)
    at file:///Users/simon/dev/temp/sk-envs/.svelte-kit/output/server/chunks/hooks.server.js:17:33
    at ModuleJob.run (node:internal/modules/esm/module_job:193:25)
    at async Promise.all (index 0)
    at async ESMLoader.import (node:internal/modules/esm/loader:526:24)
    at async Server.init (file:///Users/simon/dev/temp/sk-envs/.svelte-kit/output/server/index.js:3696:24)
    at async prerender (file:///Users/simon/dev/temp/sk-envs/node_modules/.pnpm/@sveltejs+kit@2.0.0_@sveltejs+vite-plugin-svelte@3.0.1_svelte@4.2.8_vite@5.0.9/node_modules/@sveltejs/kit/src/core/postbuild/prerender.js:102:2)
    at async MessagePort.<anonymous> (file:///Users/simon/dev/temp/sk-envs/node_modules/.pnpm/@sveltejs+kit@2.0.0_@sveltejs+vite-plugin-svelte@3.0.1_svelte@4.2.8_vite@5.0.9/node_modules/@sveltejs/kit/src/utils/fork.js:22:16)
Emitted 'error' event on Worker instance at:
    at [kOnErrorMessage] (node:internal/worker:290:10)
    at [kOnMessage] (node:internal/worker:301:37)
    at MessagePort.<anonymous> (node:internal/worker:202:57)
    at [nodejs.internal.kHybridDispatch] (node:internal/event_target:731:20)
    at exports.emitMessage (node:internal/per_context/messageport:23:28)

Node.js v18.10.0

It's possible to workaround it by adding tests for building before accessing the values, hopefully that helps anyone who has the same issue and finds this.

Scratch that: I think it was all down to me accessing it outside of the handle function itself (preparing some strings). I'll leave this just in case someone else trips over the same thing.

@ollema
Copy link

ollema commented Dec 16, 2023

@CaptainCodeman this does seem to be an issue, see #11341.

was there a workaround? if so, could you share it in #11341 perhaps? I did not quite understand the building stuff you referred to

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants