Skip to content

fix(nuxt): use fresh route when <NuxtLayout> first renders #24673

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
May 17, 2025

Conversation

huang-julien
Copy link
Member

@huang-julien huang-julien commented Dec 10, 2023

πŸ”— Linked issue

resolve #24642

❓ Type of change

  • πŸ“– Documentation (updates to the documentation, readme or JSdoc annotations)
  • 🐞 Bug fix (a non-breaking change that fixes an issue)
  • πŸ‘Œ Enhancement (improving an existing functionality like performance)
  • ✨ New feature (a non-breaking change that adds functionality)
  • 🧹 Chore (updates to the build process or auxiliary tools and libraries)
  • ⚠️ Breaking change (fix or feature that would cause existing functionality to change)

πŸ“š Description

Hi πŸ‘‹ this PR sync nuxtApp._route for NuxtLayout

edited:

this PR updated useRoute() within layouts to use the vue-router route if the layout is rendering for the first time in a page transition

I've marked two TODOs in the test - these aren't regressions from this PR but issues I spotted and which we could ultimately fix.

πŸ“ Checklist

  • I have linked an issue or discussion.
  • I have updated the documentation accordingly.

Copy link

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

@github-actions github-actions bot added the 3.x label Dec 10, 2023
@codecov-commenter
Copy link

Codecov Report

All modified and coverable lines are covered by tests βœ…

❗ No coverage uploaded for pull request base (main@caef295). Click here to learn what that means.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #24673   +/-   ##
=======================================
  Coverage        ?   58.65%           
=======================================
  Files           ?        5           
  Lines           ?      861           
  Branches        ?       46           
=======================================
  Hits            ?      505           
  Misses          ?      356           
  Partials        ?        0           

β˜” View full report in Codecov by Sentry.
πŸ“’ Have feedback on the report? Share it here.

@danielroe danielroe changed the title fix(nuxt): assign route without reactivity afterEach fix(nuxt): use fresh route when <NuxtLayout> first renders May 17, 2025
@danielroe danielroe marked this pull request as ready for review May 17, 2025 15:31
Copy link

coderabbitai bot commented May 17, 2025

Walkthrough

The changes introduce a refined mechanism for handling route reactivity within the NuxtLayout component and its LayoutProvider child. A new prop, isRenderingNewLayout, is added to LayoutProvider to determine if a new layout is being rendered, enabling conditional use of either the injected route or a synchronously updated route. The LayoutProvider now provides a shallow reactive proxy for the route based on the layout rendering state. Tests for NuxtLayout are added to verify layout and page rendering behaviour, including deferred page resolution. Minor adjustments are also made to bundle size test expectations and the catchall route's rendered output.

Note

⚑️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚑️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boostβ€”your workflow just got faster.


πŸ“œ Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 1c0b22e and 8037b7e.

