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

Advanced Nuxt 3 - Deep Dive into SSR and SSG

Choyeon
Choyeon
Aug 19, 2026 1 min read 553 Views
173 words 895 chars Updated Nov 8, 2026
Advanced Nuxt 3 - Deep Dive into SSR and SSG
Table of contents

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

About the author

Poll

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

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

Comments (5)

0 / 3000
dryrun-test
dryrun-test15 d ago

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

DevOps小能手
DevOps小能手devops-lab.cnSep 3, 2026

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

咖啡与代码
咖啡与代码Sep 3, 2026

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

考研加油鸭
考研加油鸭kaoyan-journey.xyzSep 3, 2026

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

像素小贩
像素小贩pixelart.studioSep 2, 2026

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

Related posts

Quick Start with FastAPI - Building High-Performance REST APIs

Quick Start with FastAPI - Building High-Performance REST APIs

FastAPI stands out among modern Python web frameworks with auto-generated docs based on type hints, async support, and Node.js-level performance. This hands-on guide builds a complete CRUD API from scratch covering route definition, request validation, dependency injection, and database integration—master FastAPI essentials in 30 minutes.

This post requires a password 4 min read
Python Concurrency: asyncio vs ThreadPool vs ProcessPool

Python Concurrency: asyncio vs ThreadPool vs ProcessPool

Deep Python concurrency comparison: ThreadPool for IO-bound, ProcessPool bypassing GIL for CPU-bound, asyncio coroutines for ultra IO. 4-dimension decision tree with perf and complexity.

1 min read
Alembic Deep Dive: Migrations, Autogenerate, and Branch Merging

Alembic Deep Dive: Migrations, Autogenerate, and Branch Merging

Comprehensive Alembic (official SQLAlchemy migration tool) guide: env.py setup, autogenerate detecting model changes (fields, indexes, constraints), batch scripts, downgrade rollback strategies, plus standard SOP for multi-developer migration branch conflicts and divergent head merging, with production deploy checklist.

1 min read
RAG in Practice: Embedding + Vector DB + ReRank

RAG in Practice: Embedding + Vector DB + ReRank

Build production-grade RAG from scratch: doc chunking (size + overlap windows), embedding model selection, vector DB retrieval filters, Reranker refining Top-K, plus citation grounding and prompt compression. Complete runnable code included.

1 min read
Dynamic Programming: 5 Universal Templates

Dynamic Programming: 5 Universal Templates

Master DP: 5-step universal framework then 5 high-frequency templates: Knapsack, Subsequence, Interval DP, Bitmask DP, Tree DP, each with canonical code and variant keys.

1 min read
Vue 3 Composition API in Practice

Vue 3 Composition API in Practice

Vue 3's Composition API fundamentally changed how Vue components are organized. Through building a complex e-commerce filter component, this article demonstrates ref vs reactive choices, proper computed/watch usage, custom Composable extraction principles, lifecycle hook timing, and the correct approach to cross-layer state via provide/inject.

1 min read