Skip to content

Conversation

BobbieGoede
Copy link
Member

@BobbieGoede BobbieGoede commented Sep 4, 2025

🔗 Linked issue

📚 Description

This may work without too much changes, but it feels suboptimal.

With these changes, the warning trace will include the name of the global middleware.

Copy link

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

Copy link

coderabbitai bot commented Sep 4, 2025

Walkthrough

The middleware template in packages/nuxt/src/core/templates.ts now accepts { app, nuxt } and introduces dev-only alias handling using reverseResolveAlias and strippedAtAliases. In development, it builds internal maps: _globalMiddleware and _namedMiddleware, annotates loaded middleware with a _path, and exports globalMiddleware via Object.values(...) and namedMiddleware via Object.fromEntries(...). Production paths keep prior behaviour without alias resolution. Router plugins in packages/nuxt/src/app/plugins/router.ts and packages/nuxt/src/pages/runtime/plugins/router.ts now set nuxtApp._processingMiddleware from a middleware’s _path (falling back to previous values) during development.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
packages/nuxt/src/core/templates.ts (1)

341-341: Prefer knitwork helpers over JSON.stringify for consistency

Minor style nit: use genArrayFromRaw + genString to mirror surrounding codegen patterns and ensure consistent escaping.

Apply:

-      `export const globalMiddlewareNameMap = ${JSON.stringify(globalMiddleware.map(mw => mw.name))}`,
+      `export const globalMiddlewareNameMap = ${genArrayFromRaw(globalMiddleware.map(mw => genString(mw.name)))}`,
packages/nuxt/src/pages/runtime/plugins/router.ts (1)

225-229: Avoid unnecessary indexOf for string entries

Tiny optimisation/readability: only look up the index for function entries; strings cannot be in globalMiddleware.

Apply:

-            if (import.meta.dev) {
-              nuxtApp._processingMiddleware = globalMiddlewareNameMap[globalMiddleware.indexOf(entry)] || (typeof entry === 'string' ? entry : middleware.name) || true
-            }
+            if (import.meta.dev) {
+              const idx = typeof entry !== 'string' ? globalMiddleware.indexOf(entry) : -1
+              nuxtApp._processingMiddleware =
+                (idx !== -1 ? globalMiddlewareNameMap[idx] : undefined) ||
+                (typeof entry === 'string' ? entry : middleware.name) ||
+                true
+            }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 1cd8a68 and 4891c6a.

📒 Files selected for processing (3)
  • packages/nuxt/src/app/plugins/router.ts (2 hunks)
  • packages/nuxt/src/core/templates.ts (1 hunks)
  • packages/nuxt/src/pages/runtime/plugins/router.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Follow standard TypeScript conventions and best practices

Files:

  • packages/nuxt/src/core/templates.ts
  • packages/nuxt/src/pages/runtime/plugins/router.ts
  • packages/nuxt/src/app/plugins/router.ts
🔇 Additional comments (4)
packages/nuxt/src/core/templates.ts (1)

341-341: LGTM: exposing a stable name map for dev tooling is sensible

The export aligns well with how globalMiddleware is generated and should improve _processingMiddleware labelling in dev.

packages/nuxt/src/app/plugins/router.ts (2)

11-11: LGTM: importing the name map from the generated module

The new import is correctly gated by the existing virtual-file comment and matches the middleware template export.


271-271: Dev-only labelling now maps by index — good fallback behaviour

Using the index into globalMiddleware with a fallback to middleware.name || true is robust and keeps behaviour unchanged outside dev.

packages/nuxt/src/pages/runtime/plugins/router.ts (1)

22-22: LGTM: added import for the name map

Matches the new export in #build/middleware and keeps the virtual-file typing suppression consistent.

Copy link

codspeed-hq bot commented Sep 4, 2025

CodSpeed Performance Report

Merging #33136 will not alter performance

Comparing BobbieGoede:fix/global-route-middleware-names (851cbe4) with main (911ce76)

Summary

✅ 10 untouched benchmarks

