LoginSignup
3
2

More than 5 years have passed since last update.

date-fnsでSSRした時の「Text content did not match」

Last updated at Posted at 2018-06-22

エラー

SSRをする場合、サーバーとクライアントでのレンダリング結果が一致していないとエラーが出る。

date-fnsを使って、日付のフォーマットをした時に以下のような現象に遭遇した。

const dateFormat = (date: string) => {
  return format(new Date(date), 'YYYY/MM/DD HH:mm:ss')
}
Warning: Text content did not match.
Server: "2018/06/20 05:01:02" Client: "2018/06/20 14:01:02"

Dateオブジェクトにはタイムゾーンのデータが格納されていないとのことで、そのままformat関数に渡すだけだとレンダリング結果にズレが出ているのがわかる。

これはサーバーとクライアントとで、コードを実行している現地時間を返しているためらしい。(※Moment.jsはタイムゾーンもライブラリで扱える)

解決法

Dateオブジェクトにタイムゾーン情報を明示してから関数に渡す。

format(
  new Date(date).toLocaleString('ja-JP', { timeZone: 'Asia/Tokyo' }),
  'YYYY/MM/DD HH:mm:ss'
)
3
2
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
2