提示:本网站现在为维护调试状态

Nuxt 3 応用 - SSR と SSG の深堀り解説

Choyeon
Choyeon
2026年8月19日 1 分で読了 552 閲覧
173 字 895 文字 更新日 2026年11月8日
Nuxt 3 応用 - SSR と SSG の深堀り解説
目次

Advanced Nuxt 3 - Deep Dive into SSR and SSG

Nuxt 3 represents the pinnacle of full-stack frameworks in the Vue ecosystem. Its brand-new Nitro engine unifies server-side and build-time rendering logic, making switching between SSR, SSG, and ISR simpler than ever before.

Essential Differences Between Three Rendering Modes

To understand how Nitro works, first clarify how the three rendering modes differ in their request lifecycle:

<script setup lang="ts">
import { useAsyncData, useFetch, definePageMeta } from '#app'

definePageMeta({
  name: 'products-id',
  path: '/products/:id',
  middleware: ['auth'],
  layout: 'shop'
})

const route = useRoute()
const { data: product, pending, refresh, error } = await useAsyncData(
  `product-${route.params.id}`,
  () => $fetch(`/api/products/${route.params.id}`),
  {
    server: true,
    lazy: false,
    default: () => ({}),
    transform: (res) => ({
      ...res,
      formattedPrice: new Intl.NumberFormat('zh-CN', {
        style: 'currency',
        currency: 'CNY'
      }).format(res.price)
    })
  }
)

const { data: related } = await useFetch(
  '/api/products/related',
  {
    params: { id: route.params.id, limit: 4 },
    pick: ['items']
  }
)

useHead({
  title: () => product.value?.name,
  meta: [
    { name: 'description', content: () => product.value?.description }
  ]
})

const isrTimestamp = ref(Date.now())
</script>

<template>
  <div class="product-page">
    <Suspense>
      <template #default>
        <ProductDetail v-if="product" :product="product" />
        <div v-else-if="error" class="error">{{ error.message }}</div>
      </template>
      <template #fallback>
        <ProductSkeleton />
      </template>
    </Suspense>
    <RelatedProducts v-if="related" :items="related.items" />
  </div>
</template>

Performance and Cost Comparison

Render Mode First TTFB Time to Interactive Server Cost SEO Friendly Best For
SSR ⚡ 300-600ms ✅ Excellent 💸 High ✅ Best Personalized, realtime data
SSG ⚡⚡⚡ <50ms ✅ Best 🆓 Very Low ✅ Best Docs, blogs, product pages
ISR ⚡⚡ <100ms* ✅ Excellent 💰 Medium ✅ Good E-commerce, news, mid-freq updates
CSR (SPA) 🐢 200ms + JS ❌ Poor 🆓 Very Low ⚠️ Extra work needed Dashboards, admin panels

*After first visit, cache hit scenario

Cache Strategy Configuration

Nitro provides multi-layer caching mechanisms. For SSR pages, configure CDN-level caching via routeRules:

// nuxt.config.ts
export default defineNuxtConfig({
  routeRules: {
    '/products/**': { swr: 3600 },
    '/api/**': { swr: 60, cache: { maxItems: 1000 } },
    '/static/**': { static: true }
  }
})

SWR (Stale-While-Revalidate) mode returns cached responses immediately while refreshing data in the background, balancing performance and data freshness.

Hydration Optimization Techniques

In SSR mode, the client needs to hydrate server-rendered HTML. Common performance pitfalls include:

  1. Payload too large: Use definePageMeta's payloadExtractor to slim down data sent to the client
  2. Premature hydration: Wrap non-critical interactive components with <ClientOnly>
  3. Duplicate requests: Properly set useAsyncData keys; leverage Nitro's automatic request deduping

Best Practices

  1. Default to SSG unless pages strongly depend on real-time or personalized data
  2. Mix rendering modes: Home SSG + Detail ISR + User Center SSR rather than uniform approach
  3. Leverage Nitro API Routes to avoid separate backend deployments (for small/medium projects)
  4. Monitor TTFB distribution — if P95 > 1s, consider enabling cache or switching to ISR
  5. Use nuxt build --prerender to pre-render high-frequency pages, reducing cold-start time