Copy link

pkg-pr-new bot commented Sep 4, 2025

Open in StackBlitz

@nuxt/kit

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

nuxt

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

@nuxt/rspack-builder

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

@nuxt/schema

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

@nuxt/vite-builder

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

@nuxt/webpack-builder

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

commit: 851cbe4

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
test/bundle.test.ts (2)

41-41: Avoid snapshot brittleness for bundle size; assert within a small range instead.

Bundle size tends to drift by ~1–2 kB with harmless codegen changes; using a strict inline snapshot makes this test flaky.

-    expect.soft(roundToKilobytes(clientStats!.totalBytes)).toMatchInlineSnapshot(`"171k"`)
+    // Allow minor variance from code generation and dependency updates
+    expect.soft(clientStats!.totalBytes).toBeGreaterThanOrEqual(170 * 1024)
+    expect.soft(clientStats!.totalBytes).toBeLessThanOrEqual(173 * 1024)

98-98: Use numeric bounds instead of an exact snapshot for server bundle size (inlined).

Small, non-functional changes can shift this value; prefer a tolerance to reduce flaky failures.

-    expect.soft(roundToKilobytes(serverStats.totalBytes)).toMatchInlineSnapshot(`"549k"`)
+    // Allow minor variance from bundler/codegen changes
+    expect.soft(serverStats.totalBytes).toBeGreaterThanOrEqual(546 * 1024)
+    expect.soft(serverStats.totalBytes).toBeLessThanOrEqual(552 * 1024)
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 3daa013 and 733206d.

📒 Files selected for processing (1)
  • test/bundle.test.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Follow standard TypeScript conventions and best practices

Files:

  • test/bundle.test.ts
