0
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?

"Text content does not match server-rendered HTML"の解決方法

0
Last updated at Posted at 2025-11-02

概要

  • Next.js で “Text content does not match server-rendered HTML” というエラーが発生しました。
    • 原因: SSR と CSR で日付のロケール/タイムゾーンが異なり、toLocaleDateString の出力が変わること。
  • Intl.DateTimeFormat にロケールと timeZone を固定して解決します。

事象

  • エラー: “Text content does not match server-rendered HTML.”
    image.png

  • 具体例: Server: "11/2/2025"、Client: "2025/11/2"

  • 原因: SSR(サーバ)と CSR(ブラウザ)で toLocaleDateString のロケール/タイムゾーンが一致していない

エラー該当箇所のコード

new Date(updatedAt).toLocaleDateString() という風にtoLocaleDateStringを使っていた。

解決方針

ロケールとタイムゾーンを固定して、どこで実行しても同一文字列になるようにする日付ユーティリティクラスの作成

date.ts
export function formatJPDate(dateStr: string): string {
  const dt = new Date(dateStr)
  return new Intl.DateTimeFormat('ja-JP', {
    timeZone: 'Asia/Tokyo',
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
  }).format(dt)
}

呼び出し側

caller.ts
import { formatJPDate } from '../date'
// ...
<span className="time">{formatJPDate(it.updatedAt)}</span>

まとめ

  • Intl.DateTimeFormatでロケール/タイムゾーンを固定化
  • ユーティリティ化して横断適用することで、同種の不一致を未然に防げる
0
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
0
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?