fix: make encryption key storage SSR-safe to prevent 502 errors

- Add isBrowser() check to key-storage.ts functions
- Initialize EncryptionKeyProvider with false and hydrate on mount
- Guard getInitialDisplayState against SSR execution
This commit is contained in:
Víctor Falcón 2025-12-08 17:13:45 +01:00
parent f260e933ca
commit 0fcc66e25d
3 changed files with 18 additions and 4 deletions

View File

@ -52,6 +52,9 @@ function getInitialDisplayState(isKeySet: boolean): DisplayState {
if (!isKeySet) {
return 'encrypted';
}
if (typeof window === 'undefined') {
return 'encrypted';
}
const keyString = getStoredKey();
return keyString ? 'loading' : 'encrypted';
}

View File

@ -27,10 +27,7 @@ const EncryptionKeyContext = createContext<
>(undefined);
export function EncryptionKeyProvider({ children }: { children: ReactNode }) {
const [isKeySet, setIsKeySet] = useState(() => {
const key = getStoredKey();
return !!key;
});
const [isKeySet, setIsKeySet] = useState(false);
const [encryptedMessageData, setEncryptedMessageData] =
useState<EncryptedMessageData | null>(null);
@ -56,6 +53,8 @@ export function EncryptionKeyProvider({ children }: { children: ReactNode }) {
}
useEffect(() => {
refreshKeyState();
const interval = setInterval(() => {
const key = getStoredKey();
setIsKeySet(!!key);

View File

@ -1,6 +1,12 @@
const ENCRYPTION_KEY_NAME = 'encryption_key';
function isBrowser(): boolean {
return typeof window !== 'undefined';
}
export function storeKey(key: string, persistent: boolean): void {
if (!isBrowser()) return;
if (persistent) {
localStorage.setItem(ENCRYPTION_KEY_NAME, key);
} else {
@ -9,6 +15,8 @@ export function storeKey(key: string, persistent: boolean): void {
}
export function getStoredKey(): string | null {
if (!isBrowser()) return null;
return (
sessionStorage.getItem(ENCRYPTION_KEY_NAME) ||
localStorage.getItem(ENCRYPTION_KEY_NAME)
@ -16,10 +24,14 @@ export function getStoredKey(): string | null {
}
export function clearKey(): void {
if (!isBrowser()) return;
sessionStorage.removeItem(ENCRYPTION_KEY_NAME);
localStorage.removeItem(ENCRYPTION_KEY_NAME);
}
export function isKeyPersistent(): boolean {
if (!isBrowser()) return false;
return localStorage.getItem(ENCRYPTION_KEY_NAME) !== null;
}