Skip to content

Dev: astro:env/server virtual module corrupted when any env var contains $ — String.replace` pattern substitution #18329

Closed

Description

@Samuteg

Astro Info

Astro                    v7.3.6
Node                     v26.10.0 (also affects Node 22)
System                   Linux (x64)
Package Manager          pnpm
Output                   static
Adapter                  none
Integrations             keystatic (not required to reproduce, see below)

Describe the Bug

In dev, the generated astro:env/server virtual module fails to parse with:

[ERROR] Failed to parse source for import analysis because the content contains invalid JS syntax. If you are using JSX, make sure to name the file with the .jsx or .tsx extension.
  Stack trace:
    at astro:env/server:17:863

Root cause (packages/astro/src/env/vite-plugin-env.ts, getTemplates()):

server = server.replace('// @@GET_ENV@@', `return (${JSON.stringify(loadedEnv)})[key];`);

The replacement is passed as a string, so any $ patterns ($\`` , $&, $', $1, …) inside JSON.stringify(loadedEnv) are interpreted as replacement patterns instead of literal text. When any environment variable contains e.g. `` $ ``, the template prefix gets injected into the middle of the inlined env JSON, producing an unterminated string literal on line 17 (the // @@GET_ENV@@ line).

This is trivially triggerable in the real world: the Kitty terminal exports KITTY_PUBLIC_KEY=1:… by default, whose value commonly contains $ followed by a backtick. So every Kitty user importing astro:env/server in astro dev hits this. Any secret in .env containing $&/$\`` breaks it too. astro build` is unaffected (env is not inlined there).

I verified this by replicating the generation and parsing with esbuild: string replacement → ERROR: Unterminated string literal at exactly 17:863 (matching the dev server error); function replacement → parses fine.

Reproduction (minimal, no Keystatic needed)

  1. Minimal Astro project with any SSR module importing astro:env/server, e.g. src/pages/api/test.ts:
    import { getSecret } from 'astro:env/server';
    export const GET = () => new Response('ok');
  2. Run dev with a hostile env var: FOO='a$\b' astro dev(or just use the Kitty terminal, which setsKITTY_PUBLIC_KEY`).
  3. Request the route → the [ERROR] Failed to parse source… at astro:env/server:17:… appears and the page/client fails to load the module.

What's the expected result?

The generated module must be valid JS regardless of env var contents.

Proposed fix

One line — use a replacer function (immune to $ patterns):

- server = server.replace('// @@GET_ENV@@', `return (${JSON.stringify(loadedEnv)})[key];`);
+ server = server.replace('// @@GET_ENV@@', () => `return (${JSON.stringify(loadedEnv)})[key];`);

