SSR 상태 공유와 SEO 최적화
단순한 Vue 앱에서는 전역 상태를 위해 ref를 파일 최상단에 선언하기도 합니다. 하지만 Nuxt 같은 서버 사이드 렌더링 환경에서는 이렇게 하면 A 사용자의 정보가 B 사용자에게 노출되는 '크로스 리퀘스트(Cross-Request) 오염'이 발생할 수 있습니다.
이를 완벽히 방지하는 Nuxt 4의 전용 상태 훅이 useState입니다. 또한 useSeoMeta를 통해 페이지별로 완벽한 SEO(검색엔진 최적화) 태그를 설정할 수 있습니다.
<!-- ==========================================
// 📂 app/composables/useTheme.ts (상태 공유 훅)
// ⚠️ 주의: 실제 .ts 파일에서는 <script> 태그를 작성하지 않습니다.
// ========================================== -->
<script>
// Nuxt에서는 전역 상태를 위해 useState를 사용합니다.
// 'theme' 이라는 고유 키값을 가지며, 기본값은 'light' 입니다.
export const useTheme = () => useState('theme', () => 'light')
</script>
<!-- ==========================================
// 📂 app/pages/index.vue (SEO와 전역 상태 적용)
// ========================================== -->
<template>
<!-- 테마 상태값에 따라 배경색을 동적으로 바꿉니다. -->
<div :class="theme === 'dark' ? 'bg-gray-900 text-white' : 'bg-white text-black'" class="min-h-screen p-8">
<h1 class="text-3xl font-bold mb-4">SEO 및 상태 예제</h1>
<button
@click="theme = theme === 'light' ? 'dark' : 'light'"
class="bg-indigo-500 text-white px-4 py-2 rounded shadow"
>
다크모드 토글 (현재: {{ theme }})
</button>
</div>
</template>
<script setup>
// 1. 위에서 만든 useState 훅을 바로 가져다 씁니다. (자동 임포트)
const theme = useTheme()
// 2. 이 페이지의 SEO 메타 태그를 완벽하게 세팅합니다. (서버에서 구워짐)
useSeoMeta({
title: '멋진 Nuxt 홈페이지',
description: 'Nuxt 4로 만든 빠르고 안전한 웹사이트입니다.',
ogImage: 'https://example.com/banner.png',
twitterCard: 'summary_large_image'
})
</script>