🌐 Web Development

Nuxt

Nuxt

A Vue.js-based full-stack framework. SSR, SSG, hybrid rendering.

πŸ“– Detailed Explanation

Nuxt is a full-stack framework based on Vue.js, a meta-framework on the Vue side that corresponds to Next.js in the React ecosystem. It supports hybrid rendering that flexibly combines server-side rendering (SSR), static site generation (SSG), and client-side rendering (CSR), and provides file-based routing and automatic code splitting.

Nuxt 3 fully supports Vue 3's Composition API and introduces a new server engine called Nitro. Nitro is a universal JavaScript server that can be deployed to various platforms (Node.js, Cloudflare Workers, Vercel, Netlify, etc.) and also runs in an Edge Runtime. It also supports TypeScript as a first-class citizen, ensuring type safety.

The auto-imports feature lets you use Vue APIs such as reactive, ref, and computed, as well as components, without import statements. Functions in the composables/ directory are also imported automatically, making code more concise. In addition, you can define API endpoints in the server/ directory, enabling full-stack development.

Nuxt extends its functionality through a module system. There are various official and community modules, such as @nuxt/content (Markdown-based CMS), @nuxt/image (image optimization), and @pinia/nuxt (state management). When you add a module in the nuxt.config.ts file, it is configured automatically, improving the development experience.

πŸ’» Code Example

// === Nuxt 3 ν”„λ‘œμ νŠΈ ꡬ쑰 ===
// nuxt.config.ts - ν”„λ‘œμ νŠΈ μ„€μ •
export default defineNuxtConfig({
    // λ Œλ”λ§ λͺ¨λ“œ μ„€μ •
    ssr: true, // SSR ν™œμ„±ν™” (κΈ°λ³Έκ°’)

    // λΌμš°νŠΈλ³„ λ Œλ”λ§ μ „λž΅ (ν•˜μ΄λΈŒλ¦¬λ“œ λ Œλ”λ§)
    routeRules: {
        '/': { prerender: true }, // SSG - λΉŒλ“œ μ‹œ 정적 생성
        '/blog/**': { swr: 3600 }, // ISR - 1μ‹œκ°„λ§ˆλ‹€ μž¬κ²€μ¦
        '/admin/**': { ssr: false }, // CSR - ν΄λΌμ΄μ–ΈνŠΈ μ „μš©
        '/api/**': { cors: true }, // API 라우트
    },

    // λͺ¨λ“ˆ 등둝
    modules: [
        '@pinia/nuxt',
        '@nuxt/content',
        '@nuxt/image',
    ],

    // λŸ°νƒ€μž„ ν™˜κ²½ λ³€μˆ˜
    runtimeConfig: {
        // μ„œλ²„ μ „μš© (ν΄λΌμ΄μ–ΈνŠΈμ— λ…ΈμΆœ μ•ˆλ¨)
        apiSecret: process.env.API_SECRET,
        // public: ν΄λΌμ΄μ–ΈνŠΈμ—μ„œλ„ μ ‘κ·Ό κ°€λŠ₯
        public: {
            apiBase: process.env.NUXT_PUBLIC_API_BASE || '/api'
        }
    }
});

// === pages/index.vue - νŽ˜μ΄μ§€ μ»΄ν¬λ„ŒνŠΈ ===
<script setup lang="ts">
// Auto-import: ref, useFetch λ“± import λΆˆν•„μš”

// SEO 메타데이터
useSeoMeta({
    title: 'ν™ˆ',
    description: '메인 νŽ˜μ΄μ§€μž…λ‹ˆλ‹€.',
    ogImage: '/og-image.png',
});

// μ„œλ²„μ—μ„œ 데이터 κ°€μ Έμ˜€κΈ°
const { data: posts, pending, error } = await useFetch('/api/posts', {
    // 캐싱 μ˜΅μ…˜
    key: 'posts',
    // λ³€ν™˜
    transform: (data) => data.slice(0, 10),
});

// λ°˜μ‘ν˜• μƒνƒœ
const count = ref(0);
const doubled = computed(() => count.value * 2);
</script>

