Skip to content

feat(nuxt): expose import.meta.envName - #34844

Merged
danielroe merged 5 commits into
nuxt:mainfrom
onmax:feat/import-meta-env-name-4x
May 21, 2026
Merged

danielroe merged 5 commits into
nuxt:mainfrom
onmax:feat/import-meta-env-name-4x

Conversation

@onmax

@onmax onmax commented Apr 22, 2026 •

Copy link
Copy Markdown
Member

This exposes the resolved Nuxt config environment as import.meta.envName in app runtime code for both Vite and webpack builds. It also adds runtime typing and updates the v4 import-meta documentation.

The change includes focused coverage for the runtime value in the basic fixture and for custom envName resolution in the config loader tests.

Closes #30776
related #34843

@onmax
onmax requested a review from danielroe as a code owner April 22, 2026 07:04
@bolt-new-by-stackblitz

Copy link
Copy Markdown

Review PR in StackBlitz Codeflow Run & review this pull request in StackBlitz Codeflow.

@github-actions github-actions Bot added agentscan:mixed-signals 4.x ✨ enhancement New feature or improvement to existing functionality labels Apr 22, 2026
@pkg-pr-new

pkg-pr-new Bot commented Apr 22, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@nuxt/kit

npm i https://pkg.pr.new/@nuxt/kit@34844

@nuxt/nitro-server

npm i https://pkg.pr.new/@nuxt/nitro-server@34844

nuxt

npm i https://pkg.pr.new/nuxt@34844

@nuxt/rspack-builder

npm i https://pkg.pr.new/@nuxt/rspack-builder@34844

@nuxt/schema

npm i https://pkg.pr.new/@nuxt/schema@34844

@nuxt/vite-builder

npm i https://pkg.pr.new/@nuxt/vite-builder@34844

@nuxt/webpack-builder

npm i https://pkg.pr.new/@nuxt/webpack-builder@34844

commit: 1b32eee

@codspeed

codspeed Bot commented Apr 22, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 20 untouched benchmarks
⏩ 3 skipped benchmarks1


Comparing onmax:feat/import-meta-env-name-4x (1b32eee) with main (48b15c2)

Open in CodSpeed

Footnotes

  1. 3 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

@danielroe
danielroe force-pushed the feat/import-meta-env-name-4x branch from cda09d7 to 547fe27 Compare May 21, 2026 12:36
@danielroe
danielroe changed the base branch from 4.x to main May 21, 2026 12:37
@danielroe
danielroe requested review from atinux and pi0 May 21, 2026 13:07
@coderabbitai

coderabbitai Bot commented May 21, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 4d5a74ec-3c88-4059-8cc1-ce6d8aa604b7

📥 Commits

Reviewing files that changed from the base of the PR and between 66872dd and 1b32eee.

📒 Files selected for processing (2)
  • packages/schema/src/config/common.ts
  • packages/schema/src/types/schema.ts
💤 Files with no reviewable changes (1)
  • packages/schema/src/config/common.ts

Walkthrough

This pull request introduces import.meta.envName as a runtime-accessible property that exposes the current Nuxt environment name. The implementation adds a new configuration schema property, establishes a resolver that defaults to development or production based on the dev flag but respects explicit environment name arguments. The resolved value is injected into client and server Vite builds and Webpack configurations. Type augmentation extends the ImportMeta interface, and comprehensive tests verify type safety, configuration loading precedence, and runtime availability across build toolchains.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: exposing import.meta.envName as a new runtime property in Nuxt.
Description check ✅ Passed The description clearly relates to the changeset, explaining what import.meta.envName does, where it's exposed, and the coverage added for testing.
Linked Issues check ✅ Passed The PR fully implements the requirements from issue #30776: exposing import.meta.envName at runtime with support for custom environment names, runtime typing, and documentation updates.
Out of Scope Changes check ✅ Passed All changes are directly related to implementing import.meta.envName exposure across config loaders, type definitions, Vite/webpack builds, documentation, and tests as specified in issue #30776.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@test/basic.test.ts`:
- Line 159: The assertion is brittle because
page.getByTestId('env-name').textContent() returns raw text with surrounding
whitespace; update the test so you normalize the retrieved value before
asserting (e.g., trim or collapse whitespace) when comparing to
expectedEnvName—locate the call using getByTestId('env-name') and change the
comparison to use the normalized text (trimmed or matched with a flexible
matcher) against expectedEnvName.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 5636b6a2-1420-41af-b766-2e2d1ec99d2f

