nuxt4-patterns

Nuxt 4 应用模式,涵盖水合安全、性能优化、路由规则、懒加载,以及使用 useFetch 和 useAsyncData 进行 SSR 安全的数据获取。

144,923 stars
Complexity: easy

About this skill

This skill equips an AI agent with comprehensive knowledge of Nuxt 4 application patterns, essential for building robust and performant web applications. It covers critical aspects such as ensuring hydration safety between server-rendered HTML and client-side state, optimizing performance through lazy loading and managing payload sizes, defining effective routing rules (including pre-rendering, SWR, ISR, and client-only sections), and performing secure, SSR-compatible data fetching using Nuxt's `useFetch` and `useAsyncData` composables. The skill also advises on common pitfalls related to `Date.now()`, `Math.random()`, browser-only APIs in SSR contexts, and proper usage of Nuxt's `useRoute()`.

Best use case

For AI agents assisting developers in building, debugging, or optimizing Nuxt 4 applications, especially those requiring Server-Side Rendering (SSR), hybrid rendering, advanced routing logic, or efficient data management.

Nuxt 4 应用模式,涵盖水合安全、性能优化、路由规则、懒加载,以及使用 useFetch 和 useAsyncData 进行 SSR 安全的数据获取。

The AI agent will generate Nuxt 4 code and provide advice that adheres to best practices for SSR, hydration safety, performance, and data fetching. It will help resolve common Nuxt 4 development and debugging challenges, leading to more stable, performant, and maintainable applications.

Practical example

Example input

Develop a Nuxt 4 page that fetches data on the server-side, ensures hydration safety, and uses lazy loading for non-critical components.
Debug a Nuxt 4 application exhibiting hydration mismatches and suggest solutions for `route.fullPath` usage in SSR contexts.
Propose performance optimization strategies for a Nuxt 4 application, focusing on reducing initial load time and improving perceived performance.
Generate code for a Nuxt 4 component that fetches user data using `useAsyncData` and handles loading and error states gracefully.

Example output

To create a Nuxt 4 page with SSR-safe data fetching, consider the following pattern:

```vue
<script setup lang="ts">
import { useFetch, useAsyncData, onMounted, defineAsyncComponent } from '#app'

const { data: product, pending, error } = await useFetch('/api/products/123')

// Lazy load a component
const MyLazyComponent = defineAsyncComponent(() => import('./MyLazyComponent.vue'))

// Hydration safety: client-only logic
let clientRandom = ref(0)
onMounted(() => {
  clientRandom.value = Math.random()
})
</script>

<template>
  <div>
    <h1>Product Details</h1>
    <p v-if="pending">Loading...</p>
    <p v-else-if="error">Error: {{ error.message }}</p>
    <div v-else>
      <p>Product Name: {{ product?.name }}</p>
      <p>Client Random: {{ clientRandom }}</p>
      <MyLazyComponent />
    </div>
  </div>
</template>
```

Ensure that any non-deterministic values like `Math.random()` are confined to `onMounted()` hooks or `ClientOnly` components to prevent hydration mismatches.
Regarding hydration mismatches, especially with `route.fullPath`: Avoid using `route.fullPath` directly to drive SSR-rendered markup, as URL fragments are client-only and can lead to discrepancies. Instead:

1.  **Use `useRoute()`**: Always use Nuxt's `useRoute()` composable instead of `vue-router`'s direct import for SSR safety.
2.  **Isolate Client-Only Logic**: Move browser-specific APIs, `Date.now()`, `Math.random()`, or any code dependent on browser-specific state into `onMounted()` hooks, `<ClientOnly>` components, or `.client.vue` files.
3.  **Deterministic Rendering**: Keep your initial server render deterministic. The server HTML should be exactly what the client expects to hydrate without changes. Using `ssr: false` should be a last resort, not a default fix for mismatches.
For Nuxt 4 performance optimizations, focus on these areas:

1.  **Lazy Loading**: Use `defineAsyncComponent` for components not immediately needed, or dynamic `import()` for specific modules, especially for parts 'below the fold' or in modals.
2.  **Delayed Hydration**: For less interactive components, explore strategies to delay their hydration, reducing initial JavaScript execution.
3.  **Payload Size**: Minimize your bundle size by code splitting, tree-shaking, and optimizing assets. Utilize Nuxt's build analyzer to identify large dependencies.
4.  **Optimized Data Fetching**: Leverage `useFetch` for efficient server-side data fetching, ensuring data is available for the initial render without Waterfall issues. Consider `useAsyncData` for more granular control and caching strategies. Ensure your API responses are optimized for size.