<template>
    <div>
        <h1>μ΅œμ‹  κΈ€</h1>

        <div v-if="pending">λ‘œλ”© 쀑...</div>
        <div v-else-if="error">μ—λŸ¬: {{ error.message }}</div>
        <ul v-else>
            <li v-for="post in posts" :key="post.id">
                <NuxtLink :to="`/blog/${post.slug}`">
                    {{ post.title }}
                </NuxtLink>
            </li>
        </ul>

        <!-- ν΄λΌμ΄μ–ΈνŠΈ μ „μš© μ»΄ν¬λ„ŒνŠΈ -->
        <ClientOnly>
            <Counter v-model="count" />
            <template #fallback>
                <p>μΉ΄μš΄ν„° λ‘œλ”© 쀑...</p>
            </template>
        </ClientOnly>
    </div>
</template>

// === pages/blog/[slug].vue - 동적 라우트 ===
<script setup lang="ts">
// URL νŒŒλΌλ―Έν„° μ ‘κ·Ό
const route = useRoute();
const slug = route.params.slug as string;

// 데이터 페칭
const { data: post } = await useFetch(`/api/posts/${slug}`);

// 404 처리
if (!post.value) {
    throw createError({
        statusCode: 404,
        statusMessage: 'Post Not Found'
    });
}

// 동적 메타데이터
useSeoMeta({
    title: () => post.value?.title,
    description: () => post.value?.excerpt,
});
</script>

// === server/api/posts/index.get.ts - API μ—”λ“œν¬μΈνŠΈ ===
export default defineEventHandler(async (event) => {
    // 쿼리 νŒŒλΌλ―Έν„°
    const query = getQuery(event);
    const page = Number(query.page) || 1;

    // λ°μ΄ν„°λ² μ΄μŠ€ 쑰회 (예: Prisma)
    const posts = await prisma.post.findMany({
        take: 10,
        skip: (page - 1) * 10,
        orderBy: { createdAt: 'desc' }
    });

    return posts;
});

// === server/api/posts/[slug].get.ts - 동적 API ===
export default defineEventHandler(async (event) => {
    const slug = getRouterParam(event, 'slug');

    const post = await prisma.post.findUnique({
        where: { slug }
    });

    if (!post) {
        throw createError({
            statusCode: 404,
            message: 'Post not found'
        });
    }

    return post;
});

// === composables/useAuth.ts - μ»€μŠ€ν…€ 컴포저블 ===
export const useAuth = () => {
    const user = useState<User | null>('user', () => null);
    const isLoggedIn = computed(() => !!user.value);

    const login = async (credentials: LoginInput) => {
        const data = await $fetch('/api/auth/login', {
            method: 'POST',
            body: credentials
        });
        user.value = data.user;
    };

    const logout = async () => {
        await $fetch('/api/auth/logout', { method: 'POST' });
        user.value = null;
        navigateTo('/');
    };

    return { user, isLoggedIn, login, logout };
};

πŸ—£οΈ Examples of Practical Conversations

PM

"I need to build a website with Vue.js where SEO is important. Is it okay to just start with Vue CLI?"

Developer

"If SEO is important, I recommend Nuxt. Vue CLI is a SPA by default, so search engine crawling is difficult. Nuxt supports SSR/SSG, so content is properly exposed to search engines, and it also provides file-based routing and a server API out of the box, so development efficiency is high as well."

Colleague

"In Nuxt, I want to make only some pages with SSG and the rest with SSR. Is that possible?"

Developer

"You can use hybrid rendering. In routeRules in nuxt.config.ts, you can specify the rendering strategy for each route. You can flexibly configure the main page as SSG with prerender, the blog as ISR with swr, and the admin page like CSR with ssr: false."

Interviewer

"Please explain the difference between useFetch and $fetch in Nuxt."

Candidate

"useFetch is a composable optimized for SSR; it fetches data on the server and then passes it to the client, preventing duplicate requests. It also provides reactive state and statuses such as pending and error. $fetch is a general-purpose HTTP client based on ohmyfetch, and is suitable for use in event handlers or on the server side."

Take a mock interview on this topic β†’ WIA SOOM AI Interview Β· Start for free

⚠️ Cautions

Server/client context: Nuxt code can run on both the server and the client. Browser APIs such as window and document cannot be used on the server, so you need to check with process.client or wrap them in the <ClientOnly> component.

Data fetching location: useFetch and useAsyncData must be called only at the top level of setup(). Calling them inside event handlers or conditional statements can cause SSR hydration issues. In such cases, use $fetch.

useState vs ref: useState shares state between server and client and is restored during hydration. In contrast, ref is component-local state. If you need global state, use useState or Pinia.

πŸ”— Related Terms

πŸ“š Learn More