Skip to content

feat(skills): add Nuxt 4 patterns skill#643

Closed
yongggquannn wants to merge 15 commits intoaffaan-m:mainfrom
yongggquannn:feat/nuxt-development-patterns
Closed

feat(skills): add Nuxt 4 patterns skill#643
yongggquannn wants to merge 15 commits intoaffaan-m:mainfrom
yongggquannn:feat/nuxt-development-patterns

Conversation

@yongggquannn
Copy link

@yongggquannn yongggquannn commented Mar 19, 2026

What Changed

Added a new nuxt-4-frontend-patterns skill covering production-grade Nuxt 4 / Vue 3 patterns including hydration safety, performance optimization, route rules, lazy loading, plugin best practices, data fetching (useFetch, useAsyncData, useState), and VueUse integration for SSR-safe applications.

Why This Change

Expands the ECC skill catalog with Nuxt 4 frontend patterns, giving users actionable guidance for building performant, SSR-safe Nuxt applications. This fills a gap in the existing skill set which had no Vue/Nuxt specific coverage.

Testing Done

  • Manual testing completed
  • Automated tests pass locally (node tests/run-all.js)
  • Edge cases considered and tested

Type of Change

  • fix: Bug fix
  • feat: New feature
  • refactor: Code refactoring
  • docs: Documentation
  • test: Tests
  • chore: Maintenance/tooling
  • ci: CI/CD changes

Security & Quality Checklist

  • No secrets or API keys committed (ghp_, sk-, AKIA, xoxb, xoxp patterns checked)
  • JSON files validate cleanly
  • Shell scripts pass shellcheck (if applicable)
  • Pre-commit hooks pass locally (if configured)
  • No sensitive data exposed in logs or output
  • Follows conventional commits format

Documentation

  • Updated relevant documentation
  • Added comments for complex logic
  • README updated (if needed)

Summary by cubic

Adds the new nuxt-4-frontend-patterns skill with production-ready patterns for SSR-safe hydration, performance, data fetching, and VueUse in Nuxt 4/Vue 3. Also refines frontmatter and examples so the skill renders cleanly and is easy to scan.

  • New Features

    • Hydration/SSR safety: useState/useCookie, browser-only guards, ClientOnly.
    • Performance: route rules (prerender, swr, isr, ssr: false), lazy loading/hydration, NuxtLink prefetch, NuxtImg.
    • Data & plugins: useFetch/useAsyncData with headers; prefer composables; parallel plugin loading; @vueuse/nuxt with SSR-safe storage and CSS-first breakpoints.
  • Bug Fixes

    • Fixed YAML frontmatter so the skill parses in the catalog.
    • Repaired examples: added missing <script setup>, declared refs, resolved keyboard shortcut runtime errors.
    • Corrected useAsyncData callback and fixed an improper useFetch-in-callback pattern.
    • Completed the manual-trigger useScript example and hardened it against ad blockers; strengthened debounced search.
    • Tightened TypeScript types (e.g., item generics) and removed patterns that could cause duplicate variable names.

Written for commit 046bc0e. Summary will update on new commits.

Summary by CodeRabbit

  • Documentation
    • Added a comprehensive production-focused Nuxt 4 / Vue 3 frontend playbook: activation guidance, SSR-safe hydration rules, hydration-safety examples, performance patterns (route rendering strategies, prefetching, lazy components and lazy hydration, image optimization, script loading), SSR-compatible data fetching guidance, plugin vs composable best practices, Vue/VueUse rendering primitives, SSR-safety reference tables, and a common pitfalls & fixes guide.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 19, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds a new documentation skill file skills/nuxt-4-frontend-patterns/SKILL.md that consolidates production-oriented Nuxt 4 / Vue 3 guidance: activation/context, recommended project structure, SSR-safe hydration, performance and lazy-hydration strategies, data fetching, plugin practices, VueUse integration, SSR-safe composables, and a common pitfalls reference.

Changes