Summary

Nuxt 3's Nitro engine completely erases the development differences between SSR and SSG. Developers focus purely on business logic, switching between rendering modes through configuration. The key to choosing a rendering mode lies in: page update frequency × content personalization degree × team ops capability.

X微博Telegram

筆者について

投票

你最希望 Rosetta 优先加入哪项功能?

社区投票(演示数据,可后台删除)

コメント (5)

0 / 3000
dryrun-test
dryrun-test15 天前

dry-run 联调测试评论:验证邮件链路只记日志不投递。

DevOps小能手
DevOps小能手devops-lab.cn2026年9月3日

受益匪浅,感谢大佬分享!

咖啡与代码
咖啡与代码2026年9月3日

补充一点:实际使用中如果遇到 MySQL 的 8 小时超时问题,可以在连接串里加 autoReconnect=true 参数,虽然官方不推荐但挺好用的。

考研加油鸭
考研加油鸭kaoyan-journey.xyz2026年9月3日

有个小问题:你文中用的是 @Async 注解,这个默认用的是 SimpleAsyncTaskExecutor,生产环境是不是最好手动配一个线程池?

像素小贩
像素小贩pixelart.studio2026年9月2日

楼主,我按照你的步骤操作后启动报错:Error creating bean with name 'dataSource',版本是 Spring Boot 3.2,请问有遇到过吗?

関連記事

FastAPI クイックスタート - 高性能 REST API の構築

FastAPI クイックスタート - 高性能 REST API の構築

FastAPI は現代の Python Web フレームワークの中でも傑出しており、型ヒントによる自動ドキュメント生成、非同期サポート、Node.js 並みのパフォーマンスを提供します。この実践ガイドでは、ルート定義、リクエスト検証、依存性注入、データベース統合を含む完全な CRUD API をゼロから構築します。

この記事は閲覧パスワードが必要です 4 分で読了
Python 並行処理:asyncio vs ThreadPool vs ProcessPool

Python 並行処理:asyncio vs ThreadPool vs ProcessPool

Pythonの3大並行モデル徹底比較:GIL下のThreadPool、GIL回避のProcessPool、超高IO向けasyncio。性能と複雑性の4次元デシジョンツリー。

1 分で読了
Alembic ディープガイド:DBマイグレーション + 自動生成 + ブランチマージ

Alembic ディープガイド:DBマイグレーション + 自動生成 + ブランチマージ

SQLAlchemy公式マイグレーションツール Alembic 完全ガイド:env.py設定、autogenerateによるモデル変更検出(カラム・インデックス・制約)、バッチスクリプト、ダウングレードロールバック戦略、複数人開発時のマイグレーションコンフリクトとhead分岐マージの標準SOP、本番デプロイチェックリスト付き。

1 分で読了
RAG 検索拡張生成実践:Embedding + Vector DB + ReRank

RAG 検索拡張生成実践:Embedding + Vector DB + ReRank

プロダクション級RAGをゼロから構築:文書チャンク戦略、Embeddingモデル選定、Vector DBフィルタ検索、RerankerによるTop-K精緻化、引用根拠とプロンプト圧縮。完全動作コード付き。

1 分で読了
アルゴリズム:動的計画法 5大テンプレート

アルゴリズム:動的計画法 5大テンプレート

DP完全制覇:5ステップ共通フレームワーク+5大高頻度テンプレート:ナップサック、部分列、区間DP、ビットDP、木DPに典型コードと変形ポイント。

1 分で読了
Vue 3 コンポジション API 実践

Vue 3 コンポジション API 実践

Vue 3 のコンポジション API は、Vue コンポーネントの設計手法を根本的に変えました。複雑な EC サイトのフィルターコンポーネントの構築を通じて、ref/reactive の使い分け、computed/watch の適切な使用方法、カスタム Composable の抽出原則、ライフサイクルフックのタイミング、provide/inject による階層を超えた状態受け渡しの正しい方法を解説します。

1 分で読了