3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Next.js × DOMPurify】DOMPurify.sanitize is not a functionの解決方法

3
Last updated at Posted at 2025-02-28

はじめに

Next.jsDOMPurifyを使用した際に発生したエラーの解決方法について紹介します。

この記事は個人的なアウトプットを目的として作成したものです。そのため、誤った情報や不足している内容が含まれている可能性があります。もし間違いや気になる点がございましたら、ぜひご指摘いただけますと幸いです

現象

以下のようにDOMPurifyを使用してitem.contentをサニタイズしようとしたところ、Next.jsでエラーが発生しました。

import DOMPurify from 'dompurify';

const sanitizeText = (text: string) => {
  return DOMPurify.sanitize(text, { ALLOWED_TAGS: [] });
};

return (
//省略

  <div>
    <div>{sanitizeText(item.content)}</div>
  </div>
  
//省略
);

解決方法

isomorphic-dompurify を使用することで、この問題を解決できます。
このライブラリはサーバーとクライアントの両方で動作する DOMPurify のラッパー であり、Next.js環境でもエラーなく利用できます。

手順

まず、isomorphic-dompurifyをインストールします。

npm install isomorphic-dompurify

次に、isomorphic-dompurifyをインポートします。

import DOMPurify from "isomorphic-dompurify";

const sanitizeText = (text: string) => {
  return DOMPurify.sanitize(text, { ALLOWED_TAGS: [] });
};

return (
  <div>
    <div>{sanitizeText(item.content)}</div>
  </div>
);

これにより、DOMPurifyNext.jsの環境でも利用できるようになります。

終わりに

Next.jsでは、クライアント側の処理とサーバー側の処理を分けて考えることが重要 です。
サーバー・クライアントの概念は少し難しいですが、引き続き学習を頑張ります!

参考

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?