T
TanStack2w ago
extended-salmon

Non-serializable data across server/client boundary

I'm trying to fetch some prisma data in my createServerFn, but i get an error when that data includes non JSON-serializable objects like prisma's JsonValue (as demonstrated below). What is the recommended way of dealing with this issue? 1. Creating DTO for each model and transform non serializable data on the server into something serializable 2. I've seen people recommend return JSON.parse(JSON.stringify(response)) but then i lose type safety 3. https://tanstack.com/router/latest/docs/framework/react/guide/ssr#data-serialization using a custom serializer like superjson? If so, where is option defined, i can't find any examples of this in either tanstack-router or tanstack-start. 4. Any other solutions?
import { createFileRoute } from '@tanstack/react-router'
import { createServerFn } from '@tanstack/react-start'
import type { JsonValue } from '@prisma/client/runtime/library'

interface ServerResponse {
normalString: string
jsonValue: JsonValue
}

export const getServerData = createServerFn().handler(async () => { // Error: Promise<ServerResponse>' is not assignable to parameter of type 'ServerFn<Method, "data", undefined, undefined, ServerResponse>'.
const response: ServerResponse = {
normalString: 'regular string',
jsonValue: { key: 'value', nested: { prop: true } }
}
return response
})

export const Route = createFileRoute('/jsonvalue')({
component: RouteComponent,
loader: async () => await getServerData()
})

function RouteComponent() {
const data = Route.useLoaderData()

return <div>Normal: {data.normalString}, JsonValue: {JSON.stringify(data.jsonValue)}</div>
}
import { createFileRoute } from '@tanstack/react-router'
import { createServerFn } from '@tanstack/react-start'
import type { JsonValue } from '@prisma/client/runtime/library'

interface ServerResponse {
normalString: string
jsonValue: JsonValue
}

export const getServerData = createServerFn().handler(async () => { // Error: Promise<ServerResponse>' is not assignable to parameter of type 'ServerFn<Method, "data", undefined, undefined, ServerResponse>'.
const response: ServerResponse = {
normalString: 'regular string',
jsonValue: { key: 'value', nested: { prop: true } }
}
return response
})

export const Route = createFileRoute('/jsonvalue')({
component: RouteComponent,
loader: async () => await getServerData()
})

function RouteComponent() {
const data = Route.useLoaderData()

return <div>Normal: {data.normalString}, JsonValue: {JSON.stringify(data.jsonValue)}</div>
}
SSR | TanStack Router React Docs
[!WARNING] While every effort has been made to separate these APIs from changes to Tanstack Start, there are underlying shared implementations internally. Therefore these can be subject to change and...
1 Reply
xenial-black
xenial-black2w ago
we will add a way to customize the serializer. its not there yet.

Did you find this page helpful?