Cohort / File(s) Summary
Nuxt 4 Frontend Patterns Documentation
skills/nuxt-4-frontend-patterns/SKILL.md
New comprehensive documentation covering activation criteria and project structure, SSR-safe hydration rules and examples, route-level performance (routeRules) and lazy-hydration strategies, component lazy loading and NuxtLink prefetching, image/script optimization, data-fetch patterns (useFetch, useAsyncData, header forwarding), plugin best practices (including parallel plugin loading), VueUse integration with SSR notes, SSR-safe composable reference tables, and a common pitfalls/fixes table.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐇 I nibble notes of Nuxt by moonlight,

Hydration safe, and lazy loads take flight.
Routes that rest, images that gleam,
Plugins parallel, a developer's dream.
Hooray — frontend patterns, swift and bright!

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat(skills): add nuxt-4 patterns' clearly summarizes the main change: adding a new Nuxt 4 frontend patterns skill documentation to the repository.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
📝 Coding Plan
  • Generate coding plan for human review comments

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.

@greptile-apps
Copy link
Contributor

greptile-apps bot commented Mar 19, 2026

Greptile Summary

This PR adds skills/nuxt-4-frontend-patterns/SKILL.md, a production-focused guidance document for Nuxt 4 / Vue 3 covering hydration safety, hybrid rendering, lazy loading, data fetching, plugin best practices, and VueUse integration. Several prior review rounds have resolved critical issues (frontmatter, composable-in-callback errors, missing ref declarations, TypeScript errors, and race conditions in the debounced search example).

Key remaining observations:

  • Hydration mismatch in useDark() exampleuseDark() reads localStorage/matchMedia on the client but defaults on the server, risking the exact hydration mismatch the document warns against. A cookie-based approach or @nuxtjs/color-mode would be SSR-safe.
  • Import inconsistency in useBreakpoints example — the document claims all VueUse composables are auto-imported, but the example explicitly imports useBreakpoints alongside breakpointsTailwind. Only the constant preset needs an explicit import.
  • CSS-only responsive pattern mounts both components — presenting both <MobileNav> and <DesktopNav> as always mounted without noting the performance trade-off could mislead developers applying this pattern to heavier components.