(Same latent pattern exists one line above for // @@ON_SET_GET_ENV@@, but its input is schema keys rather than arbitrary process env.)

Participation

  • I am willing to submit a pull request for this issue.

Activity

  1. added
    triage: in progress
    on Oct 10, 2026
  2. astro-factory commented on Oct 10, 2026

    @astro-factory
    Contributor

    Triage complete

    • Prepare the workspace: ready
    • Install dependencies: complete
    • Build the project: complete
    • Reproduce the issue: confirmed
    • Diagnose the cause: high confidence
    • Verify the diagnosis: bug
    • Attempt a fix: verified
    • Publish the result: set triage: fix pending

    • Reproduced: Yes
    • Exploration: Yes — View branch
    • Unit Test: Yes — packages/astro/test/units/env/vite-plugin-env.test.ts
    • Priority: P3: minor bug. This only happens in astro dev, and only when some env var contains $ sequences (for example Kitty's KITTY_PUBLIC_KEY). astro build is not affected.

    Your analysis is correct. In getTemplates() in packages/astro/src/env/vite-plugin-env.ts, the dev env is inlined with String.prototype.replace using a string as the replacement, so $`, $&, $' and $$ inside JSON.stringify(loadedEnv) are treated as replacement patterns. With $`, the template text that comes before the placeholder gets pasted into a JSON string literal, which breaks line 17 of the generated module. The other patterns change values without any error (for example, $$ becomes $). Build is not affected because loadedEnv is null there.

    I found a potential fix for this issue. It's the one-line change you proposed: use function replacers for the // @@GET_ENV@@ replacement, and also for the // @@ON_SET_GET_ENV@@ one, because $ is a valid identifier character in schema keys. It needs review by a maintainer.

    Try this fix

    You can test this fix right now without waiting for a release:

    # astro
    npm i https://pkg.pr.new/astro@f9d681c

    If this fixes your issue, please leave a comment letting us know (for example
    "confirmed, this fixes it"). A pull request will then be opened to get it merged.

    Full Triage Report

    Reproduction

    Environment: Astro 7.3.8 (built from the monorepo packages/astro), Node.js (sandbox), minimal example with no adapter.

    1. Copied examples/minimal into the triage directory.
    2. Added src/pages/api/test.ts:
      import { getSecret } from 'astro:env/server';
      export const prerender = false;
      export const GET = () => new Response('ok:' + typeof getSecret);
    3. Ran FOO='a$`b' astro dev, then curl /api/test.

    Result: The page returned an error, and the server logged:

    [ERROR] Failed to parse source for import analysis because the content contains invalid JS syntax. If you are using JSX, make sure to name the file with the .jsx or .tsx extension.
      Stack trace:
        at  astro:env/server:17:30
    

    Baseline: Without FOO, the same request returned ok:function with status [200].

    Diagnosis

    File: packages/astro/src/env/vite-plugin-env.ts, getTemplates(), around lines 202–206:

    server = server.replace('// @@ON_SET_GET_ENV@@', onSetGetEnv);
    if (loadedEnv) {
    	server = server.replace('// @@GET_ENV@@', `return (${JSON.stringify(loadedEnv)})[key];`);
    } else {
    	server = server.replace('// @@GET_ENV@@', 'return _getEnv(key);');
    }
    • In dev, loadedEnv holds the whole loaded env, including process.env (loadedEnv: isBuild ? null : loadedEnv).
    • Because the replacement is a string, $ patterns in it get expanded. $` inserts the beginning of templates/env.mjs, which contains newlines, so the string literal is never closed. The // @@GET_ENV@@ placeholder sits on line 17 of that template, which matches the error position.
    • A quick check in Node shows that {FOO:"a$`b"} produces return ({"FOO":"a<template prefix>b"})[key];, while a function replacer keeps the value as-is.
    • Confidence: high.

    Verification

    • Verdict: bug (high confidence).
    • No comment, guard or test suggests anyone considered $ handling here.
    • The GET_ENV line was added in a9373c0 ("fix: do not freeze process.env in dev (fix: do not freeze process.env in dev #12585)", 2024-12). The ON_SET_GET_ENV line has been there since astro:env was introduced (41121fb).
    • Valid JS that returns the exact env values is clearly the intended output.

    Fix

    -	server = server.replace('// @@ON_SET_GET_ENV@@', onSetGetEnv);
    +	// Function replacers keep `$` sequences (e.g. `$&`, "$`") in keys and env values literal
    +	server = server.replace('// @@ON_SET_GET_ENV@@', () => onSetGetEnv);
     	if (loadedEnv) {
    -		server = server.replace('// @@GET_ENV@@', `return (${JSON.stringify(loadedEnv)})[key];`);
    +		server = server.replace('// @@GET_ENV@@', () => `return (${JSON.stringify(loadedEnv)})[key];`);
    • Rerun of the reproduction: with FOO='a$`b$&c' astro dev, /api/test returns [200] and there is no parse error.
    • Unit test: packages/astro/test/units/env/vite-plugin-env.test.ts builds the astroEnv plugin in serve mode with a stub env loader. It loads \0astro:env/server and checks that the inlined env JSON appears unchanged for the values a$`b and c$&d$'e$$f. It fails without the fix and passes with it. All 34 tests in test/units/env/* pass.
    • Changeset: .changeset/ten-poets-pull.md (astro: patch).
    • Alternative considered: escaping $ as $$ would also work, but the function replacer is simpler and is the usual way to do this.
    • Side note: while writing the edit, a node -e script that used String.replace with a string replacement corrupted the source file in exactly the way described in this issue.

    This report was made by an LLM. The analysis may be wrong, and the potential fix might not work, but is intended as a starting point for exploring the issue.

  3. added
    - P3: minor bug
    pkg: astro
    triage: fix pending
    and removed
    triage: in progress
    on Oct 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

- P3: minor bugpkg: astrotriage: fix pending

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions