Skip to content

Commit

Permalink
Improve env var handling in SSR (#9637)
Browse files Browse the repository at this point in the history
  • Loading branch information
bluwy authored Jan 9, 2024
1 parent d77a032 commit 5cba637
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 21 deletions.
5 changes: 5 additions & 0 deletions .changeset/curvy-socks-rhyme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"astro": patch
---

Improves environment variables replacement in SSR
10 changes: 7 additions & 3 deletions packages/astro/src/core/create-vite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -308,3 +308,7 @@ function isCommonNotAstro(dep: string): boolean {
)
);
}

function stringifyForDefine(value: string | undefined): string {
return typeof value === 'string' ? JSON.stringify(value) : 'undefined';
}
18 changes: 0 additions & 18 deletions packages/astro/src/vite-plugin-env/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

Expand All @@ -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;
},
Expand Down

0 comments on commit 5cba637

Please sign in to comment.