Confidence Score: 3/5

  • The skill document is largely sound after multiple fix iterations, but a few patterns contradict the document's own SSR/hydration safety guidance and should be corrected before shipping as canonical guidance.
  • The PR has gone through 5+ fix commits addressing critical issues (runtime errors, TypeScript compile errors, race conditions, frontmatter). What remains are documentation-quality and correctness issues: useDark() without SSR guard, an import inconsistency, and an undocumented performance caveat. None are blocking regressions (it's a docs-only skill file), but since the document's primary value is teaching correct SSR-safe patterns, including a pattern that can itself cause hydration mismatches undermines its credibility.
  • skills/nuxt-4-frontend-patterns/SKILL.md — specifically the Dark Mode section (line 379), Responsive Breakpoints section (lines 450–470)

Important Files Changed

Filename Overview
skills/nuxt-4-frontend-patterns/SKILL.md New skill document covering Nuxt 4/Vue 3 SSR-safe patterns; multiple rounds of fixes have addressed frontmatter, runtime errors, type errors, and race conditions from earlier reviews, but a few issues remain: useDark() can still produce hydration mismatches, an explicit import contradicts the stated auto-import guarantee, and the CSS-only component switching pattern silently mounts both components without documenting the trade-off.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[Nuxt 4 Request] --> B{Route Rule?}
    B -->|prerender: true| C[Static HTML served from CDN]
    B -->|swr: N seconds| D[Stale-While-Revalidate Cache]
    B -->|isr: N seconds| E[Incremental Static Regeneration]
    B -->|ssr: false| F[SPA / Client-Only Bundle]
    B -->|default SSR| G[Server-Side Render]

    G --> H{Data Fetching}
    H -->|useFetch / useAsyncData| I[Server fetches + serialises payload]
    I --> J[Client hydrates from payload — no double fetch]

    J --> K{Hydration Safety Check}
    K -->|useState / useCookie| L[Server + Client state in sync ✓]
    K -->|window / localStorage direct| M[Hydration Mismatch ✗]
    K -->|useDark without cookie| N[Potential Mismatch ⚠]

    L --> O[Interactive Page]
    J --> P{Performance}
    P -->|Lazy prefix| Q[Component JS deferred until rendered]
    P -->|hydrate-on-visible/idle| R[Hydration deferred — reduces JS work]
    P -->|NuxtImg + webp| S[Optimised images with priority hints]
    P -->|useScript manual trigger| T[Third-party scripts load after consent]
Loading

Last reviewed commit: "fix: update type par..."

@yongggquannn yongggquannn changed the title feat: add nuxt-4 patterns feat(skills): add nuxt-4 patterns Mar 19, 2026
Copy link
Contributor

@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 (2)
skills/nuxt-4-frontend-patterns/SKILL.md (2)

87-94: Clarify that this example would crash SSR, not just mismatch.

The "Not good" example on line 89 (v-if="window?.innerWidth > 768") would throw a ReferenceError during server-side rendering since window is undefined. The optional chaining operator doesn't prevent this error in Vue template expressions. Consider updating the comment to reflect that this crashes SSR rather than just causing a hydration mismatch.

📝 Suggested clarification
 <template>
-  <!-- Not good: causes hydration mismatch -->
+  <!-- Not good: crashes on server (ReferenceError) -->
   <div v-if="window?.innerWidth > 768">Desktop</div>
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@skills/nuxt-4-frontend-patterns/SKILL.md` around lines 87 - 94, The comment
on the "Not good" example is incorrect: using v-if="window?.innerWidth > 768" in
a Vue template will throw a ReferenceError during SSR because window is
undefined (the optional chaining doesn't avoid the server-side evaluation).
Update the comment to state this crashes SSR (not just a hydration mismatch) and
suggest using CSS responsiveness (as shown) or a client-only guard such as
checking window inside mounted/useMounted or a reactive isClient/isMounted flag
(replace the v-if window expression with a client-side check or move it into
mounted/composables).

1-515: Add a "How It Works" section to align with skill formatting guidelines.

While the document provides excellent patterns and examples, it's missing an explicit "How It Works" section that explains the underlying concepts. Consider adding a section after "When to Activate" that covers:

  • The SSR/hydration lifecycle (server render → hydration → client interactivity)
  • When code runs on server vs. client
  • Why hydration mismatches occur and their impact
  • The role of route rules in the rendering pipeline

This would help developers new to Nuxt/SSR understand why these patterns are necessary before seeing what patterns to use.

As per coding guidelines, skills should be formatted with clear sections for "When to Use", "How It Works", and "Examples". The file currently has "When to Activate" (✓) and extensive examples (✓), but lacks the conceptual "How It Works" section.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@skills/nuxt-4-frontend-patterns/SKILL.md` around lines 1 - 515, Add a new
"How It Works" section immediately after the existing "When to Activate" header
that briefly explains the SSR/hydration lifecycle (server render → hydration →
client interactivity), clarifies when code runs on server vs client (mention
import.meta.client, onMounted, browser-only APIs), summarizes why hydration
mismatches occur and their impact, and describes how route rules (referencing
routeRules keys like prerender, swr, isr, ssr: false) affect the rendering
pipeline; keep it concise, aligned with the "When to Use"/"Examples" structure,
and reference composables used elsewhere (useState, useFetch, useAsyncData,
useCookie) for context.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@skills/nuxt-4-frontend-patterns/SKILL.md`:
- Around line 258-266: The documentation example using useScriptGoogleAnalytics
lacks a note that the Nuxt Scripts module must be installed; update SKILL.md
near the VueUse section to add a short setup step instructing users to install
and enable the official Nuxt Scripts module (e.g., npm install `@nuxt/scripts` and
add to modules in nuxt.config) before using useScriptGoogleAnalytics, and
mention that the composable depends on `@nuxt/scripts` so the manual trigger
(scriptOptions: { trigger: 'manual' }) will work.

---

Nitpick comments:
In `@skills/nuxt-4-frontend-patterns/SKILL.md`:
- Around line 87-94: The comment on the "Not good" example is incorrect: using
v-if="window?.innerWidth > 768" in a Vue template will throw a ReferenceError
during SSR because window is undefined (the optional chaining doesn't avoid the
server-side evaluation). Update the comment to state this crashes SSR (not just
a hydration mismatch) and suggest using CSS responsiveness (as shown) or a
client-only guard such as checking window inside mounted/useMounted or a
reactive isClient/isMounted flag (replace the v-if window expression with a
client-side check or move it into mounted/composables).
- Around line 1-515: Add a new "How It Works" section immediately after the
existing "When to Activate" header that briefly explains the SSR/hydration
lifecycle (server render → hydration → client interactivity), clarifies when
code runs on server vs client (mention import.meta.client, onMounted,
browser-only APIs), summarizes why hydration mismatches occur and their impact,
and describes how route rules (referencing routeRules keys like prerender, swr,
isr, ssr: false) affect the rendering pipeline; keep it concise, aligned with
the "When to Use"/"Examples" structure, and reference composables used elsewhere
(useState, useFetch, useAsyncData, useCookie) for context.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 1d5bf154-7f60-42a4-b93f-ae2aff9418b3

📥 Commits

Reviewing files that changed from the base of the PR and between 4bdbf57 and 6aa55b1.

📒 Files selected for processing (1)
  • skills/nuxt-4-frontend-patterns/SKILL.md

Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

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

2 issues found across 1 file

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="skills/nuxt-4-frontend-patterns/SKILL.md">

<violation number="1" location="skills/nuxt-4-frontend-patterns/SKILL.md:1">
P1: Malformed frontmatter (`## name` and missing closing `---`) can break skill metadata parsing/registration.</violation>

<violation number="2" location="skills/nuxt-4-frontend-patterns/SKILL.md:440">
P2: Debounced event-driven search example uses `useFetch` inside a runtime callback; this should use `$fetch` for client-triggered requests.</violation>
</file>

Since this is your first cubic review, here's how it works:

  • cubic automatically reviews your code and comments on bugs and improvements
  • Teach cubic by replying to its comments. cubic learns from your replies and gets better over time
  • Add one-off context when rerunning by tagging @cubic-dev-ai with guidance or docs links (including llms.txt)
  • Ask questions if you need clarification on any suggestion

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

Remove markdown heading prefix (##) from name field and add missing
closing --- delimiter so the skill catalog parses the description correctly.
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

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

1 issue found across 1 file (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="skills/nuxt-4-frontend-patterns/SKILL.md">

<violation number="1" location="skills/nuxt-4-frontend-patterns/SKILL.md:439">
P2: Debounced search example is race-prone: older async responses can overwrite newer query results.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

Copy link
Contributor

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

♻️ Duplicate comments (1)
skills/nuxt-4-frontend-patterns/SKILL.md (1)

258-266: ⚠️ Potential issue | 🟡 Minor

Setup instructions for @nuxt/scripts are still missing.

The example uses useScriptGoogleAnalytics but the document doesn't include installation/setup instructions for the @nuxt/scripts module. Add a setup section (similar to VueUse at lines 372-386) showing:

npm install `@nuxt/scripts`
// nuxt.config.ts
export default defineNuxtConfig({
  modules: ['@nuxt/scripts'],
})
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@skills/nuxt-4-frontend-patterns/SKILL.md` around lines 258 - 266, Add a short
"Setup" subsection showing how to install and register the `@nuxt/scripts` module
so the useScriptGoogleAnalytics example works: instruct to run npm install
`@nuxt/scripts` and show adding modules: ['@nuxt/scripts'] to nuxt.config.ts
(referencing the example that uses useScriptGoogleAnalytics and the manual
scriptOptions trigger). Place this setup block near the VueUse setup section so
readers can follow installation before the useScriptGoogleAnalytics snippet.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@skills/nuxt-4-frontend-patterns/SKILL.md`:
- Around line 258-266: Add a short "Setup" subsection showing how to install and
register the `@nuxt/scripts` module so the useScriptGoogleAnalytics example works:
instruct to run npm install `@nuxt/scripts` and show adding modules:
['@nuxt/scripts'] to nuxt.config.ts (referencing the example that uses
useScriptGoogleAnalytics and the manual scriptOptions trigger). Place this setup
block near the VueUse setup section so readers can follow installation before
the useScriptGoogleAnalytics snippet.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 1ae19968-33f3-44d7-8e25-20c760c1c6e1

📥 Commits

Reviewing files that changed from the base of the PR and between 555f379 and bec3230.

📒 Files selected for processing (1)
  • skills/nuxt-4-frontend-patterns/SKILL.md

Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

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

1 issue found across 1 file (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="skills/nuxt-4-frontend-patterns/SKILL.md">

<violation number="1" location="skills/nuxt-4-frontend-patterns/SKILL.md:260">
P2: The new Google Analytics example depends on `@nuxt/scripts` (`useScriptGoogleAnalytics`) but the guide omits required setup, so the snippet can fail in a baseline Nuxt app.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

yongggquannn and others added 2 commits March 19, 2026 18:53
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

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

2 issues found across 1 file (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="skills/nuxt-4-frontend-patterns/SKILL.md">

<violation number="1" location="skills/nuxt-4-frontend-patterns/SKILL.md:392">
P2: The guide labels `useLocalStorage`/theme composables as “SSR-safe” without clarifying first-render hydration risks, which can mislead readers into rendering client-derived values directly and reintroducing hydration mismatch.</violation>

<violation number="2" location="skills/nuxt-4-frontend-patterns/SKILL.md:448">
P2: Debounced search example can show stale results due to out-of-order async responses (no cancellation or sequencing).</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

@@ -0,0 +1,536 @@
---
Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot Mar 19, 2026

Choose a reason for hiding this comment

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

P2: The guide labels useLocalStorage/theme composables as “SSR-safe” without clarifying first-render hydration risks, which can mislead readers into rendering client-derived values directly and reintroducing hydration mismatch.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At skills/nuxt-4-frontend-patterns/SKILL.md, line 392:

<comment>The guide labels `useLocalStorage`/theme composables as “SSR-safe” without clarifying first-render hydration risks, which can mislead readers into rendering client-derived values directly and reintroducing hydration mismatch.</comment>

<file context>
@@ -392,7 +389,7 @@ All VueUse composables are auto-imported — no manual imports needed.
 <script setup lang="ts">
 // Not good: raw localStorage causes hydration mismatch
-const theme = ref(localStorage.getItem('theme') || 'light')
+// const theme = ref(localStorage.getItem('theme') || 'light')
 
 // Good: useLocalStorage is SSR-safe via @vueuse/nuxt
</file context>
Fix with Cubic

Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

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

2 issues found across 1 file (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="skills/nuxt-4-frontend-patterns/SKILL.md">

<violation number="1" location="skills/nuxt-4-frontend-patterns/SKILL.md:247">
P2: Nuxt Scripts composables are documented without the required `@nuxt/scripts` setup, so readers may hit missing composable/auto-import errors.</violation>

<violation number="2" location="skills/nuxt-4-frontend-patterns/SKILL.md:438">
P2: Debounced-search example leaves `error` sticky, so a past failure can permanently mask later successful results.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

### Third-Party Script Management

```vue
<script setup lang="ts">
Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot Mar 19, 2026

Choose a reason for hiding this comment

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

P2: Nuxt Scripts composables are documented without the required @nuxt/scripts setup, so readers may hit missing composable/auto-import errors.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At skills/nuxt-4-frontend-patterns/SKILL.md, line 247:

<comment>Nuxt Scripts composables are documented without the required `@nuxt/scripts` setup, so readers may hit missing composable/auto-import errors.</comment>

<file context>
@@ -243,7 +243,8 @@ Control when components become interactive — reduces JavaScript work on initia
 
-```typescript
+```vue
+<script setup lang="ts">
 // Good: controlled loading with useScript
 const { load, proxy } = useScriptGoogleAnalytics({
</file context>
Fix with Cubic

@yongggquannn yongggquannn force-pushed the feat/nuxt-development-patterns branch from d6a01ae to 046bc0e Compare March 19, 2026 13:58
@yongggquannn yongggquannn changed the title feat(skills): add nuxt-4 patterns feat(skills): add Nuxt 4 patterns Mar 19, 2026
Comment on lines +379 to +390
```vue
<script setup lang="ts">
const isDark = useDark()
const toggleDark = useToggle(isDark)
</script>

<template>
<button @click="toggleDark()">
{{ isDark ? 'Light Mode' : 'Dark Mode' }}
</button>
</template>
```
Copy link
Contributor

Choose a reason for hiding this comment

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

P1 useDark() potential hydration mismatch not documented

useDark() reads from localStorage and/or window.matchMedia('(prefers-color-scheme: dark)') on the client. On the server, neither is available, so isDark always resolves to the initial default (typically false). If the user's system or stored preference is dark, the server renders "Dark Mode" (button label) but the client hydrates with "Light Mode" — a hydration mismatch — which is exactly the class of bugs this document warns against in its Hydration Safety section.

A more robust pattern for SSR-safe dark mode is to persist preference in a cookie (readable on both server and client) and initialise useDark from it:

<script setup lang="ts">
// Read server-accessible cookie so SSR and client agree on initial value
const colorModeCookie = useCookie<'dark' | 'light'>('color-mode', { default: () => 'light' })
const isDark = computed({
  get: () => colorModeCookie.value === 'dark',
  set: (val) => { colorModeCookie.value = val ? 'dark' : 'light' },
})
const toggleDark = useToggle(isDark)
</script>

At minimum, add a callout that useDark() can cause a hydration flash and pair it with <ClientOnly>, or recommend @nuxtjs/color-mode which handles this correctly.

Comment on lines +450 to +455
```vue
<template>
<!-- Good: CSS handles layout — no hydration mismatch -->
<MobileNav class="md:hidden" />
<DesktopNav class="hidden md:block" />
</template>
Copy link
Contributor

Choose a reason for hiding this comment

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

P2 CSS-only approach mounts both components simultaneously

The CSS-first pattern shown here renders both <MobileNav> and <DesktopNav> in the DOM at all times — only visibility is toggled with Tailwind classes. This means both components are instantiated, have their lifecycle hooks executed, fire their own data-fetching calls (useFetch/useAsyncData), and consume memory. For lightweight nav components this is fine, but as written this is presented as a universal good practice without caveating the trade-off.

Consider adding a note so developers know when this pattern is appropriate vs. when the useBreakpoints/ssrWidth approach (which does conditionally mount) is preferable:

<!-- Good: CSS handles layout — no hydration mismatch -->
<!-- Note: both components are mounted; prefer this only for lightweight components -->
<MobileNav class="md:hidden" />
<DesktopNav class="hidden md:block" />

@affaan-m
Copy link
Owner

Thanks for the detailed Nuxt 4 patterns skill! The content quality is high -- hydration safety, route rules, VueUse integration, and performance patterns are all well-covered.

This PR now likely has merge conflicts from recent merges that updated component counts in AGENTS.md and README.md. Could you rebase on the latest main and resolve any conflicts? Once clean, this is ready to merge.

@affaan-m
Copy link
Owner

Superseded by rebased PR

@affaan-m affaan-m closed this Mar 20, 2026
@yongggquannn yongggquannn deleted the feat/nuxt-development-patterns branch March 20, 2026 16:55
@yongggquannn yongggquannn changed the title feat(skills): add Nuxt 4 patterns feat(skills): add Nuxt 4 patterns skill Mar 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants