getStaticProps with SWR "Error serializing `.initialData.config.transformRequest[0]` returned from `getStaticProps`"

Viewed 831

I'm trying to use SWR in Next.js env.

const Best = (props: InferGetStaticPropsType<typeof getStaticProps>) => {
  const { data } = useSWR('/best', apis.getBestProduct, {
    initialData: props.initialData,
  });

  console.log(data);

  return (
    ...SOME PRESENTER
  );
};

export const getStaticProps: GetStaticProps = async () => {
  const data = await apis.getBestProduct();
  return { props: { initialData: data } };
};

export default Best;

I want to use useSWR with getStaticProps.

But this code makes error like this.

Server Error
Error: Error serializing `.initialData.config.transformRequest[0]` returned from `getStaticProps` in "/best".
Reason: `function` cannot be serialized as JSON. Please only return JSON serializable data types.

The data came well, I don't know why it doesn't work.

I'm using MacOS, custom Node.js server, and this is localhost.

1 Answers

getStaticProps sends your data to the front end by first serializing it with JSON—that is, it transforms data from a runtime JavaScript object into a string that can be parsed into a runtime JavaScript object by your front end.

However, JSON has certain limitations, one of which is that it cannot serialize functions. And somewhere in your data object you have a value that is a function. You need to clean up this data object before you return it from getStaticProps.

For example, suppose data.myFunction is a function, you could do something like:

export const getStaticProps: GetStaticProps = async () => {
  const {myFunction, ...data} = await apis.getBestProduct();
  return { props: { initialData: data } };
};

This will remove myFunction and leave all the other keys in data.

Related