When to use this skill

  • When encountering hydration mismatches between server HTML and client state.
  • When making routing-level rendering decisions, such as pre-rendering, SWR, ISR, or defining client-only parts.
  • When performing performance optimization work related to lazy loading, delayed hydration, or reducing payload size.
  • When using `useFetch`, `useAsyncData`, or `$fetch` for page or component-level data fetching.

When not to use this skill

  • When working with non-Nuxt frameworks or older Nuxt versions (Nuxt 3 or earlier).
  • For simple static Nuxt applications that do not involve SSR, complex routing, or advanced data fetching patterns.
  • When the task does not involve code generation, debugging, or architectural advice related to Nuxt 4 best practices.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/nuxt4-patterns/SKILL.md --create-dirs "https://raw.githubusercontent.com/affaan-m/everything-claude-code/main/docs/zh-CN/skills/nuxt4-patterns/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/nuxt4-patterns/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How nuxt4-patterns Compares

Feature / Agentnuxt4-patternsStandard Approach
Platform SupportClaudeLimited / Varies
Context Awareness High Baseline
Installation ComplexityeasyN/A

Frequently Asked Questions

What does this skill do?

Nuxt 4 应用模式,涵盖水合安全、性能优化、路由规则、懒加载,以及使用 useFetch 和 useAsyncData 进行 SSR 安全的数据获取。

Which AI agents support this skill?

This skill is designed for Claude.

How difficult is it to install?

The installation complexity is rated as easy. You can find the installation instructions above.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

Related Guides

SKILL.md Source

# Nuxt 4 模式

在构建或调试具有 SSR、混合渲染、路由规则或页面级数据获取的 Nuxt 4 应用时使用。

## 何时激活

* 服务器 HTML 与客户端状态之间的水合不匹配
* 路由级别的渲染决策,例如预渲染、SWR、ISR 或仅客户端部分
* 围绕懒加载、延迟水合或有效负载大小的性能工作
* 使用 `useFetch`、`useAsyncData` 或 `$fetch` 进行页面或组件数据获取
* 与路由参数、中间件或 SSR/客户端差异相关的 Nuxt 路由问题

## 水合安全性

* 保持首次渲染是确定性的。不要将 `Date.now()`、`Math.random()`、仅限浏览器的 API 或存储读取直接放入 SSR 渲染的模板状态中。
* 当服务器无法生成相同标记时,将仅限浏览器的逻辑移到 `onMounted()`、`import.meta.client`、`ClientOnly` 或 `.client.vue` 组件后面。
* 使用 Nuxt 的 `useRoute()` 组合式函数,而不是来自 `vue-router` 的那个。
* 不要使用 `route.fullPath` 来驱动 SSR 渲染的标记。URL 片段是仅客户端的,这可能导致水合不匹配。
* 将 `ssr: false` 视为真正仅限浏览器区域的逃生舱口,而不是解决不匹配的默认修复方法。

## 数据获取

* 在页面和组件中,优先使用 `await useFetch()` 进行 SSR 安全的 API 读取。它将服务器获取的数据转发到 Nuxt 有效负载中,并避免在水合时进行第二次获取。
* 当数据获取器不是简单的 `$fetch()` 调用,或者需要自定义键,或者正在组合多个异步源时,使用 `useAsyncData()`。
* 为 `useAsyncData()` 提供一个稳定的键以重用缓存并实现可预测的刷新行为。
* 保持 `useAsyncData()` 处理程序无副作用。它们可能在 SSR 和水合期间运行。
* 将 `$fetch()` 用于用户触发的写入或仅客户端操作,而不是应该从 SSR 水合而来的顶级页面数据。
* 对于不应阻塞导航的非关键数据,使用 `lazy: true`、`useLazyFetch()` 或 `useLazyAsyncData()`。在 UI 中处理 `status === 'pending'`。
* 仅对 SEO 或首次绘制不需要的数据使用 `server: false`。
* 使用 `pick` 修剪有效负载大小,并在不需要深层响应性时优先使用较浅的有效负载。

```ts
const route = useRoute()

const { data: article, status, error, refresh } = await useAsyncData(
  () => `article:${route.params.slug}`,
  () => $fetch(`/api/articles/${route.params.slug}`),
)

const { data: comments } = await useFetch(`/api/articles/${route.params.slug}/comments`, {
  lazy: true,
  server: false,
})
```

## 路由规则

在 `nuxt.config.ts` 中优先使用 `routeRules` 来定义渲染和缓存策略:

