withastro / astro

The web framework for content-driven websites. ⭐️ Star to support our work!
https://astro.build
Other
45.18k stars 2.36k forks source link

Missing .env variables are incorrectly resolved in SSR mode #11465

Closed Lesmian closed 1 month ago

Lesmian commented 1 month ago

Astro Info

Astro                    v4.11.5
Node                     v18.20.3
System                   Linux (x64)
Package Manager          unknown
Output                   server
Adapter                  @astrojs/node
Integrations             none

If this issue only occurs in one browser, which browser is a problem?

No response

Describe the Bug

In SSR mode not found env variables are replaced during build with object containing all public variables (including build-in ones like DEV/PROD/BASE_URL) instead of just being undefined.

Example: Import variable which is not defined in .env file: const notFound = import.meta.env.PUBLIC_NOT_FOUND;

Build project in server mode with: npm run build

In the dist folder you will see this as variable value: const notFound = {"PUBLIC_FOUND": "This variable was found", "BASE_URL": "/", "MODE": "production", "DEV": false, "PROD": true, "SSR": true, "SITE": undefined, "ASSETS_PREFIX": undefined}.PUBLIC_NOT_FOUND;

What's the expected result?

Not defined variables should be replaced during build with undefined value. It works like that in static rendering mode as well as when using the new experimental.env. In the case of experimental.env it works correctly (so the value is undefined) in SSR mode as well, so the problem appears only in SSR mode using import.meta.env feature.

Link to Minimal Reproducible Example

https://stackblitz.com/edit/github-8xejlh?file=src%2Fpages%2Findex.astro

Participation

bluwy commented 1 month ago

Is this a Vite issue? I believe PUBLIC_ env vars are handled by Vite only.

bluwy commented 1 month ago

Closing in favour of https://github.com/vitejs/vite/issues/17710