Next.js Error: Inconsistent text content between server-rendered HTML and hydration. Unicode characters U+202F versus U+0020

Having issues with dates in Next.js development. Encountering three errors that need to be addressed:

Warning: Text content did not match. Server: "Tuesday, January 24, 2023 at 11:01 AM" Client: "Tuesday, January 24, 2023 at 11:01 AM"

Error: Hydration failed because the initial UI does not match what was rendered on the server.

Error: There was an error while hydrating. Due to the issue occurring outside of a Suspense boundary, client rendering takes over for the entire root page.

The subsequent errors seem connected to the first one.

Noteworthy is that the discrepancy between the server and client texts only involve spacing around time notation – why no-break space (U+202F) on the server but regular space (U+0020) on the client?

Currently employing getServerSideProps as shown below:

export async function getServerSideProps() {
  const eventsResult = (await prisma.event.findMany()).slice(0, 3);
  const newsResult = (await prisma.news.findMany()).slice(0, 3);

  return {
    props: {
      events: JSON.parse(JSON.stringify(eventsResult)),
      news: JSON.parse(JSON.stringify(newsResult)),
      backgroundColor: "red",
    },
  };
}

Initially considered that JSON parsing might influence this issue, yet altering the code yielded no success:

export async function getServerSideProps() {
  const eventsResult = (await prisma.event.findMany()).slice(0, 3);
  const newsResult = (await prisma.news.findMany()).slice(0, 3);

  const formattedEventsResults = eventsResult.map((e) => ({
    ...e,
    start: e.start.toString(),
    end: e.start.toString(),
  }));

  const formattedNewsResult = newsResult.map((n) => ({
    ...n,
    datetime: n.datetime.toString(),
  }));

  return {
    props: {
      events: formattedEventsResults,
      news: formattedNewsResult,
      backgroundColor: "red",
    },
  };
}

The specific line within the component displaying the date reads as follows:

(Without involving timezone conversions since working with fabricated data for simplicity's sake. Just seeking consistency between stored and displayed values.)

{new Date(props.start).toLocaleString(undefined, {
  timeZone: "UTC",
  year: "numeric",
  month: "long",
  day: "2-digit",
  weekday: "long",
  hour: "2-digit",
  minute: "2-digit",
})}

Any suggestions on enforcing synchronization between server and client rendering without encountering hydration challenges?

Answer â„–1

To resolve the issue, I implemented a solution where all spaces within the formatted date were replaced with a standard space character.

const myFormattedDate = new Date().toLocaleString(undefined, {
  timeZone: "UTC",
  year: "numeric",
  month: "long",
  day: "2-digit",
  weekday: "long",
  hour: "2-digit",
  minute: "2-digit",
}).replace(/\s/g, ' ')

Answer â„–2

After taking the necessary steps, I successfully resolved the problem by updating my Chrome browser to the most recent version. It seems like a hotfix must have been implemented.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Visibility in classes can shift once a new file is imported

Currently, I am encountering a puzzling issue in my angular2 project using typescript. In my main.ts file, which contains a component along with some imports at the start of the file, there is a custom type class (let's call it TypeFoo) located in mod ...

What is the best approach to defining a type for a subclass (such as React.Component) in typescript?

Can someone help me with writing a type definition for react-highlight (class Highlightable)? I want to extend Highlightable and add custom functionality. The original Highlightable JS-class is a subclass of React.Component, so all the methods of React.Com ...

TypeScript throws an error when attempting to call a user-defined event handling function

I have created a custom event handling function like this: /** Trigger an event when clicking outside of a specific node */ export function eventHandlers(node: HTMLElement) { const handleClick = (event: MouseEvent) => { if (node && ...

Leveraging React SSR with Next.js, we can utilize the `getInitialProps` method to insert a

When working on Next.js with server-side rendering in React, I encountered an issue while trying to render a page as shown below: // This common element is used in many projects through my private node_modules const Header = ({ result }) => <div> ...

What is the most efficient method for transferring images to Google Cloud Storage?

Context: I am currently working on incorporating a new feature that allows users to upload their profile image to Google Cloud Storage (GCS). I am aware of two methods for uploading objects using the client library: The conventional method (refer here: h ...

Contrasting bracket notation property access with Pick utility in TypeScript

I have a layout similar to this export type CameraProps = Omit<React.HTMLProps<HTMLVideoElement>, "ref"> & { audio?: boolean; audioConstraints?: MediaStreamConstraints["audio"]; mirrored?: boolean; screenshotFormat?: "i ...

Automatically collapse the Shadcn-UI Accordion when the mouse exits

For my self-education project, I am working on building a sidebar with an accordion using Shadcn-ui, NextJS (13.4), React, and Node. Being new to these technologies, I have encountered a problem that I can't seem to solve. The sidebar expands on mous ...

How to reference an array from one component to another in Angular 2

Within my AddUserComponent, I have a public array declared like this: public arr: Array<any> = [] This array stores the names of users. Now, I need to access these values in another component called AddTopicComponent in order to display the user&a ...

Using Angular's dependency injection in a project that has been transpiled with Babel

I am currently attempting to transpile my Angular 6 project, which is written in TypeScript, using the new Babel 7. However, I am facing challenges with getting dependency injection to function properly. Every time I try to launch the project in Chrome, I ...

Website created using React without the use of Javascript

Currently, I am considering migrating one of my websites that is built using Python-Flask and Jinja2. The reason behind this decision is primarily due to the limitations of Jinja2's developer experience and the fact that Python is not typed by default ...

ngModelChange doesn't trigger if the value is manually altered

Here is the scenario I am experiencing: //html <input (ngModelChange)="onSelection()" [(ngModel)]="selectedNode" > // in the ts file onSelection() { alert('changed'); } Typing something inside the input tri ...

Production environment is not recognizing Next JS environment variables

In the Next.js documentation, it states that you should declare your environment variables in next.config.js under the env key in order to access them at build time: env: { GOOGLE_ANALYTICS_ID: process.env.GOOGLE_ANALYTICS_ID }, While this setup wor ...

Exclusive Pages in NextJS for Development Purposes

I want to set up a /storybook page specifically for development purposes. However, I do not want this page to be accessible in production mode. How can we make that happen? ...

How can I update a value using a specific key in Angular?

So, I have a string value that I need to pass to another function. For instance, if the string is 'eng', I want it to be converted to 'en'. I'm looking for a solution that does not involve using slice or if statements. I attempted ...

A more advanced approach to validating form input in React/Next Js

I have designed a basic form for my web application. I am considering adding a feature to validate all fields, ensuring they are not empty and displaying an error message if necessary. Here is the outline of what I have so far: import { useState } from &ap ...

Encountering an issue with a custom hook causing an error stating "Attempting to access block-scoped variable 'X' before its declaration."

Currently, I am in the process of developing my initial custom hook. My confusion lies in the fact that an error is being displayed, even though the function is defined just a few lines above where it's invoked. Here is the relevant code snippet: f ...

Angular2 tutorial with VS2015 may encounter a call-signature error that is expected

Currently following the Angular2 tutorial in VS2015 and encountering an issue with a warning that is impeding the compilation of one of my TypeScript files. The link to the tutorial is provided below. https://angular.io/docs/ts/latest/tutorial/toh-pt4.htm ...

What is the key attribute for a component that is not displayed in reactjs?

I have completed my project and now I am trying to generate a production build. However, I encountered an error with the message "Component definition is missing display name" while using Next.js. Out of all the components in my project, only two are show ...

Tips for effectively utilizing a Query or QueryTask with local graphics (GraphicsLayer)

Working on developing an ESRI map prototype using Angular4, I have successfully utilized the Draw tool to initiate a Query on a FeatureLayer to draw various graphics such as ConvexHull and Buffer. The primary goal was to create a clear Buffer graphic over ...

Issue encountered when trying to utilize Firestore in a React component: TypeError occurs as db.collection is not recognized as a

I am facing an issue while attempting to utilize Firestore within my React component. The specific error message reads "Unhandled Runtime Error: TypeError: firebase_firebaseConfig__WEBPACK_IMPORTED_MODULE_4_.db.collection is not a function." I am utilizing ...