oRPC RPC JSON Serializer
Extend or override the standard RPC JSON serializer.
SKILL.mdskills/orpc-rpc-json-serializer/SKILL.md
GitHubRPC JSON Serializer
Handles JSON payloads for the RPC Protocol and supports native data types.
Extending Native Data Types
- Define Your Custom Serializer:
import type { StandardRPCCustomJsonSerializer } from '@orpc/client/standard'
export class User {
constructor(
public readonly id: string,
public readonly name: string,
public readonly email: string,
public readonly age: number,
) {}
toJSON() {
return { id: this.id, name: this.name, email: this.email, age: this.age }
}
}
export const userSerializer: StandardRPCCustomJsonSerializer = {
type: 21,
condition: data => data instanceof User,
serialize: data => data.toJSON(),
deserialize: data => new User(data.id, data.name, data.email, data.age),
}
Ensure
typeis unique and greater than20to avoid conflicts with built-in types.
- Use Your Custom Serializer:
import { RPCHandler } from '@orpc/server/fetch'
import { RPCLink } from '@orpc/client/fetch'
const handler = new RPCHandler(router, {
customJsonSerializers: [userSerializer],
})
const link = new RPCLink({
url: 'https://example.com/rpc',
customJsonSerializers: [userSerializer],
})
Overriding Built-in Types
Match type with built-in types.
Example: oRPC ignores undefined in objects. To override:
export const undefinedSerializer: StandardRPCCustomJsonSerializer = {
type: 3, // Match built-in undefined type
condition: data => data === undefined,
serialize: data => null,
deserialize: data => undefined,
}