Description
I'm using the next-superjson-plugin to pass data from next.js server components to client components and this works like a charm.
Besides server components next.js also provides server actions, a new way of fetching data from the backend to to client by directly calling a backend function from the client side.
Server actions have the same serialization problem like passing data from server components to client components: behind the scenes data is serialized as JSON string on the server and then passed to the client. Therefore the following example doesn't work as expected, since the custom type is lost on the client side
"use server"
export async function serverAction(){
return new Prisma.Decimal(10)
}
// client side
const response = await serverAction()
console.log(typeof response) // returns string not decimal/object!
As a workaround we can use SuperJSON.serialize()
and SuperJSON.deserialize()
like this:
"use server"
export async function serverAction(){
return SuperJSON.serialize(new Prisma.Decimal(10))
}
// client side
const response = SuperJSON.deserialize(await serverAction())
However with this solution we are loosing the TypeScript type safety and we have to assign the return types manually.
Is there any way to integrate SuperJSON into next.js server actions? Maybe there is a way to provide a custom serializer to next.js?