Locale formatted Dates in Next.JS

By: Rajzer

Created at:

Edited at:

The usual approach to showing dates using Javascript is by using the .toLocaleString() method. Still, in NextJS this method quickly breaks, due to the server-side rendering aspect of the framework which throws errors if the DOM rendered on the server differed from the initial page displayed on the client device, there are many ways to combat this issue, but I have found that there is an easy but inefficient way and a slightly more complicated but way more elegant solution.

Solution 1:

Disable server-side rendering for the page.

In order to disable server-side rendering, you can wrap the problematic component in:

const ComponentWithNoSSR = dynamic(
  () => import('../components/helloWorld'),
  { ssr: false }
)

But this solution is both clumsy and can hurt Your page's SEO performance.

Solution 2:

Render a "placeholder" on the server and change it clientside.

Since NextJS stems from ReactJS we can use React hooks to control the logic in our pages. Then the correct way to display a date with locale string formatting is:

import { useState, useEffect } from "react";

export default MyComponent(date) {
  const [localeString, setLocaleString] = useState("en-GB");
  useEffect(() => {
    setLocaleString(navigator.language);
  }, []);
  return (
    <time datetime={date.toISOString()}>
      {date.toLocaleString(localeString)}
    </time>);
}

Of course this solution gives the default locale of Great Britain, but this can be changed to any place using the appropriate locale string in the initial useState statement.