💻 Programming

Nuxt.js

The Intuitive Vue Framework

A Vue.js-based full-stack web framework. Supports SSR/SSG/ISR. File-based routing. Provides SEO optimization and an excellent developer experience.

📖 Detailed Explanation

Nuxt.js is a meta framework built on Vue.js that automatically provides the configuration and structure needed for web application development. Like Next.js for React, it has established itself as the de facto standard framework for full-stack development in the Vue ecosystem, and it lets you build production-grade applications right away without complex webpack configuration.

Nuxt 3 provides hybrid rendering that supports SSR (Server-Side Rendering), SSG (Static Site Generation), and ISR (Incremental Static Regeneration). Because the rendering strategy can be set differently for each page, flexible setups are possible, such as building a blog with SSG and serving a dashboard with SSR. It also runs on edge runtimes through the Nitro engine.

File-based routing is a core feature of Nuxt. When you create a Vue file in the pages/ directory, a route is registered automatically. Dynamic routing is implemented in the form [id].vue, and catch-all routing with [...slug].vue. In addition, the directory structure of layouts/, middleware/, composables/, and others enforces code organization, so a consistent project architecture can be maintained.

In practice, Nuxt is particularly strong for SEO-critical marketing sites, blogs, and e-commerce. Because it delivers fully rendered HTML from the server, search engine crawlers can easily index the content, and the initial loading speed (FCP, LCP) is significantly faster than with CSR. Composables such as useFetch and useAsyncData let you manage data fetching and caching declaratively, which also boosts development productivity.

📊 Rendering Mode Comparison

Mode Build Time SEO Use case
SSR Rendered on the server for every request Excellent Real-time data, personalized pages
SSG Static HTML generated at build time Excellent Blogs, documentation, landing pages
ISR Build + periodic regeneration Excellent Product listings, news (frequently changing)
CSR Rendered on the client Limited Post-login dashboards, admin pages

Practical tip: In nuxt.config.ts, you can use routeRules to specify the rendering mode per route. Example: '/blog/**': { prerender: true }

💻 Code Example

<!-- pages/posts/[id].vue - 동적 라우팅 페이지 -->
<script setup lang="ts">
// 라우트 파라미터 접근
const route = useRoute()
const postId = route.params.id

// 서버에서 데이터 페칭 (SSR/SSG 지원)
const { data: post, pending, error } = await useFetch(
  `/api/posts/${postId}`,
  {
    // 캐싱 전략 설정
    key: `post-${postId}`,
    // 에러 발생 시 404 페이지로 리다이렉트
    onResponseError({ response }) {
      if (response.status === 404) {
        throw createError({
          statusCode: 404,
          message: '포스트를 찾을 수 없습니다'
        })
      }
    }
  }
)

// SEO 메타 태그 설정
useSeoMeta({
  title: () => post.value?.title || '로딩 중...',
  description: () => post.value?.excerpt,
  ogImage: () => post.value?.thumbnail
})
</script>

<template>
  <div class="post-page">
    <!-- 로딩 상태 -->
    <div v-if="pending" class="loading">
      <LoadingSpinner />
    </div>

    <!-- 에러 상태 -->
    <div v-else-if="error" class="error">
      <p>{{ error.message }}</p>
      <NuxtLink to="/posts">목록으로 돌아가기</NuxtLink>
    </div>

    <!-- 성공 상태 -->
    <article v-else-if="post">
      <h1>{{ post.title }}</h1>
      <time>{{ formatDate(post.createdAt) }}</time>
      <div class="content" v-html="post.content" />
    </article>
  </div>
</template>
// composables/useProducts.ts - 재사용 가능한 데이터 로직
export const useProducts = () => {
  // 상품 목록 조회 (캐싱 적용)
  const fetchProducts = async (category?: string) => {
    return useFetch('/api/products', {
      query: { category },
      // 5분간 캐시 유지
      getCachedData(key) {
        const data = nuxtApp.payload.data[key]
        if (!data) return null

        const expirationDate = new Date(data.fetchedAt)
        expirationDate.setMinutes(expirationDate.getMinutes() + 5)

        if (expirationDate < new Date()) return null
        return data
      },
      transform(data) {
        return { ...data, fetchedAt: new Date() }
      }
    })
  }

  // 단일 상품 조회
  const fetchProduct = async (id: string) => {
    return useFetch(`/api/products/${id}`, {
      key: `product-${id}`,
      // Nuxt 3의 자동 dedupe - 같은 요청 중복 방지
      dedupe: 'defer'
    })
  }

  // 상품 검색 (클라이언트 사이드)
  const searchProducts = async (query: string) => {
    // $fetch는 useFetch와 달리 반응형이 아님
    // 이벤트 핸들러에서 사용
    return $fetch('/api/products/search', {
      method: 'POST',
      body: { query }
    })
  }

  return {
    fetchProducts,
    fetchProduct,
    searchProducts
  }
}

