Skip to content

feat(nuxt): add support for required layers in nuxt config - #35653

Closed
hacknug wants to merge 2 commits into
nuxt:mainfrom
hacknug:hacknug/feat-required-layers
Closed

hacknug wants to merge 2 commits into
nuxt:mainfrom
hacknug:hacknug/feat-required-layers

Conversation

@hacknug

@hacknug hacknug commented Jul 18, 2026

Copy link
Copy Markdown
Contributor

🔗 Linked issue

Closes #33145.

📚 Description

This PR adds support to mark layers as required. When a required layer is missing nuxt will throw using nostics.

Let me know if you need me to make any changes before we can merge it 👍

@hacknug
hacknug requested a review from danielroe as a code owner July 18, 2026 17:23
Copilot AI review requested due to automatic review settings July 18, 2026 17:23
@github-actions github-actions Bot added 5.x ✨ enhancement New feature or improvement to existing functionality labels Jul 18, 2026
@coderabbitai

This comment has been minimized.

@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 `@packages/kit/src/loader/config.ts`:
- Around line 196-199: Update the required-layer validation around resolvedRoots
and NUXT_B8020 to compare against the layer’s actual resolved/downloaded
directory rather than resolving the raw source string. Preserve the existing
skip behavior for non-string or non-required sources, and ensure valid remote
Git or npm layers are matched correctly.
🪄 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: d4bbbdf4-c070-48c7-9dd4-36c1dd62c735

📥 Commits

Reviewing files that changed from the base of the PR and between e985b20 and 0f75af4.

📒 Files selected for processing (5)
  • docs/3.guide/6.going-further/7.layers.md
  • packages/kit/src/diagnostics/kit-api.ts
  • packages/kit/src/loader/config.ts
  • packages/kit/test/load-nuxt-config.spec.ts
  • packages/schema/src/types/schema.ts

Comment on lines +196 to +199
if (typeof source !== 'string' || !(options as { required?: boolean } | undefined)?.required) { continue }
if (!resolvedRoots.has(withoutTrailingSlash(resolve(baseDir, source)))) {
throw diagnostics.NUXT_B8020({ layer: source })
}

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Check `c12` layer types for original source metadata.
# Since we don't have the full workspace in the sandbox, we'll check the repository's `c12` usage or write a small node script.

cat << 'EOF' > test_c12.mjs
import { loadConfig } from 'c12'
import { join } from 'path'
import { writeFileSync, mkdirSync } from 'fs'

mkdirSync('test-layer', { recursive: true })
writeFileSync('test-layer/nuxt.config.ts', 'export default {}')

writeFileSync('nuxt.config.ts', `
export default {
  extends: [
    './test-layer'
  ]
}
`)

async function test() {
  try {
    const { layers } = await loadConfig({
      name: 'nuxt',
      configFile: 'nuxt.config',
      cwd: process.cwd()
    })
    console.log(JSON.stringify(layers.map(l => ({ source: l.source, cwd: l.cwd })), null, 2))
  } catch (err) {
    console.error(err)
  }
}
test()
EOF
npm install c12 pathe
node test_c12.mjs

Repository: nuxt/nuxt

Length of output: 2401


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the relevant loader code and nearby helpers.
file="packages/kit/src/loader/config.ts"
wc -l "$file"
sed -n '1,280p' "$file"

# Search for related source/roots handling in the kit loader.
rg -n "resolvedRoots|withoutTrailingSlash|extends|source" packages/kit/src/loader -g '!**/dist/**'

Repository: nuxt/nuxt

Length of output: 9061


🏁 Script executed:

#!/bin/bash
set -euo pipefail

rg -n "resolvedRoots|withoutTrailingSlash|NUXT_B8020|layer: source|resolve\(baseDir, source\)" packages/kit/src -g '!**/dist/**'

Repository: nuxt/nuxt

Length of output: 824


🌐 Web query:

c12 ConfigLayer source cwd remote npm extends layer.source docs

💡 Result:

