Home > Enterprise >  How should date strings be handled when rendering on both server and client?
How should date strings be handled when rendering on both server and client?

Time:02-02

I am creating a blog using NextJS and luxon.

  1. I want to include the post creation date in HTML when a post is rendered by the server, so that the Google crawler has that information.
  2. I also want the creation date to display in a suitable format for the end user. I am using the luxon package which formats to the user's timezone and locale automatically

The server does not know where the end user's request is coming from - I don't want to format the date to the user's locale during SSR

...but if there is a difference between the server rendered content and the client rendered content, I get a react-hydration-error

What is the recommended approach for rendering date strings on both server and client?

CodePudding user response:

You can format the date the server and pass it to the client-side as a prop, then format it again to your desired format using luxon. With this method, you can use the formatted date in your HTML for the Google crawler as well as the user, without any difference in the information received by either. This should also avoid the hydration error.

Here is an example:

// server-side:
import { DateTime } from 'luxon';

export async function getServerSideProps() {
  const creationDate = DateTime.utc().toISO();

  return {
    props: {
      creationDate,
    },
  };
}

// client-side:
import { DateTime } from 'luxon';

const Post = ({ creationDate }) => {
  const formattedCreationDate = DateTime.fromISO(creationDate)
    .setLocale('en-US')
    .toLocaleString(DateTime.DATE_FULL);

  return (
    <>
      <p>{formattedCreationDate}</p>
    </>
  );
};

export default Post;
  • Related