📥 Commits

Reviewing files that changed from the base of the PR and between 274d46b and 66872dd.

📒 Files selected for processing (13)
  • docs/4.api/6.advanced/2.import-meta.md
  • packages/kit/src/env.ts
  • packages/kit/src/loader/config.ts
  • packages/kit/test/load-nuxt-config.spec.ts
  • packages/nuxt/src/app/types/augments.ts
  • packages/schema/src/config/common.ts
  • packages/schema/src/types/schema.ts
  • packages/vite/src/shared/client.ts
  • packages/vite/src/shared/server.ts
  • packages/webpack/src/presets/base.ts
  • test/basic.test.ts
  • test/fixtures/basic-types/app/app-types.ts
  • test/fixtures/basic/app/pages/env-name.vue

Comment thread test/basic.test.ts
it('exposes the current env name at runtime', async () => {
const expectedEnvName = isDev ? 'development' : 'production'
const { page } = await renderPage('/env-name')
expect(await page.getByTestId('env-name').textContent()).toBe(expectedEnvName)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect around the reported line and also find expectedEnvName definition/usage.
echo "== test/basic.test.ts (around 130-180) =="
sed -n '120,190p' test/basic.test.ts

echo
echo "== Find where expectedEnvName is defined (within file) =="
rg -n "expectedEnvName" test/basic.test.ts

echo
echo "== Show some broader context around any template/fixture rendering mentioning env-name =="
rg -n "env-name" test/basic.test.ts

Repository: nuxt/nuxt

Length of output: 3627


🌐 Web query:

Playwright Locator.textContent() includes whitespace newlines textContent() behavior recommended to use innerText or toHaveText trim

💡 Result:

When working with text in Playwright, understanding the differences between methods and assertions is crucial for avoiding flaky tests caused by whitespace and hidden elements [1][2]. textContent vs. innerText The locator.textContent method returns the raw text content of a node and all its descendants [1][3]. It includes all whitespace (including newlines) and retrieves text from both visible and hidden elements [2][3]. In contrast, locator.innerText retrieves the visible text content of an element [2][4][3]. Because it is "visible-text aware," it requires layout information, making it more performance-heavy than textContent [3]. It generally aligns more closely with what a user sees on the screen, as it excludes hidden text [2][3]. Recommended Assertion Practice To avoid flakiness and manage whitespace issues, the official Playwright recommendation is to prefer web-first assertions over manual extraction [1]. Instead of manually extracting text with textContent and comparing it, use the built-in assertion expect(locator).toHaveText or expect(locator).toContainText [1][5][6]. These assertions are designed to be resilient [7][8]. Key points regarding whitespace and assertions: 1. Normalization: Playwright's text-based matching (including locators like getByText and assertions like toHaveText) automatically normalizes whitespace [9][10][1]. This means it treats multiple spaces as a single space and ignores leading/trailing whitespace, which is usually the desired behavior for reliable tests [9][11]. 2. Avoiding Flakiness: If you manually extract text using textContent and try to trim or regex it yourself, you risk introducing race conditions [1]. Web-first assertions (expect(locator).toHaveText) include built-in retry logic that waits for the element to reach the expected state, significantly reducing flakiness [1][7][8]. 3. Flexible Matching: If you need to verify that an element contains specific text while ignoring surrounding whitespace, use expect(locator).toContainText [12][13]. If you need to perform more complex logic, you can use regular expressions within these assertions (e.g., await expect(locator).toHaveText(/\S/)) [12]. In summary, avoid manual text extraction for validation [1]. Use expect(locator).toHaveText or expect(locator).toContainText to handle whitespace normalization and waiting logic automatically [1][6].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== Search for env-name test id usage =="
rg -n "data-testid=['\"]env-name['\"]|getByTestId\\('env-name'\\)|\"env-name\"" -S . --hidden --glob '!.git/*' --glob '*.ts' --glob '*.js' --glob '*.vue' --glob '*.tsx' --glob '*.md'

echo
echo "== Search for route '/env-name' implementation =="
rg -n "['\"]\\/env-name['\"]|/env-name" -S . --hidden --glob '!.git/*' --glob '*.ts' --glob '*.js' --glob '*.vue'

Repository: nuxt/nuxt

Length of output: 447


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== env-name.vue =="
nl -ba test/fixtures/basic/app/pages/env-name.vue | sed -n '1,120p'

echo
echo "== Find references to '/env-name' (safe patterns) =="
rg -n "/env-name" -S test test/fixtures --glob '!*node_modules*' || true

Repository: nuxt/nuxt

Length of output: 133


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== env-name.vue (with line numbers) =="
cat -n test/fixtures/basic/app/pages/env-name.vue | sed -n '1,120p'

Repository: nuxt/nuxt

Length of output: 308


Whitespace-sensitive assertion on env-name (Line 159)

env-name.vue renders {{ envName }} with leading/trailing newlines/indentation inside the data-testid="env-name" element; Locator.textContent() reads raw text including that whitespace, so toBe(expectedEnvName) can be brittle/flaky.

Suggested fix
-    expect(await page.getByTestId('env-name').textContent()).toBe(expectedEnvName)
+    expect((await page.getByTestId('env-name').textContent())?.trim()).toBe(expectedEnvName)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
expect(await page.getByTestId('env-name').textContent()).toBe(expectedEnvName)
expect((await page.getByTestId('env-name').textContent())?.trim()).toBe(expectedEnvName)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@test/basic.test.ts` at line 159, The assertion is brittle because
page.getByTestId('env-name').textContent() returns raw text with surrounding
whitespace; update the test so you normalize the retrieved value before
asserting (e.g., trim or collapse whitespace) when comparing to
expectedEnvName—locate the call using getByTestId('env-name') and change the
comparison to use the normalized text (trimmed or matched with a flexible
matcher) against expectedEnvName.

@atinux atinux left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like the idea of having a way to have an in-between between dev and prod, many companies need to enable special flags for "staging" for instance, this is a nice way to solve it

@danielroe
danielroe merged commit 20c5662 into nuxt:main May 21, 2026
30 of 31 checks passed
@github-actions github-actions Bot mentioned this pull request May 21, 2026
2 of 5 tasks
@onmax
onmax deleted the feat/import-meta-env-name-4x branch May 21, 2026 19:26
@github-actions github-actions Bot mentioned this pull request May 22, 2026
danielroe pushed a commit that referenced this pull request Jun 2, 2026
danielroe pushed a commit that referenced this pull request Jun 2, 2026
danielroe pushed a commit that referenced this pull request Jun 8, 2026
@github-actions github-actions Bot mentioned this pull request Jul 18, 2026
@luc122c

luc122c commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

Hey, sorry to piggy-back on this PR. Will this tree-shake at build time? For example:

if (import.meta.envName === 'staging') {
  // this entire of block will not be incuded in the production bundle
}

@onmax

onmax commented Jul 19, 2026 •

Copy link
Copy Markdown
Member Author

Yes, as I understand it:

  1. During the build, Nuxt relpaces import.meta.envName with a string literal:
    if (import.meta.envName === 'staging')
    // becomes
    if ('production' === 'staging')
  2. The minifier then removes the unreachable block.

If you build with --envName staging, the condition is true and the block remains.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

4.x agentscan:mixed-signals ✨ enhancement New feature or improvement to existing functionality

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add import.meta.envName for build EnvName

4 participants