Fix SSR using Cookies

This commit is contained in:
copecone committed 2026-03-31 15:25:44 +09:00
1 parent 5dfb1dba03
commit 69774fab76
3 files changed
+9 -16

No files matched your search

+1 -1
View File
@@ -3,6 +3,6 @@ import { RenderMode, ServerRoute } from '@angular/ssr';
export const serverRoutes: ServerRoute[] = [
{
path: '**',
renderMode: RenderMode.Prerender,
renderMode: RenderMode.Server,
},
];
@@ -48,11 +48,6 @@
}
}
&.dummy-link {
cursor: not-allowed;
opacity: 0.6;
}
strong {
font-weight: 700;
}
+8 -10
View File
@@ -1,9 +1,6 @@
import { Injectable, signal, inject, PLATFORM_ID, computed, InjectionToken } from '@angular/core';
import { Injectable, signal, inject, PLATFORM_ID, computed, REQUEST } from '@angular/core';
import { isPlatformBrowser, isPlatformServer } from '@angular/common';
// Angular 21 SSR 환경에서 서버 요청 객체를 가져오기 위한 토큰 정의
export const REQUEST = new InjectionToken<any>('REQUEST');
export type Language = 'EN' | 'KR' | 'JP';
@Injectable({
@@ -11,9 +8,7 @@ export type Language = 'EN' | 'KR' | 'JP';
})
export class SettingsService {
private platformId = inject(PLATFORM_ID);
// 서버 사이드에서만 주입되는 Request 객체를 가져옵니다.
private request = inject(REQUEST, { optional: true });
private request: Request | null;
// Signals for state
private _language = signal<Language>('EN');
@@ -28,6 +23,7 @@ export class SettingsService {
userName = computed(() => this._userName());
constructor() {
this.request = inject(REQUEST);
this.initializeSettings();
}
@@ -39,11 +35,12 @@ export class SettingsService {
this._romanisation.set(this.getCookie('romanisation') === 'true');
this._userName.set(this.getCookie('userName') || 'Guest');
} else if (isPlatformServer(this.platformId)) {
// 서버: 요청 객체의 쿠키 읽기
// Express 요청 객체의 경우 headers['cookie']를 사용합니다.
const cookieHeader = (this.request as any)?.headers?.['cookie'] || (this.request as any)?.headers?.cookie;
const cookieHeader = this.request?.headers.get('Cookie');
if (cookieHeader) {
const cookies = this.parseServerCookies(cookieHeader);
// console.log(cookies);
if (cookies['lang']) this._language.set(cookies['lang'] as Language);
if (cookies['darkMode'] !== undefined) this._darkMode.set(cookies['darkMode'] !== 'false');
if (cookies['romanisation'] !== undefined) this._romanisation.set(cookies['romanisation'] === 'true');
@@ -87,6 +84,7 @@ export class SettingsService {
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop()?.split(';').shift();
}
return undefined;
}