πŸ“’ Files selected for processing (1)
  • packages/nuxt/src/app/components/nuxt-layout.ts (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/nuxt/src/app/components/nuxt-layout.ts
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: codeql (javascript-typescript)
  • GitHub Check: code
  • GitHub Check: build
✨ Finishing Touches
  • πŸ“ Generate Docstrings
πŸ§ͺ Generate Unit Tests
  • Create PR with Unit Tests
  • Commit Unit Tests in branch fix/layout-route
  • Post Copyable Unit Tests in 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.
    • Explain this complex logic.
    • 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. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai 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

Documentation and Community

  • 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: 1

🧹 Nitpick comments (4)
packages/nuxt/src/app/components/nuxt-layout.ts (2)

129-133: Prefer an explicit PropType over bare Function

Typing props with the generic PropType gives clearer IDE hints and prevents accidental misuse.

-  isRenderingNewLayout: {
-    type: Function as unknown as () => (name?: string | boolean) => boolean,
-    required: true,
-  },
+  isRenderingNewLayout: {
+    type: Object as PropType<(name?: string | boolean) => boolean>,
+    required: true,
+  },

151-163: Dynamic property-proxy incurs per-navigation defineProperty cost

Creating a fresh object and redefining every property on each navigation can add noticeable overhead when the route object contains many keys. Consider a lighter approach:

  1. Use shallowReactive({ _: vueRouterRoute }) and expose a single computed getter, or
  2. Cache the proxied object per layout instance and only swap the underlying source reference instead of re-defining descriptors.

Not urgent, but worthwhile for high-traffic apps.

test/nuxt/nuxt-layout.test.ts (1)

95-97: Avoid delete for performance – mutate instead

Static analysis flags delete layouts.test. Setting the entry to undefined (or calling router.removeRoute) sidesteps the hidden de-opt.

-  delete layouts.test
+  // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
+  // layouts.test = undefined     // keeps object shape JIT-friendly
+  // or, if available:
+  // router.removeRoute('layout-slug')
🧰 Tools
πŸͺ› Biome (1.9.4)

[error] 96-96: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

test/bundle.test.ts (1)

120-120: Consider reducing brittleness of bundle size tests.

A strict inline snapshot for bundle size can lead to frequent test churn as the bundle evolves. You may want to use a tolerance or range-based assertion (for example, expect(bytes).toBeLessThanOrEqual(300 * 1024)) to make this test more resilient.

πŸ“œ Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 146acb7 and ef0a5a3.

πŸ“’ Files selected for processing (4)
  • packages/nuxt/src/app/components/nuxt-layout.ts (6 hunks)
  • test/bundle.test.ts (1 hunks)
  • test/nuxt/nuxt-layout.test.ts (1 hunks)
  • test/runtime/app/router.options.ts (2 hunks)
🧰 Additional context used
πŸͺ› Biome (1.9.4)
test/nuxt/nuxt-layout.test.ts

[error] 96-96: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: lint-docs
  • GitHub Check: build
  • GitHub Check: code
πŸ”‡ Additional comments (3)
test/runtime/app/router.options.ts (1)

12-13: Return value now explicit – good defensive change

Rendering a simple <div> with the help of h() avoids the previous β€œempty‐render” edge-case where some test runners choke on falsy VNodes. The additional import of h completes the change.

test/nuxt/nuxt-layout.test.ts (1)

13-14: useRouter() relies on auto-imports – add explicit import to avoid fragile tests

In the test environment auto-imports are sometimes disabled, causing useRouter to be undefined. Importing it directly prevents silent failures:

-import { useRoute } from '#app/composables/router'
+import { useRoute, useRouter } from '#app/composables/router'
test/bundle.test.ts (1)

120-120: Approve updated snapshot for new server bundle size.

The inline snapshot expectation has been updated from "282k" to "283k" to reflect the increase in the server bundle size introduced by recent layout and routing changes.

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/app/components/nuxt-layout.ts (2)

59-59: Non-null assertions are used safely but consider refining type safety

The non-null assertions (!) are used in a context where the code logic ensures the route is defined, making them safe. However, it might be better to use type guards or default values to avoid the need for assertions.

-let layout = unref(props.name) ?? route!.meta.layout as string ?? 'default'
+let layout = unref(props.name) ?? (route?.meta.layout as string) ?? 'default'

-const transitionProps = route!.meta.layoutTransition ?? defaultLayoutTransition
+const transitionProps = route?.meta.layoutTransition ?? defaultLayoutTransition

Also applies to: 88-88


145-165: Excellent route proxy implementation for handling fresh routes

The proxy implementation is very well done. It:

  1. Checks if the component is outside of <NuxtPage>
  2. Creates a dynamic proxy for the route that selectively uses either:
    • The eager route when rendering a new layout (ensuring fresh data)
    • The lazy route otherwise (maintaining compatibility with existing behavior)
  3. Makes the proxy reactive with shallowReactive

This addresses the core issue of the PR by ensuring layouts always use fresh route data on first render.

However, I suggest adding a brief comment explaining why shallowReactive is used instead of reactive. The shallow version will only track changes to the top-level properties of the route, which is sufficient for this use case and more performant.

-      provide(PageRouteSymbol, shallowReactive(reactiveChildRoute))
+      // Using shallowReactive as we only need to track top-level route properties
+      provide(PageRouteSymbol, shallowReactive(reactiveChildRoute))
πŸ“œ Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 88bd7e0 and 1c0b22e.

πŸ“’ Files selected for processing (1)
  • packages/nuxt/src/app/components/nuxt-layout.ts (6 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: build
  • GitHub Check: codeql (javascript-typescript)
  • GitHub Check: codeql (actions)
  • GitHub Check: code
πŸ”‡ Additional comments (5)
packages/nuxt/src/app/components/nuxt-layout.ts (5)

54-56: Good approach to determining when to use eager route

The logic to determine when to use the eager route is clear and includes good comments explaining each condition. This approach ensures that route is always defined, addressing the issue mentioned in the previous review comments.


84-84: Good technique for tracking layout changes

Using lastLayout to track the previously rendered layout is an effective approach. This allows the component to detect when a layout is being rendered for the first time, which is crucial for the fix.

Also applies to: 90-91


103-105: Well-designed function for detecting new layout rendering

The isRenderingNewLayout function provides a clean way to determine if a layout is being rendered for the first time. This is key to ensuring fresh routes on first render.


130-133: Props properly typed and required

The isRenderingNewLayout prop is correctly marked as required and has an appropriate type definition. Good practice to ensure the component receives all necessary props.


2-2: Added necessary import for the route proxy implementation

The addition of shallowReactive to the imports is needed for the reactive route proxy. Good practice to keep imports organized.

Copy link

pkg-pr-new bot commented May 17, 2025

Open in StackBlitz

@nuxt/kit

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

nuxt

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

@nuxt/schema

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

@nuxt/rspack-builder

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

@nuxt/vite-builder

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

@nuxt/webpack-builder

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

commit: 8037b7e

Copy link

codspeed-hq bot commented May 17, 2025

CodSpeed Performance Report

Merging #24673 will not alter performance

Comparing fix/layout-route (8037b7e) with main (847d936)

Summary

βœ… 10 untouched benchmarks

@danielroe danielroe merged commit cfda706 into main May 17, 2025
46 checks passed
@danielroe danielroe deleted the fix/layout-route branch May 17, 2025 20:04
@github-actions github-actions bot mentioned this pull request May 17, 2025
@github-actions github-actions bot mentioned this pull request May 20, 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.

useRoute not correctly populated with async layout
3 participants
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy