diff --git a/.changeset/curvy-socks-rhyme.md b/.changeset/curvy-socks-rhyme.md new file mode 100644 index 000000000000..485402efee0e --- /dev/null +++ b/.changeset/curvy-socks-rhyme.md @@ -0,0 +1,5 @@ +--- +"astro": patch +--- + +Improves environment variables replacement in SSR diff --git a/packages/astro/src/core/create-vite.ts b/packages/astro/src/core/create-vite.ts index a3edff3b917c..4ce605b9f52d 100644 --- a/packages/astro/src/core/create-vite.ts +++ b/packages/astro/src/core/create-vite.ts @@ -149,9 +149,9 @@ export async function createVite( root: fileURLToPath(settings.config.root), envPrefix: settings.config.vite?.envPrefix ?? 'PUBLIC_', define: { - 'import.meta.env.SITE': settings.config.site - ? JSON.stringify(settings.config.site) - : 'undefined', + 'import.meta.env.SITE': stringifyForDefine(settings.config.site), + 'import.meta.env.BASE_URL': stringifyForDefine(settings.config.base), + 'import.meta.env.ASSETS_PREFIX': stringifyForDefine(settings.config.build.assetsPrefix), }, server: { hmr: @@ -308,3 +308,7 @@ function isCommonNotAstro(dep: string): boolean { ) ); } + +function stringifyForDefine(value: string | undefined): string { + return typeof value === 'string' ? JSON.stringify(value) : 'undefined'; +} diff --git a/packages/astro/src/vite-plugin-env/index.ts b/packages/astro/src/vite-plugin-env/index.ts index 1958344e595c..c52a345be477 100644 --- a/packages/astro/src/vite-plugin-env/index.ts +++ b/packages/astro/src/vite-plugin-env/index.ts @@ -48,12 +48,6 @@ function getPrivateEnv( } } } - privateEnv.SITE = astroConfig.site ? JSON.stringify(astroConfig.site) : 'undefined'; - privateEnv.SSR = JSON.stringify(true); - privateEnv.BASE_URL = astroConfig.base ? JSON.stringify(astroConfig.base) : 'undefined'; - privateEnv.ASSETS_PREFIX = astroConfig.build.assetsPrefix - ? JSON.stringify(astroConfig.build.assetsPrefix) - : 'undefined'; return privateEnv; } @@ -74,18 +68,6 @@ export default function envVitePlugin({ settings }: EnvPluginOptions): vite.Plug return { name: 'astro:vite-plugin-env', enforce: 'pre', - config() { - return { - define: { - 'import.meta.env.BASE_URL': astroConfig.base - ? JSON.stringify(astroConfig.base) - : 'undefined', - 'import.meta.env.ASSETS_PREFIX': astroConfig.build.assetsPrefix - ? JSON.stringify(astroConfig.build.assetsPrefix) - : 'undefined', - }, - }; - }, configResolved(resolvedConfig) { viteConfig = resolvedConfig; },