I am creating a blog using NextJS and luxon.
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?
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;