서버에 없는 window와 localStorage를 클라이언트 생명주기에서 사용합니다.
Nuxt setup은 서버에서도 실행될 수 있으므로 브라우저 전용 API는 onMounted, import.meta.client 또는 ClientOnly 경계에서 접근합니다.
초기 UI에 필요한 값이면 cookie나 서버 세션으로 전달해 hydration 차이를 줄입니다.
mounted 후 값이 나타날 때 레이아웃 이동과 대체 UI를 설계합니다.
setup 최상위에서 window를 읽으면 SSR 중 ReferenceError가 발생합니다.
로컬 프로젝트에서 확인해보세요localStorage에서 theme를 읽되 light와 dark만 허용하세요.
<script setup>
const width = ref(null);
function update() {
width.value = window.innerWidth;
}
onMounted(() => {
update();
window.addEventListener("resize", update);
});
onUnmounted(() => {
if (import.meta.client) window.removeEventListener("resize", update);
});
</script>
<template>
<main>
<h1>브라우저 너비</h1>
<p>{{ width === null ? "서버 렌더링 중" : width + "px" }}</p>
</main>
</template>