Nuxt
Nuxt
A Vue.js-based full-stack framework. SSR, SSG, hybrid rendering.
Nuxt
A Vue.js-based full-stack framework. SSR, SSG, hybrid rendering.
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.
// === 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 };
};
"I need to build a website with Vue.js where SEO is important. Is it okay to just start with Vue CLI?"
"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."
"In Nuxt, I want to make only some pages with SSG and the rest with SSR. Is that possible?"
"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."
"Please explain the difference between useFetch and $fetch in Nuxt."
"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
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.