// 사용 예시: pages/products/index.vue
<script setup>
const { fetchProducts } = useProducts()
const route = useRoute()

// URL 쿼리 파라미터로 카테고리 필터링
const { data: products, refresh } = await fetchProducts(
  route.query.category as string
)

// 카테고리 변경 시 자동 리프레시
watch(() => route.query.category, () => refresh())
</script>
// nuxt.config.ts - 프로젝트 설정
export default defineNuxtConfig({
  // TypeScript 지원
  typescript: {
    strict: true
  },

  // 런타임 환경 변수
  runtimeConfig: {
    // 서버 전용 (절대 클라이언트에 노출 안됨)
    apiSecret: process.env.API_SECRET,
    // 클라이언트에도 노출
    public: {
      apiBase: process.env.API_BASE_URL || 'https://api.example.com'
    }
  },

  // 모듈 (플러그인 생태계)
  modules: [
    '@nuxt/ui',           // 공식 UI 컴포넌트
    '@nuxt/image',        // 이미지 최적화
    '@pinia/nuxt',        // 상태 관리
    '@nuxtjs/i18n',       // 다국어 지원
    '@vueuse/nuxt'        // Vue Composables
  ],

  // 하이브리드 렌더링 - 경로별 렌더링 전략
  routeRules: {
    // 홈페이지: ISR (60초마다 재생성)
    '/': { isr: 60 },
    // 블로그: 정적 생성
    '/blog/**': { prerender: true },
    // 대시보드: CSR only (서버 렌더링 비활성화)
    '/dashboard/**': { ssr: false },
    // API 프록시
    '/api/**': {
      proxy: 'https://api.backend.com/**',
      cors: true
    }
  },

  // Nitro 서버 설정
  nitro: {
    // Vercel, Netlify, Cloudflare 등 자동 감지
    preset: 'vercel-edge',
    // 서버 캐싱
    storage: {
      cache: {
        driver: 'redis',
        url: process.env.REDIS_URL
      }
    }
  },

  // 앱 전역 설정
  app: {
    head: {
      title: 'My Nuxt App',
      meta: [
        { name: 'viewport', content: 'width=device-width, initial-scale=1' }
      ],
      link: [
        { rel: 'icon', type: 'image/png', href: '/favicon.png' }
      ]
    }
  }
})

🗣️ Examples of Practical Conversations

In a meeting to select the tech stack for a new project

"Since this is a marketing site where SEO matters, CSR has its limits. If we go with Nuxt, we can build it with SSG and deploy it to Vercel, and it's easy to switch to SSR later when we add dynamic features. It also saves initial setup time compared to plain Vue, and file-based routing speeds up onboarding for team members."

In a discussion of CSR vs SSR rendering approaches

"Post-login pages like dashboards don't really need SSR. In nuxt.config, just set ssr: false only for '/dashboard/**' with routeRules. But for landing pages and product detail pages, SSR is essential because of SEO and initial loading speed. I like that Nuxt makes this kind of hybrid setup simple."

In a technical interview

"The core value Nuxt provides on top of Vue is threefold. First, universal rendering delivers both SEO and performance; second, file-system-based routing and directory conventions standardize the project structure; and third, the Nitro engine supports a wide range of deployment environments, from edge runtimes to Node.js, with a single codebase."

In a code review - SSR data fetching

"This component calls the API inside onMounted, so there is no data during SSR, which is bad for SEO. If you call useFetch or useAsyncData at the setup level, the data is fetched on the server and included in the HTML. And be sure to include the key option to take advantage of caching. With the same key, requests aren't duplicated."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Cautions

1
Server-Side State Management

If you carelessly use global state (a Pinia store) in SSR, state is shared between requests, which causes security problems. Use the useState() Composable, or initialize state as a function in Pinia. In particular, manage sensitive information such as authentication tokens with cookies or headers.

2
Hydration Mismatch

If the HTML rendered on the server differs from the DOM generated on the client, a Hydration Mismatch warning occurs. Common causes: using Date.now() or Math.random(), and accessing browser-only APIs. Wrap the code in the <ClientOnly> component or handle it in onMounted.

3
Deployment Environment Considerations

SSR requires a Node.js server, while SSG is fine with static hosting. Vercel/Netlify are configured automatically, but when deploying to your own server, you must set the Nitro preset correctly. Edge runtimes (Cloudflare Workers) may not support some Node.js APIs, so you need to check.

🔗 Related Terms

📚 Learn More