Skip to content

Commit

Permalink
fix: do not inject env vars into non-source files (#13001)
Browse files Browse the repository at this point in the history
  • Loading branch information
ascorbic authored Jan 17, 2025
1 parent 78fd73a commit 627aec3
Show file tree
Hide file tree
Showing 10 changed files with 96 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/warm-pandas-lick.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': patch
---

Fixes a bug that caused Astro to attempt to inject environment variables into non-source files, causing performance problems and broken builds
12 changes: 10 additions & 2 deletions packages/astro/src/env/vite-plugin-import-meta-env.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { transform } from 'esbuild';
import MagicString from 'magic-string';
import type * as vite from 'vite';
import { createFilter, isCSSRequest } from 'vite';
import type { EnvLoader } from './env-loader.js';

interface EnvPluginOptions {
Expand Down Expand Up @@ -71,6 +72,7 @@ export function importMetaEnv({ envLoader }: EnvPluginOptions): vite.Plugin {
let isDev: boolean;
let devImportMetaEnvPrepend: string;
let viteConfig: vite.ResolvedConfig;
const filter = createFilter(null, ['**/*.html', '**/*.htm', '**/*.json']);
return {
name: 'astro:vite-plugin-env',
config(_, { command }) {
Expand All @@ -96,11 +98,17 @@ export function importMetaEnv({ envLoader }: EnvPluginOptions): vite.Plugin {
}
}
},

transform(source, id, options) {
if (!options?.ssr || !source.includes('import.meta.env')) {
if (
!options?.ssr ||
!source.includes('import.meta.env') ||
!filter(id) ||
isCSSRequest(id) ||
viteConfig.assetsInclude(id)
) {
return;
}

// Find matches for *private* env and do our own replacement.
// Env is retrieved before process.env is populated by astro:env
// so that import.meta.env is first replaced by values, not process.env
Expand Down
9 changes: 9 additions & 0 deletions packages/astro/test/astro-envs.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -120,5 +120,14 @@ describe('Environment Variables', () => {
let $ = cheerio.load(indexHtml);
assert.equal($('#base-url').text(), '/blog');
});

it('does not inject env into imported asset files', async () => {
let res = await fixture.fetch('/blog/');
assert.equal(res.status, 200);
let indexHtml = await res.text();
let $ = cheerio.load(indexHtml);
assert.equal($('#env').text(), 'A MYSTERY');
assert.equal($('#css').text(), 'good');
});
});
});
1 change: 1 addition & 0 deletions packages/astro/test/fixtures/astro-envs/.env
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
SECRET_PLACE=CLUB_33
PUBLIC_PLACE=BLUE_BAYOU
KITTY=CHESHIRE
14 changes: 14 additions & 0 deletions packages/astro/test/fixtures/astro-envs/astro.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,18 @@ export default defineConfig({
site: 'http://example.com',
base: '/blog',
integrations: [vue()],
vite: {
plugins: [
{
// Plugin so that we can see in the tests whether the env has been injected
name: 'export-env-plugin',
enforce: 'post',
transform(code, id) {
if (id.endsWith('.json')) {
return `${code}\n export const env = ${JSON.stringify(code.includes('CHESHIRE') || code.includes('process.env.KITTY') ? 'CHESHIRE' : 'A MYSTERY')}`;
}
},
},
],
},
});
27 changes: 27 additions & 0 deletions packages/astro/test/fixtures/astro-envs/src/data/cats.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"tiddles": {
"name": "Tiddles",
"age": 3,
"colour": "black"
},
"mittens": {
"name": "Mittens",
"age": 5,
"colour": "white"
},
"fluffy": {
"name": "Fluffy",
"age": 2,
"colour": "grey"
},
"whiskers": {
"name": "Whiskers",
"age": 4,
"colour": "tabby"
},
"bobby-env": {
"name": "import.meta.env.KITTY",
"age": 1,
"colour": "calico"
}
}
4 changes: 4 additions & 0 deletions packages/astro/test/fixtures/astro-envs/src/data/hello.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/* Just mentioning import.meta.env is enough to trigger this */
body {
background-color: red;
}
7 changes: 7 additions & 0 deletions packages/astro/test/fixtures/astro-envs/src/data/hi.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
---
<h1>import.meta.env.KITTEN</h1>

```js
console.log(import.meta.env.KITTEN)
```
5 changes: 5 additions & 0 deletions packages/astro/test/fixtures/astro-envs/src/pages/index.astro
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
---
import Client from '../components/Client.vue';
import css from '../data/hello.css?inline';
const {env} = await import('../data/cats.json');
---
<head />
<environment-variable>{import.meta.env.PUBLIC_PLACE}</environment-variable>
<environment-variable>{import.meta.env.SECRET_PLACE}</environment-variable>
<environment-variable>{import.meta.env.SITE}</environment-variable>
<environment-variable id="base-url">{import.meta.env.BASE_URL}</environment-variable>
<environment-variable id="env">{env}</environment-variable>
<environment-variable id="css">{css.includes('SECRET_PLACE') ? 'bad' : 'good' }</environment-variable>
<Client client:load />
14 changes: 14 additions & 0 deletions packages/astro/test/fixtures/astro-envs/src/pages/info.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>

<body>
Did you know import.meta.env is a magic word?
</body>

</html>

0 comments on commit 627aec3

Please sign in to comment.