**/*.{test,spec}.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Write unit tests for core functionality using vitest

Files:

  • test/bundle.test.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: codeql (javascript-typescript)
  • GitHub Check: build
  • GitHub Check: code

@BobbieGoede BobbieGoede changed the title fix(nuxt): global route middleware name map fix(nuxt): global route middleware name in warning Sep 4, 2025
Comment on lines 342 to 344
`for (const name in _globalMiddleware) {`,
` Object.defineProperty(_globalMiddleware[name], 'name', { value: name })`,
`}`,
Copy link
Member

Choose a reason for hiding this comment

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

we should only do this in dev mode, and likely only if the function doesn't already have a name....

Copy link
Member Author

Choose a reason for hiding this comment

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

done! now it uses the original export/implementation outside dev mode, this way the dev logic/variable is tree-shaken out.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ Duplicate comments (1)
packages/nuxt/src/core/templates.ts (1)

342-347: Dev-only and “only-if-unnamed” logic acknowledged.

This aligns with prior feedback; keep this behaviour with the array-based approach.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 733206d and 8ceb682.

📒 Files selected for processing (1)
  • packages/nuxt/src/core/templates.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Follow standard TypeScript conventions and best practices

Files:

  • packages/nuxt/src/core/templates.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: code

@danielroe
Copy link
Member

have I made it too complicated?

it prints out this:

Screenshot 2025-09-04 at 21 23 21

previously:

Screenshot 2025-09-04 at 21 22 53

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (4)
packages/nuxt/src/pages/runtime/plugins/router.ts (1)

225-229: Preserve fallback to middleware function name for better dev diagnostics

If _path is missing (e.g. programmatically-registered middleware), falling back to true degrades warning clarity. Keep the previous middleware.name fallback.

-              nuxtApp._processingMiddleware = (middleware as any)._path || (typeof entry === 'string' ? entry : true)
+              nuxtApp._processingMiddleware = (middleware as any)._path
+                || (typeof entry === 'string' ? entry : (middleware as any).name)
+                || true
packages/nuxt/src/app/plugins/router.ts (1)

269-273: Retain name fallback when _path is absent

Same rationale as pages runtime: keep middleware.name before falling back to true to improve dev-time warnings.

-              nuxtApp._processingMiddleware = (middleware as any)._path || true
+              nuxtApp._processingMiddleware = (middleware as any)._path
+                || (middleware as any).name
+                || true
packages/nuxt/src/core/templates.ts (2)

346-364: Make _path properties configurable to avoid dev-time surprises

Defining _path as non-configurable/non-writable can hinder HMR or wrappers that may want to redefine it. Mark as configurable: true.

-            for (const path in _globalMiddleware) {
-              Object.defineProperty(_globalMiddleware[path], '_path', { value: path })
-            }
+            for (const path in _globalMiddleware) {
+              Object.defineProperty(_globalMiddleware[path], '_path', { value: path, configurable: true })
+            }
@@
-            mw.import = () => i().then(r => {
-              Object.defineProperty(r.default || r, '_path', { value: mw.path })
-              return r
-            })
+            mw.import = () => i().then(r => {
+              Object.defineProperty(r.default || r, '_path', { value: mw.path, configurable: true })
+              return r
+            })

677-680: Tiny doc hint for maintainers

Add a short comment explaining why @/@@ are stripped (to surface real file-ish paths in warnings).

-const strippedAtAliases = {
+// Normalise common Nuxt aliases in dev warnings for readability
+const strippedAtAliases = {
   '@': '',
   '@@': '',
 }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between a01eb8b and 851cbe4.

📒 Files selected for processing (3)
  • packages/nuxt/src/app/plugins/router.ts (1 hunks)
  • packages/nuxt/src/core/templates.ts (3 hunks)
  • packages/nuxt/src/pages/runtime/plugins/router.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Follow standard TypeScript conventions and best practices

Files:

  • packages/nuxt/src/app/plugins/router.ts
  • packages/nuxt/src/pages/runtime/plugins/router.ts
  • packages/nuxt/src/core/templates.ts
🧠 Learnings (1)
📓 Common learnings
Learnt from: GalacticHypernova
PR: nuxt/nuxt#26468
File: packages/nuxt/src/components/plugins/loader.ts:24-24
Timestamp: 2024-11-05T15:22:54.759Z
Learning: In `packages/nuxt/src/components/plugins/loader.ts`, the references to `resolve` and `distDir` are legacy code from before Nuxt used the new unplugin VFS and will be removed.
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: build
  • GitHub Check: code
🔇 Additional comments (4)
packages/nuxt/src/core/templates.ts (4)

9-9: LGTM: import reverseResolveAlias

Import location is correct and used only in dev code paths.


334-334: LGTM: widened getContents signature

Using { app, nuxt } is compatible with existing template invocation and required for alias handling.


337-337: LGTM: dev-only alias map

Merging nuxt.options.alias with stripped @/@@ is sensible for user-facing paths in warnings.


346-351: Order and deduplication check

Using an object keyed by resolved path and Object.values preserves insertion order but will drop duplicates sharing the same resolved path. That’s unlikely in practice; calling it out for awareness.

Would you like me to add a tiny generator-side assertion to warn if duplicate paths are detected in dev?

@danielroe danielroe changed the title fix(nuxt): global route middleware name in warning fix(nuxt): print route middleware path in warning Sep 5, 2025
@BobbieGoede
Copy link
Member Author

BobbieGoede commented Sep 5, 2025

We could print/add the full path of the middleware to the stack trace if it isn't in there too 👀 the alias path is nice but it doesn't click through to file (at least in my local project)

This is what is printed with the reproduction from #31029
image

@danielroe
Copy link
Member

tricky one

the difficulty is - sometimes middleware will already be in the stack trace, but if it isn't, then it's not part of the call stack at all (e.g. separated with an async call somewhere) so it would be misleading to print it.

@danielroe
Copy link
Member

Let's stick with the alias path in the warning itself, as this is what we do for other warnings.

@danielroe danielroe merged commit 27dc1f2 into nuxt:main Sep 5, 2025
83 of 84 checks passed
@github-actions github-actions bot mentioned this pull request Sep 5, 2025
This was referenced Sep 5, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants