I’m working with Next.js, I tried accessing data but got this error:
Error: Error serializing `.profileData` returned from `getStaticProps` in "/profile/[slug]".
Reason: `undefined` cannot be serialized as JSON. Please use `null` or omit this value.
My code:
import { getAllBusinessProfiles } from '../../lib/api';
const Profile = ({ allProfiles: { edges } }) => {
return (
<>
<Head>
<title>Profile</title>
</Head>
<Hero />
<section>
{edges.map(({ node }) => (
<div key={node.id}>
<Link href={`/profile/${node.slug}`}>
<a> {node.businessInfo.name} </a>
</Link>
</div>
))}
</section>
</>
);
}
export default Profile;
export async function getStaticProps() {
const allProfiles = await getAllBusinessProfiles();
return {
props: {
allProfiles
}
};
}
getAllBusinessProfiles from api.js:
const API_URL = process.env.WP_API_URL;
async function fetchAPI(query, { variables } = {}) {
const headers = { 'Content-Type': 'application/json' };
const res = await fetch(API_URL, {
method: 'POST',
headers,
body: JSON.stringify({ query, variables })
});
const json = await res.json();
if (json.errors) {
console.log(json.errors);
console.log('error details', query, variables);
throw new Error('Failed to fetch API');
}
return json.data;
}
export async function getAllBusinessProfiles() {
const data = await fetchAPI(
`
query AllProfiles {
businessProfiles(where: {orderby: {field: DATE, order: ASC}}) {
edges {
node {
date
title
slug
link
uri
businessInfo {
name
title
company
image {
mediaItemUrl
altText
}
highlight
phone
city
country
facebook
instagram
email
website
profiles {
profile
profileInfo
}
extendedProfile {
title
info
}
}
}
}
}
}
`
);
return data?.businessProfiles;
};
What could be the error here? I used the getStaticProps method on Next.js but got the error above instead. Please, check. Thanks.
The error:
Server Error
Error: Error serializing .profileData
returned from getStaticProps
in "/profile/[slug]".
Reason: undefined
cannot be serialized as JSON. Please use null
or omit this value.
I don’t know what could cause this though.
13
Answers
I had the same issue when I was working with redux with next js and the reason was one of the fields in the default state I set it to undefined. Instead I used
null
:error:undefined
was causing the error. Because "undefined" cannot be serialized:you are returning "allProfiles" which is the result of async
getAllBusinessProfiles()
which is either returning undefined, error or one of the fields of the returned object is undefined. "error" object is not serializable in javascriptAdd
JSON.stringify
when calling an asynchronous function that returns an object.Try modifying your
getStaticProps
function like this.Source: MDN
I had this issue using Mongoose and Next.js.
To solve it: I switched from convert require to import then wrapped my result in
JSON.parse(JSON.stringify(result));
.Good:
import mongoose from 'mongoose';
Bad:
const mongoose = require('mongoose');
try this, it worked for me:
I had the same serialization error when accessing a Vercel system environment variable in
getStaticProps
.Using
JSON.stringify
did not do the trick, butString()
worked. My code:Thanks to this GitHub issue for the inspiration
I was having the same issue while trying to find a match in the array of data using the id. The issue I had was the items in the array had ids which were numbers while the value I was getting from params was a string. So all i did was convert the number id to a string to match the comparison.
In
getStaticProps()
function, after fetching your data it will be in json format initially, but you should change it as follow:now it will work.
install a package called babel-plugin-superjson-next and superjson and added a .babelrc file with these contents:
see this topic : https://github.com/vercel/next.js/discussions/11498.
Instead of using
undefined
, you have to usenull
as the value for your variables.Note that the error shows you exactly which variable is using
undefined
as its value. Just modify its value to benull
.The value ‘undefined’ denotes that a variable has been declared, but hasn’t been assigned any value. So, the value of the variable is ‘undefined’. On the other hand, ‘null’ refers to a non-existent object, which basically means ’empty’ or ‘nothing’.
Source: [1]
I had a similar problem too where I was fetching data through apollo directly inside of getStaticProps. All I had to do to fix the error was add the spread syntax to the return.
When you call api you should use try catch. It will resolve error.
Example:
Hope help for you !
put res from API in Curly Brackets