In C12, a configuration layer represents an individual source of configuration that is merged into the final result [1][2]. The extends property within a configuration object allows you to compose your configuration from multiple layers, including local files, directories, npm packages, or remote git repositories [1][3]. Key Concepts and Behavior: * Extends: When a configuration object includes an extends key, C12 resolves these items recursively [1][3]. Each item can be an absolute path, a relative path (to the current config file), or a remote source [1][2]. * Remote Sources: C12 supports extending from remote sources like GitHub, GitLab, Bitbucket, or HTTPS URLs [1][4]. When a source starts with one of these prefixes, C12 automatically clones it [1][3]. * Peer Dependency Requirement: Extending from remote sources requires the giget peer dependency to be installed in your project [1][5]. * Layer Metadata: Each resolved layer contains metadata, including: * config: The actual configuration object for that layer [6][7]. * configFile: The path to the configuration file (e.g., config.ts) [6][7]. * cwd: The working directory associated with the layer [6][7]. * Merging: Layers are merged using unjs/defu, which provides a predictable and deep merging strategy [1][2]. You can access individual layers directly via the layers property returned by the loadConfig function to implement custom merging logic if needed [1][6]. For remote sources, you can pass additional options to the giget integration within your layer configuration [1][3]. For example, you can provide authentication tokens for private repositories or enable automatic dependency installation [2]. Example usage: ts // config.ts export default { extends: ["gh:user/repo", { auth: process.env.GITHUB_TOKEN, install: true }], }; For more comprehensive documentation on the layer system and available options, refer to the official UnJS C12 repository [1][2].

Citations:


🌐 Web query:

unjs c12 layer source property remote npm extends cwd source original specifier

💡 Result:

In the UnJS c12 library, the extends feature allows configuration to be inherited from multiple local or remote sources [1][2][3]. When extending, c12 resolves these layers and provides access to their metadata via the layers property in the final configuration object [1][3]. The layers property is an array of objects, where each object represents a specific configuration layer. While the specific properties of a layer may vary depending on the internal implementation, they generally include [1][3]: 1. config: The actual configuration object loaded from that layer [1][3]. 2. configFile: The absolute path to the configuration file (if applicable) [1][3]. 3. cwd: The current working directory associated with that specific layer [1][3]. Remote sources—such as npm packages or GitHub/GitLab/Bitbucket repositories—are supported via the extends key [1][2][3]. When a specifier starts with a remote prefix (e.g., github:, npm:), c12 uses the giget library to download/clone the source [1][3][4]. For remote sources, the "original specifier" is typically the string provided in the extends array (e.g., "github:user/repo"), which c12 then resolves to a local directory before loading the configuration file (usually config.ts or config.{name}.ts) [1][2][3]. If you need to configure how remote layers are fetched, you can pass options to the giget integration directly within the layer configuration or disable it by setting giget: false [1][3]. The final configuration is produced by deep-merging all layers (including overrides and defaults) using the defu library [1][2][3].

Citations:


Compare against the resolved layer directory, not source. source can be a remote Git or npm specifier, so resolve(baseDir, source) will not match the downloaded layer path and can raise NUXT_B8020 for a valid required layer.

🤖 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 `@packages/kit/src/loader/config.ts` around lines 196 - 199, Update the
required-layer validation around resolvedRoots and NUXT_B8020 to compare against
the layer’s actual resolved/downloaded directory rather than resolving the raw
source string. Preserve the existing skip behavior for non-string or
non-required sources, and ensure valid remote Git or npm layers are matched
correctly.

@pkg-pr-new

pkg-pr-new Bot commented Jul 18, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@nuxt/kit

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

@nuxt/nitro-server

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

nuxt

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

@nuxt/rspack-builder

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

@nuxt/schema

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

@nuxt/vite-builder

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

@nuxt/webpack-builder

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

commit: 2c067f7

Copilot AI 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.

Pull request overview

Adds a required flag for Nuxt config layers so missing/unresolvable layers fail fast with a diagnostic error, improving feedback when essential layers aren’t present.

Changes:

  • Adds a required-layer validation step during config loading and introduces a new kit diagnostic (NUXT_B8020).
  • Adds test coverage for required layers behavior and updates docs to document required: true.
  • Updates schema/docs comments to describe the new option.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