```ts
export default defineNuxtConfig({
  routeRules: {
    '/': { prerender: true },
    '/products/**': { swr: 3600 },
    '/blog/**': { isr: true },
    '/admin/**': { ssr: false },
    '/api/**': { cache: { maxAge: 60 * 60 } },
  },
})
```

* `prerender`:在构建时生成静态 HTML
* `swr`:提供缓存内容并在后台重新验证
* `isr`:在支持的平台上进行增量静态再生
* `ssr: false`:客户端渲染的路由
* `cache` 或 `redirect`:Nitro 级别的响应行为

按路由组选择路由规则,而非全局设置。营销页面、产品目录、仪表板和 API 通常需要不同的策略。

## 懒加载与性能

* Nuxt 已经按路由进行代码分割。在微优化组件分割之前,保持路由边界的意义。
* 使用 `Lazy` 前缀来动态导入非关键组件。
* 使用 `v-if` 有条件地渲染懒加载组件,以便在 UI 实际需要时才加载该代码块。
* 对首屏下方或非关键的交互式 UI 使用延迟水合。

```vue
<template>
  <LazyRecommendations v-if="showRecommendations" />
  <LazyProductGallery hydrate-on-visible />
</template>
```

* 对于自定义策略,使用 `defineLazyHydrationComponent()` 配合可见性或空闲策略。
* Nuxt 延迟水合适用于单文件组件。向延迟水合的组件传递新 props 将立即触发水合。
* 在内部导航中使用 `NuxtLink`,以便 Nuxt 可以预取路由组件和生成的有效负载。

## 检查清单

* 首次 SSR 渲染和水合后的客户端渲染产生相同的标记
* 页面数据使用 `useFetch` 或 `useAsyncData`,而非顶层的 `$fetch`
* 非关键数据是懒加载的,并具有明确的加载 UI
* 路由规则符合页面的 SEO 和新鲜度要求
* 重量级交互式组件是懒加载或延迟水合的

Related Skills

hono

31392
from sickn33/antigravity-awesome-skills

Build ultra-fast web APIs and full-stack apps with Hono — runs on Cloudflare Workers, Deno, Bun, Node.js, and any WinterCG-compatible runtime.

Web DevelopmentClaudeCursorGemini

frontend-design

31392
from sickn33/antigravity-awesome-skills

You are a frontend designer-engineer, not a layout generator.

Web DevelopmentClaude

favicon

31392
from sickn33/antigravity-awesome-skills

Generate favicons from a source image

Web DevelopmentClaude

django-pro

31392
from sickn33/antigravity-awesome-skills

Master Django 5.x with async views, DRF, Celery, and Django Channels. Build scalable web applications with proper architecture, testing, and deployment.

Web DevelopmentClaude

healthcare-emr-patterns

144923
from affaan-m/everything-claude-code

EMR/EHR development patterns for healthcare applications. Clinical safety, encounter workflows, prescription generation, clinical decision support integration, and accessibility-first UI for medical data entry.

HealthcareClaude

healthcare-cdss-patterns

144923
from affaan-m/everything-claude-code

Clinical Decision Support System (CDSS) development patterns. Drug interaction checking, dose validation, clinical scoring (NEWS2, qSOFA), alert severity classification, and integration into EMR workflows.

HealthcareClaude

swiftui-patterns

144923
from affaan-m/everything-claude-code

SwiftUI 架构模式,使用 @Observable 进行状态管理,视图组合,导航,性能优化,以及现代 iOS/macOS UI 最佳实践。

DevelopmentClaude

pytorch-patterns

144923
from affaan-m/everything-claude-code

PyTorch深度学习模式与最佳实践,用于构建稳健、高效且可复现的训练流程、模型架构和数据加载。

Development ToolsClaude

perl-patterns

144923
from affaan-m/everything-claude-code

现代 Perl 5.36+ 的惯用法、最佳实践和约定,用于构建稳健、可维护的 Perl 应用程序。

DevelopmentClaude

kotlin-ktor-patterns

144923
from affaan-m/everything-claude-code

Ktor 服务器模式,包括路由 DSL、插件、身份验证、Koin DI、kotlinx.serialization、WebSockets 和 testApplication 测试。

DevelopmentClaude

kotlin-exposed-patterns

144923
from affaan-m/everything-claude-code

JetBrains Exposed ORM 模式,包括 DSL 查询、DAO 模式、事务、HikariCP 连接池、Flyway 迁移和仓库模式。

DevelopmentClaude

rust-patterns

144923
from affaan-m/everything-claude-code

Idiomatic Rust patterns, ownership, error handling, traits, concurrency, and best practices for building safe, performant applications.

DevelopmentClaude