The use of toJSON methods in objects is not supported when passing props to Client components in Next.js

Utilizing Sequelize ORM in a Next.js App router, I am retrieving data from a MySQL database. The method "getTransactions" returns the following:

const { rows, count } =  await Transaction.findAndCountAll({
    limit,
    offset,
    where: whereClause,
    order: [['created_at', 'DESC']],
});

return {
    items: rows,
    totalItems: count,
    totalPages: Math.ceil(count / limit),
    currentBalance,
};

When passing this data to a client component, a warning appears in the console:

Warning: Only plain objects can be passed to Client Components from Server Components. Objects with toJSON methods are not supported. Convert it manually to a simple value before passing it to props.

Server Component:

const data = await getTransactions({ page, limit, query: search });
return (
    <TransactionsTable response={data} />
);

Client Component:

const TransactionsTable = ({ response }: { response : PaginatedTransactions | null }) => {
    //TSX
}

I attempted to serialize and deserialize the data, ensuring that timestamps (created_at and updated_at) are converted to Dates before being sent to the client component. This resolved the issue and no warning is logged to the console. However, the necessity of this extra step remains unclear.

const data = await getTransactions({ page, limit, query: search });
const serialize = JSON.stringify(data);
const deserialize = JSON.parse(serialize, (key, value) => {
    if (key === "created_at" || key === "updated_at") {
        return new Date(value);
    }
    return value;
}) as PaginatedTransactions | null;

<TransactionsTable response={deserialize} />

Answer №1

The error occurred because client components can only receive certain types of data:

  • Plain objects and promises
  • Strings
  • Numbers
  • Booleans

When "passing" values from server to client components, they must be serializable as they are sent over the network.

// this does not work
export default async function ServerComponent() {
  const response = await fetch("..");
  return <ClientComponent data={response} />;
}

// this does work
export default function ServerComponent() {
  const promise = fetch("..");
  return <ClientComponent data={promise} />;
}

// this does work too
export default async function ServerComponent() {
  const json = await (await fetch("..")).json();
  return <ClientComponent data={json} />;
}

An exception to this rule is server actions that can be passed to client components, but they also have limitations on the type of values they can accept as parameters.

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

Retrieving a single object in NEXT.JS and MongoDB can be achieved by returning just a single object

