diff --git a/.changeset/moody-crabs-stare.md b/.changeset/moody-crabs-stare.md new file mode 100644 index 000000000..19b9a23f2 --- /dev/null +++ b/.changeset/moody-crabs-stare.md @@ -0,0 +1,5 @@ +--- +'astro': patch +--- + +Ensure import.meta.env.SSR is true in SSR mode diff --git a/packages/astro/src/core/build/static-build.ts b/packages/astro/src/core/build/static-build.ts index 25e0b04e4..c912b74c1 100644 --- a/packages/astro/src/core/build/static-build.ts +++ b/packages/astro/src/core/build/static-build.ts @@ -122,6 +122,7 @@ async function ssrBuild(opts: StaticBuildOptions, internals: BuildInternals, inp entryFileNames: opts.buildConfig.serverEntry, }, }, + ssr: true, // must match an esbuild target target: 'esnext', diff --git a/packages/astro/src/vite-plugin-env/index.ts b/packages/astro/src/vite-plugin-env/index.ts index d3a5f2635..565ea0dae 100644 --- a/packages/astro/src/vite-plugin-env/index.ts +++ b/packages/astro/src/vite-plugin-env/index.ts @@ -78,6 +78,7 @@ export default function envVitePlugin({ privateEnv = getPrivateEnv(config, astroConfig); if (privateEnv) { privateEnv.SITE = astroConfig.site ? `'${astroConfig.site}'` : 'undefined'; + privateEnv.SSR = JSON.stringify(true); const entries = Object.entries(privateEnv).map(([key, value]) => [ `import.meta.env.${key}`, value, @@ -86,6 +87,7 @@ export default function envVitePlugin({ // These additional replacements are needed to match Vite replacements = Object.assign(replacements, { 'import.meta.env.SITE': astroConfig.site ? `'${astroConfig.site}'` : 'undefined', + 'import.meta.env.SSR': JSON.stringify(true), // This catches destructed `import.meta.env` calls, // BUT we only want to inject private keys referenced in the file. // We overwrite this value on a per-file basis. diff --git a/packages/astro/test/fixtures/ssr-env/astro.config.mjs b/packages/astro/test/fixtures/ssr-env/astro.config.mjs new file mode 100644 index 000000000..42f10a572 --- /dev/null +++ b/packages/astro/test/fixtures/ssr-env/astro.config.mjs @@ -0,0 +1,5 @@ +import preact from '@astrojs/preact'; + +export default { + integrations: [preact()] +} diff --git a/packages/astro/test/fixtures/ssr-env/package.json b/packages/astro/test/fixtures/ssr-env/package.json new file mode 100644 index 000000000..f2d339704 --- /dev/null +++ b/packages/astro/test/fixtures/ssr-env/package.json @@ -0,0 +1,9 @@ +{ + "name": "@test/ssr-env", + "version": "0.0.0", + "private": true, + "dependencies": { + "astro": "workspace:*", + "@astrojs/preact": "workspace:*" + } +} diff --git a/packages/astro/test/fixtures/ssr-env/src/components/Env.jsx b/packages/astro/test/fixtures/ssr-env/src/components/Env.jsx new file mode 100644 index 000000000..776cf3785 --- /dev/null +++ b/packages/astro/test/fixtures/ssr-env/src/components/Env.jsx @@ -0,0 +1,7 @@ + +export default function() { + const ssr = import.meta.env.SSR; + return ( +