43 lines
994 B
TypeScript
43 lines
994 B
TypeScript
"use client";
|
|
|
|
import DOMPurify from "dompurify";
|
|
|
|
export type SanitizeHtmlOptions = {
|
|
tags?: string[];
|
|
attributes?: string[];
|
|
};
|
|
|
|
export function sanitizeHtml(
|
|
input: string,
|
|
options?: SanitizeHtmlOptions,
|
|
): string {
|
|
if (!input) {
|
|
return "";
|
|
}
|
|
|
|
// DOMPurify는 window/document가 있어야 동작한다. Next.js는 "use client" 컴포넌트도
|
|
// 최초 HTML을 만들 때 서버에서 한 번 실행하므로, SSR 단계에서는 sanitize를 건너뛴다.
|
|
// (이 값은 하이드레이션 후 클라이언트에서 다시 렌더링되며 정상적으로 sanitize된다.)
|
|
if (typeof window === "undefined") {
|
|
return input;
|
|
}
|
|
|
|
return DOMPurify.sanitize(
|
|
input,
|
|
{
|
|
USE_PROFILES: {
|
|
html: true,
|
|
},
|
|
ADD_TAGS: options?.tags ?? [],
|
|
ADD_ATTR: options?.attributes ?? [],
|
|
},
|
|
);
|
|
}
|
|
|
|
export function sanitizeHtmlForPreview(
|
|
input: string,
|
|
options?: SanitizeHtmlOptions,
|
|
): string {
|
|
return sanitizeHtml(input, options);
|
|
}
|