diff --git a/.changeset/real-actors-jog.md b/.changeset/real-actors-jog.md new file mode 100644 index 000000000000..d2a77195fddc --- /dev/null +++ b/.changeset/real-actors-jog.md @@ -0,0 +1,5 @@ +--- +'astro': patch +--- + +Fixes a case where environment variables would not be refreshed when using `astro:env` diff --git a/packages/astro/src/env/runtime-constants.ts b/packages/astro/src/env/runtime-constants.ts new file mode 100644 index 000000000000..27b5d72113b2 --- /dev/null +++ b/packages/astro/src/env/runtime-constants.ts @@ -0,0 +1 @@ +export const ENV_SYMBOL = Symbol.for('astro:env/dev'); diff --git a/packages/astro/src/env/runtime.ts b/packages/astro/src/env/runtime.ts index a2017b617f84..3d3b3c77500b 100644 --- a/packages/astro/src/env/runtime.ts +++ b/packages/astro/src/env/runtime.ts @@ -1,4 +1,5 @@ import { AstroError, AstroErrorData } from '../core/errors/index.js'; +import { ENV_SYMBOL } from './runtime-constants.js'; import { invalidVariablesToError } from './errors.js'; import type { ValidationResultInvalid } from './validators.js'; export { validateEnvVariable, getEnvFieldType } from './validators.js'; @@ -6,7 +7,10 @@ export { validateEnvVariable, getEnvFieldType } from './validators.js'; export type GetEnv = (key: string) => string | undefined; type OnSetGetEnv = (reset: boolean) => void; -let _getEnv: GetEnv = (key) => process.env[key]; +let _getEnv: GetEnv = (key) => { + const env = (globalThis as any)[ENV_SYMBOL] ?? {}; + return env[key]; +}; export function setGetEnv(fn: GetEnv, reset = false) { _getEnv = fn; diff --git a/packages/astro/src/env/vite-plugin-env.ts b/packages/astro/src/env/vite-plugin-env.ts index 9ae24a90ba1b..d8165f48caf4 100644 --- a/packages/astro/src/env/vite-plugin-env.ts +++ b/packages/astro/src/env/vite-plugin-env.ts @@ -11,12 +11,7 @@ import { import { type InvalidVariable, invalidVariablesToError } from './errors.js'; import type { EnvSchema } from './schema.js'; import { getEnvFieldType, validateEnvVariable } from './validators.js'; - -// TODO: reminders for when astro:env comes out of experimental -// Types should always be generated (like in types/content.d.ts). That means the client module will be empty -// and server will only contain getSecret for unknown variables. Then, specifying a schema should only add -// variables as needed. For secret variables, it will only require specifying SecretValues and it should get -// merged with the static types/content.d.ts +import { ENV_SYMBOL } from './runtime-constants.js'; interface AstroEnvVirtualModPluginParams { settings: AstroSettings; @@ -47,11 +42,7 @@ export function astroEnv({ fileURLToPath(settings.config.root), '', ); - for (const [key, value] of Object.entries(loadedEnv)) { - if (value !== undefined) { - process.env[key] = value; - } - } + (globalThis as any)[ENV_SYMBOL] = loadedEnv; const validatedVariables = validatePublicVariables({ schema,