SvelteKit은 기본적으로 서버 사이드 렌더링(SSR)을 지원합니다. 그런데 writable()
로 만든 store 값이 페이지를 새로고침하거나 이동할 때 초기화되는 문제가 발생할 수 있습니다.
문제 원인
- SvelteKit은 SSR 시 매 요청마다 store 인스턴스를 새로 생성합니다.
- 이로 인해 클라이언트에서 저장한 store 값이 서버에는 전달되지 않고 초기값으로 리셋됩니다.
간단한 해결 방법: sessionStorage 동기화
클라이언트 환경에서만 store 값을 sessionStorage
에 저장하고, 컴포넌트가 로드될 때 다시 불러오도록 설정하면 값이 유지됩니다.
1. store 정의
src/lib/stores/locationStore.ts
import { writable } from 'svelte/store';
import { browser } from '$app/environment';
const initial = browser && sessionStorage.getItem('location')
? JSON.parse(sessionStorage.getItem('location'))
: {
x: null,
y: null,
address: '',
name: ''
};
export const locationStore = writable(initial);
locationStore.subscribe(value => {
if (browser) {
sessionStorage.setItem('location', JSON.stringify(value));
}
});
2. 사용 예 (store 값 설정)
import { locationStore } from '$lib/stores/locationStore';
function selectStoreData(data) {
locationStore.set({
x: data.x,
y: data.y,
address: data.address,
name: data.name
});
}
3. 다른 페이지에서 가져오기
<code class="language-svelte">
<script>
import { locationStore } from '$lib/stores/locationStore';
$: location = $locationStore;
</script>
<p>선택된 주소: {location.address}</p>
<p>좌표: {location.x}, {location.y}</p>
</code>
보완 팁
- sessionStorage는 탭 간 공유되지 않지만, 새로고침이나 뒤로가기엔 적합
- localStorage를 사용하면 브라우저 간에도 값 유지 가능
- 민감한 정보는 절대 저장하지 마세요 (브라우저 저장소는 안전하지 않음)
결론
SvelteKit에서 클라이언트 상태를 SSR 환경에서도 유지하고 싶다면,
가장 간단한 해결책은 스토어 값을 sessionStorage에 저장하고, 페이지 로드시 다시 복원하는 방식입니다.
'Web > SvelteKit' 카테고리의 다른 글
Cloudflare Pages + Wrangler로 SvelteKit SSR 배포하기 (0) | 2025.06.04 |
---|---|
SvelteKit 최신 프로젝트 생성 방법 (2025 기준) (0) | 2025.06.03 |
MongoDB 데이터를 Redis로 캐시 처리하기(예제) (0) | 2025.02.21 |
SvelteKit에서 Redis 캐시 사용하여 MongoDB 연동하기 (1) | 2025.02.21 |
SvelteKit에서 서버 데이터를 클라이언트로 전달시 유의사항 (0) | 2025.02.17 |