Is there a way to retrieve a single object instead of an array from the API? I am specifically looking for just a single "Event" while using MongoDB and Next.js. Currently, I always receive: [{}] But I would like to receive: {} const fetchWithId = (url ...

Guide to setting up App Check in a development environment and launching your next js 13.4 project with an app folder and integrating reactfire

Having trouble integrating "firebase app check" into a Next.js 13.4 project that has the "app" directory in development mode. I attempted to use ReactFire but kept running into errors. Since the latest version of Next.js is in SSR, I tried using effects to ...

Next.js is reporting an error where the Schema has not been registered for Mongoose

Recently, I started using next.js and encountered an issue when calling an API with a reference to another document. Mongoose threw an error saying "Schema hasn't been registered for model". Below is the code snippet: Models Task.js // Task Model C ...

Importing Heroicons dynamically in Next.js for more flexibility

In my Next.js project, I decided to use heroicons but faced a challenge with dynamic imports. The current version does not support passing the icon name directly to the component, so I created my own workaround. // HeroIcon.tsx import * as SolidIcons from ...

Deployment of the website resulted in a NextJS 500 internal server error, yet the build functions flawlessly when tested locally

Everything runs flawlessly on my personal computer using pm2. There are no errors, every page loads perfectly, and fetching files does not result in any 404 or 500 errors. It's absolutely fantastic! This is exactly how I envision it working. However, ...

Tips for preventing a React component from re-fetching data when navigating back using the browser button

In my React app using Next.js and the Next Link for routing, I have two pages set up: /product-list?year=2020 and /product-list/details?year=2020&month=4 Within the pages/product-list.js file, I am utilizing React router to grab the query parameter ye ...

Nextjs API call ended without a response being sent

I am currently facing a challenge in my NextJS project as my endpoint API does not support multiple calls, and I am looking to implement a data refresh every 3 minutes from the original source. To achieve this, I have integrated an API in NextJS by creati ...

I'm having trouble resolving 'fs' within my Next.js api route

When attempting to use the fs module within my api route file for filesystem operations, I encountered an error message: Module not found: Can't resolve 'fs'. This issue not only prevents me from utilizing fs in my handler function but also ...

The environmental variables stored in the .env file are showing up as undefined in Next.js 13

I am having trouble accessing the environment variables stored in my .env.local file within the utils folder located in the root directory. When I try to console log them, they show as undefined. console.log({ clientId: process.env.GOOGLE_ID, clien ...

What is it about that that ticks off so many different boxes?

Hey there! I've been working on creating checkboxes within next js that iterate through each filter and its options. Fortunately, I managed to get it up and running smoothly. However, I'm encountering an issue where checking one option in a speci ...

Enhance website performance by optimizing pagespeed score for pages containing a Vimeo video on the initial view

I recently launched a website in NextJS 13 that is known for its impressive speed. One of the key features of the site is a video from Vimeo embedded on the first screen. To ensure that the Vimeo iframe does not negatively impact the page speed, I have ex ...

unable to decrease the dimensions of the image within the next/image component

Why won't the image size change? I've attempted to adjust the width and height in the component and also tried styling with className, but no luck. The image only seems to resize when using a regular img tag. Here is my code: function Header() ...

Is it possible to run both a Spring Boot JAR and Next.js app on the same port within a packaged JAR

Is it possible to run NextJs code on a different port like 3000, and have it combined with Springboot in an executable Jar/WAR (with embedded Tomcat) running on default port 8080? Can the combined application jar/war be configured to run on a single port? ...

`Is it common to use defined variables from `.env` files in Next.js applications?`

Next.js allows us to utilize environment variable files such as .env.development and .env.production for configuring the application. These files can be filled with necessary environment variables like: NEXT_PUBLIC_API_ENDPOINT="https://some.api.url/a ...

Trouble arises with Service Workers during the transition from Create React App to Next JS

After transitioning our landing page from create-react-app to Next.js, we encountered an issue with users receiving a cached version of the old website. This is due to the default service worker that was registered on their browsers when using create-react ...

Building a Next.js application in a docker container on a local machine using minikube is successful, however, the build fails when attempting to build it on a staging environment

I've encountered a puzzling issue. My next.js app is running in a docker container. It builds successfully on my local Ubuntu machine with minikube and ks8 orchestration, but it gets stuck indefinitely during the build process on the staging setup. T ...

Having trouble resolving the module path 'fs/promises' while using Next.js and eslint

Recently, I began working on a Next.js application and successfully configured eslint to ensure code quality. Here is the list of dev dependencies for my Next.js app: "devDependencies": { "babel-eslint": "^10.1.0", &qu ...

Exploring the feature of On Demand Cache Revalidation in Next JS 13 with a remote ASP .NET Core backend

Seeking guidance on leveraging NextJS cache revalidation for a specific use case that seems unique. Currently, I am in the process of developing an online food ordering platform where numerous restaurants (currently 30) can publish their menus for customer ...

Problem with session cookies not being included in cross-origin replies using Express, Redis, and Next.js

I am currently working on a project that involves using an Express.js backend in conjunction with a Next.js frontend. The backend utilizes the Redis and connect-redis packages for session management, while the server is deployed on Heroku with the Heroku-D ...

The state update is triggering a soft refresh of the page within Next.js

In my Next.js project, I have integrated a modal component using Radix UI that includes two-way bound inputs with state management. The issue arises when any state is updated, triggering a page-wide re-render and refreshing all states. Here is a snippet of ...