packages/kit/src/loader/config.ts Adds assertRequiredLayers to throw when a required layer is not present in resolved layers.
packages/kit/src/diagnostics/kit-api.ts Adds a new diagnostic code/message for missing required layers.
packages/kit/test/load-nuxt-config.spec.ts Adds tests covering required layers (resolved/missing/non-required).
packages/schema/src/types/schema.ts Documents required layers in the extends schema comments.
docs/3.guide/6.going-further/7.layers.md Documents required: true usage for layers.
Comments suppressed due to low confidence (1)

packages/schema/src/types/schema.ts:560

  • The new required option is documented, but extends is still typed in terms of c12's SourceOptions, and this implementation had to cast to access required. To avoid TS errors for end users ({ required: true } being rejected), widen the extends option type to include required?: boolean.
   * When a layer is marked as required (e.g. `['github:username/repoName', { required: true }]`), Nuxt will throw an error if the layer cannot be resolved or installed.
   *
   * @see [`c12` docs on extending config layers](https://github.com/unjs/c12#extending-config-layer-from-remote-sources)
   *
   * @see [`giget` documentation](https://github.com/unjs/giget)
   */
  extends: string | [string, SourceOptions?] | (string | [string, SourceOptions?])[]

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +183 to +187
const resolvedRoots = new Set(layers
.map(layer => layer.config?.rootDir ?? layer.cwd)
.filter((root): root is string => Boolean(root))
.map(root => withoutTrailingSlash(resolve(baseDir, root))),
)
Comment on lines +195 to +199
const [source, options] = Array.isArray(entry) ? entry : [entry]
if (typeof source !== 'string' || !(options as { required?: boolean } | undefined)?.required) { continue }
if (!resolvedRoots.has(withoutTrailingSlash(resolve(baseDir, source)))) {
throw diagnostics.NUXT_B8020({ layer: source })
}
Comment on lines +106 to +115
it('does not throw when all required layers are resolved', async () => {
await writeFile(join(tempDir, 'nuxt.config.ts'), `export default defineNuxtConfig({
extends: [
['./present-layer', { required: true }],
],
})`)
const config = await loadNuxtConfig({ cwd: tempDir })
expect(config._layers.map(l => l.cwd)).toContain(resolve(tempDir, 'present-layer'))
})

Comment on lines +173 to +181
::note
If a layer is essential to your project, you can mark it as `required`. When a required layer cannot be resolved or installed (for example, if you forgot to clone or install it), Nuxt will throw an error instead of silently continuing the build.

```ts [nuxt.config.ts]
export default defineNuxtConfig({
extends: [
['github:username/repoName', { required: true }],
],
})

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.

is this a valid comment @hacknug ?

@codspeed

codspeed Bot commented Jul 18, 2026 •

Copy link
Copy Markdown

Merging this PR will degrade performance by 24.39%

⚠️ Different runtime environments detected

Some benchmarks with significant performance changes were compared across different runtime environments,
which may affect the accuracy of the results.

Open the report in CodSpeed to investigate

❌ 1 regressed benchmark
✅ 20 untouched benchmarks
⏩ 3 skipped benchmarks1

Warning

Please fix the performance issues or acknowledge them on CodSpeed.

Performance Changes

Benchmark BASE HEAD Efficiency
❌ loadNuxtConfig in the basic test fixture (types) 16.7 ms 22.1 ms -24.39%

Tip

Investigate this regression by commenting @codspeedbot fix this regression on this PR, or directly use the CodSpeed MCP with your agent.


Comparing hacknug:hacknug/feat-required-layers (2c067f7) with main (5a4614b)2

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. ↩

  2. No successful run was found on main (20009ea) during the generation of this report, so 5a4614b was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

```ts [nuxt.config.ts]
export default defineNuxtConfig({
extends: [
['github:username/repoName', { required: true }],

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.

is this not something that c12/giget would currently throw on?

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

Labels

5.x ✨ enhancement New feature or improvement to existing functionality

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Ability to set a Nuxt layer as required

3 participants