nuxt-production について
nuxt-productionは、Nuxt 4プロジェクト向けの本番運用ガイドです。ハイドレーション、パフォーマンス、テスト、デプロイ、Nuxt 3からの移行を扱い、実装パターンとトラブルシューティングを示します。
主な機能
- 01ハイドレーション問題の対処パターン
- 02遅延読み込みとキャッシュの最適化
- 03VitestとNuxtのテスト例
- 04デプロイと環境設定のガイド
- 05Nuxt 3からの移行手順
活用シーン
- 01サーバーとクライアント間のハイドレーション不一致の診断
- 02コンポーネント読み込みとルートキャッシュの最適化
- 03コンポーネントやサーバールートのテスト作成
- 04Nuxt 3プロジェクトのNuxt 4への移行
インストール
コマンドをコピーしてターミナルで実行します。
$
npx skills add https:/ / github.com/ secondsky/ claude-skills --skill nuxt-productionインストール後、Claude Code で/nuxt-productionを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
references/deployment-cloudflare.mdhydration.mdperformance.mdtesting-vitest.mdtemplates/wrangler.tomltemplates/tests/components/BlogPost.test.ts詳細
Nuxt 4 本番環境ガイド
ハイドレーション、パフォーマンス、テスト、デプロイ、移行のパターンです。
Nuxt 4 の新機能
v4.2 の機能(最新)
1. データ取得の中止制御
const controller = ref<AbortController>()
const { data } = await useAsyncData(
'users',
() => $fetch('/api/users', { signal: controller.value?.signal })
)
const abortRequest = () => {
controller.value?.abort()
controller.value = new AbortController()
}
2. 非同期データハンドラーの抽出
- クライアントバンドルが39%小さくなります
- データ取得ロジックがサーバーチャンクに抽出されます
- 自動的に最適化されます(設定は不要です)
3. エラーハンドリングの強化
- エラーを2種類の方法で表示:カスタムエラーページと技術的なオーバーレイ
- 開発時のエラーメッセージを改善
v4.1 の機能
1. チャンクの安定性を強化
- インポートマップにより、ハッシュ変更の連鎖を防止します
- 長期キャッシュが改善されます
2. 遅延ハイドレーション
<script setup>
const LazyComponent = defineLazyHydrationComponent(() =>
import('./HeavyComponent.vue')
)
</script>
v3 からの破壊的変更
| 変更点 | v3 | v4 |
|---|---|---|
| ソースディレクトリ | ルート | app/ |
| データのリアクティビティ | ディープ | シャロー(デフォルト) |
| デフォルト値 | null | undefined |
| ルートミドルウェア | クライアント | サーバー |
| アプリマニフェスト | オプトイン | デフォルト |
リファレンスを読み込むタイミング
次の場合は references/hydration.md を読み込んでください:
- 「Hydration node mismatch」エラーのデバッグ
- ClientOnly コンポーネントの実装
- 非決定的なレンダリング問題の修正
- SSR とクライアントレンダリングの理解
次の場合は references/performance.md を読み込んでください:
- Core Web Vitals スコアの最適化
- 遅延読み込みとコード分割の実装
- キャッシュ戦略の設定
- バンドルサイズの削減
次の場合は references/testing-vitest.md を読み込んでください:
- @nuxt/test-utils を使ったコンポーネントテストの作成
- Nuxt コンテキストでのコンポーザブルのテスト
- Nuxt API(useFetch、useRoute)のモック
- Vitest 設定のセットアップ
次の場合は references/deployment-cloudflare.md を読み込んでください:
- Cloudflare Pages または Workers へのデプロイ
- wrangler.toml の設定
- NuxtHub 統合のセットアップ
- D1、KV、R2 バインディングの使用
ハイドレーションのベストプラクティス
ハイドレーションの不一致が発生する原因
| 原因 | 例 | 修正方法 |
|---|---|---|
| 非決定的な値 | Math.random() | useState を使用する |
| サーバー上でのブラウザー API | window.innerWidth | onMounted を使用する |
| サーバー上での日付/時刻 | new Date() | useState または ClientOnly を使用する |
| サードパーティスクリプト | アナリティクス | ClientOnly を使用する |
修正パターン
非決定的な値:
<script setup>
const id = Math.random()
</script>
<script setup>
const id = useState('random-id', () => Math.random())
</script>
ブラウザー API:
<script setup>
const width = window.innerWidth // Crashes on server!
</script>
<script setup>
const width = ref(0)
onMounted(() => {
width.value = window.innerWidth
})
</script>
ClientOnly コンポーネント:
<template>
<ClientOnly>
<MyMapComponent />
<template #fallback>
<div class="skeleton">Loading map...</div>
</template>
</ClientOnly>
</template>
条件付きレンダリング:
<script setup>
const showWidget = ref(false)
onMounted(() => {
// Only show after hydration
showWidget.value = true
})
</script>
<template>
<AnalyticsWidget v-if="showWidget" />
</template>
パフォーマンス最適化
コンポーネントの遅延読み込み
<script setup>
// Lazy load heavy components
const HeavyChart = defineAsyncComponent(() =>
import('~/components/HeavyChart.vue')
)
// With loading/error states
const HeavyChart = defineAsyncComponent({
loader: () => import('~/components/HeavyChart.vue'),
loadingComponent: LoadingSpinner,
errorComponent: ErrorFallback,
delay: 200,
timeout: 10000
})
</script>
<template>
<Suspense>
<HeavyChart :data="chartData" />
<template #fallback>
<LoadingSpinner />
</template>
</Suspense>
</template>
遅延ハイドレーション
<script setup>
// Hydrate when visible in viewport
const LazyComponent = defineLazyHydrationComponent(
() => import('./HeavyComponent.vue'),
{ hydrate: 'visible' }
)
// Hydrate on user interaction
const InteractiveComponent = defineLazyHydrationComponent(
() => import('./InteractiveComponent.vue'),
{ hydrate: 'interaction' }
)
// Hydrate when browser is idle
const IdleComponent = defineLazyHydrationComponent(
() => import('./IdleComponent.vue'),
{ hydrate: 'idle' }
)
</script>
ルートキャッシュ
// nuxt.config.ts
export default defineNuxtConfig({
routeRules: {
// Static pages (prerendered at build)
'/': { prerender: true },
'/about': { prerender: true },
// SWR caching (1 hour)
'/blog/**': { swr: 3600 },
// ISR (regenerate every hour)
'/products/**': { isr: 3600 },
// SPA mode (no SSR)
'/dashboard/**': { ssr: false },
// Static with CDN caching
'/static/**': {
headers: { 'Cache-Control': 'public, max-age=31536000' }
}
}
})
画像の最適化
<template>
<NuxtImg
src="/images/hero.jpg"
alt="Hero image"
width="800"
height="400"
loading="lazy"
placeholder
format="webp"
/>
<NuxtPicture
src="/images/product.jpg"
alt="Product"
sizes="sm:100vw md:50vw lg:400px"
:modifiers="{ quality: 80 }"
/>
</template>
Vitest によるテスト
セットアップ
bun add -d @nuxt/test-utils vitest @vue/test-utils happy-dom
// vitest.config.ts
import { defineVitestConfig } from '@nuxt/test-utils/config'
export default defineVitestConfig({
test: {
environment: 'nuxt',
environmentOptions: {
nuxt: {
domEnvironment: 'happy-dom'
}
}
}
})
コンポーネントテスト
// tests/components/UserCard.test.ts
import { describe, it, expect } from 'vitest'
import { mountSuspended } from '@nuxt/test-utils/runtime'
import UserCard from '~/components/UserCard.vue'
describe('UserCard', () => {
it('renders user name', async () => {
const wrapper = await mountSuspended(UserCard, {
props: {
user: { id: 1, name: 'John Doe', email: '[email protected]' }
}
})
expect(wrapper.text()).toContain('John Doe')
expect(wrapper.text()).toContain('[email protected]')
})
it('emits delete event', async () => {
const wrapper = await mountSuspended(UserCard, {
props: { user: { id: 1, name: 'John' } }
})
await wrapper.find('[data-test="delete-btn"]').trigger('click')
expect(wrapper.emitted('delete')).toHaveLength(1)
expect(wrapper.emitted('delete')[0]).toEqual([1])
})
})
コンポーザブルのモック
// tests/components/Dashboard.test.ts
import { describe, it, expect, vi } from 'vitest'
import { mountSuspended, mockNuxtImport } from '@nuxt/test-utils/runtime'
import Dashboard from '~/pages/dashboard.vue'
// Mock useFetch
mockNuxtImport('useFetch', () => {
return () => ({
data: ref({ users: [{ id: 1, name: 'John' }] }),
pending: ref(false),
error: ref(null)
})
})
describe('Dashboard', () => {
it('displays users from API', async () => {
const wrapper = await mountSuspended(Dashboard)
expect(wrapper.text()).toContain('John')
})
})
サーバールートのテスト
// tests/api/users.test.ts
import { describe, it, expect } from 'vitest'
import { $fetch, setup } from '@nuxt/test-utils/e2e'
describe('API: /api/users', async () => {
await setup({ server: true })
it('returns users list', async () => {
const users = await $fetch('/api/users')
expect(users).toHaveProperty('users')
expect(Array.isArray(users.users)).toBe(true)
})
it('creates a new user', async () => {
const result = await $fetch('/api/users', {
method: 'POST',
body: { name: 'Jane', email: '[email protected]' }
})
expect(result.user.name).toBe('Jane')
})
})
デプロイ
Cloudflare Pages(推奨)
# Build and deploy
bun run build
bunx wrangler pages deploy .output/public
// nuxt.config.ts
export default defineNuxtConfig({
nitro: {
preset: 'cloudflare-pages'
}
})
Cloudflare Workers
// nuxt.config.ts
export default defineNuxtConfig({
nitro: {
preset: 'cloudflare-module'
}
})
# wrangler.toml
name = "my-nuxt-app"
compatibility_date = "2025-01-01"
compatibility_flags = ["nodejs_compat"]
[[d1_databases]]
binding = "DB"
database_name = "my-database"
database_id = "xxx-xxx-xxx"
[[kv_namespaces]]
binding = "KV"
id = "xxx-xxx-xxx"
Vercel
// nuxt.config.ts
export default defineNuxtConfig({
nitro: {
preset: 'vercel'
}
})
Netlify
// nuxt.config.ts
export default defineNuxtConfig({
nitro: {
preset: 'netlify'
}
})
NuxtHub(Cloudflare オールインワン)
bun add @nuxthub/core
// nuxt.config.ts
export default defineNuxtConfig({
modules: ['@nuxthub/core'],
hub: {
database: true, // D1
kv: true, // KV
blob: true, // R2
cache: true // Cache API
}
})
// Usage in server routes
export default defineEventHandler(async (event) => {
const db = hubDatabase()
const kv = hubKV()
const blob = hubBlob()
// Use like regular Cloudflare bindings
const users = await db.prepare('SELECT * FROM users').all()
})
環境変数
# .env (development)
API_SECRET=dev-secret
DATABASE_URL=http://localhost:8787
# Production (Cloudflare)
wrangler secret put API_SECRET
wrangler secret put DATABASE_URL
# Production (Vercel/Netlify)
# Set in dashboard or CLI
Nuxt 3 からの移行
ステップ 1:package.json を更新する
{
"devDependencies": {
"nuxt": "^4.0.0"
}
}
ステップ 2:互換モードを有効にする
// nuxt.config.ts
export default defineNuxtConfig({
future: {
compatibilityVersion: 4
}
})
ステップ 3:ファイルを app/ に移動する
# Create app directory
mkdir app
# Move files
mv components app/
mv composables app/
mv pages app/
mv layouts app/
mv middleware app/
mv plugins app/
mv assets app/
mv app.vue app/
mv error.vue app/
ステップ 4:シャローリアクティビティを修正する
// If mutating data.value properties:
const { data } = await useFetch('/api/user', {
deep: true // Enable deep reactivity
})
// Or replace entire value
data.value = { ...data.value, name: 'New Name' }
ステップ 5:デフォルト値を更新する
// v3: data.value is null
// v4: data.value is undefined
// Update null checks
if (data.value === null) // v3
if (!data.value) // v4 (works for both)
よくあるアンチパターン
サーバー上でのクライアント専用コード
// WRONG
const width = window.innerWidth
// CORRECT
if (import.meta.client) {
const width = window.innerWidth
}
// Or use onMounted
onMounted(() => {
const width = window.innerWidth
})
非決定的な SSR
// WRONG - Different on server vs client
const id = Math.random()
const time = Date.now()
// CORRECT - Use useState for consistency
const id = useState('id', () => Math.random())
const time = useState('time', () => Date.now())
非同期コンポーネントでの Suspense の欠落
<AsyncComponent />
<Suspense>
<AsyncComponent />
<template #fallback>
<LoadingSpinner />
</template>
</Suspense>
トラブルシューティング
ハイドレーションの不一致:
window、document、localStorageの使用箇所を確認しますClientOnlyで囲むか、onMountedを使用しますMath.random()、Date.now()、crypto.randomUUID()を探します
ビルドエラー:
rm -rf .nuxt .output node_modules/.vite && bun install
デプロイの失敗:
nitro.presetが対象と一致しているか確認します- 環境変数が設定されているか確認します
- wrangler.toml のバインディングがコードと一致しているか確認します
テストの失敗:
@nuxt/test-utilsがインストールされていることを確認します- vitest.config.ts に
environment: 'nuxt'があるか確認します - 非同期コンポーネントには
mountSuspendedを使用します
関連スキル
- nuxt-core:プロジェクトのセットアップ、ルーティング、設定
- nuxt-data:コンポーザブル、データ取得、状態管理
- nuxt-server:サーバールート、API のパターン
- cloudflare-d1:D1 データベースのパターン
バージョン:4.0.0 | 最終更新日:2025-12-28 | ライセンス:MIT
コメント
Markdown 対応