Data Transformers

You are able to serialize the response data & input args. The transformers need to be added both to the server and the client.

Using superjson

SuperJSON allows us to able to transparently use e.g. standard Date/Map/Sets over the wire between the server and client. That means you can return any of these types in your API-resolver and use them in the client without recreating the objects from JSON.

How to

1. Install

  1. yarn add superjson

2. Add to createTRPCCLient() or withTRPC() config

  1. import superjson from 'superjson';
  2. // [...]
  3. export const client = createTRPCClient<AppRouter>({
  4. // [...]
  5. transformer: superjson,
  6. });
  1. import superjson from 'superjson';
  2. // [...]
  3. export default withTRPC<AppRouter>({
  4. config({ ctx }) {
  5. return {
  6. // [...]
  7. transformer: superjson,
  8. }
  9. }
  10. })(MyApp);

3. Add to your AppRouter

  1. import superjson from 'superjson';
  2. import * as trpc from '@trpc/server';
  3. export const appRouter = trpc.router()
  4. .transformer(superjson)
  5. // .query(...)

Different transformers for upload and download

If a transformer should only be used for one directon or different transformers should be used for upload and download (e.g. for performance reasons), you can provide individual transformers for upload and download. Make sure you use the same combined transformer everywhere.

How to

Here superjson is be used for uploading and devalue for downloading data, because devalue is a lot faster but insecure to use on the server.

1. Install

  1. yarn add superjson devalue

2. Add to utils/trpc.ts

  1. import superjson from 'superjson';
  2. import devalue from 'devalue';
  3. // [...]
  4. export const transformer = {
  5. input: superjson,
  6. output: {
  7. serialize: (object) => devalue(object),
  8. deserialize: (object) => eval(`(${object})`),
  9. },
  10. };

3. Add to createTRPCCLient()

  1. import { transformer } from '../utils/trpc';
  2. // [...]
  3. export const client = createTRPCClient<AppRouter>({
  4. // [...]
  5. transformer: transformer,
  6. });

4. Add to your AppRouter

  1. import { transformer } from '../../utils/trpc';
  2. import * as trpc from '@trpc/server';
  3. export const appRouter = trpc.router()
  4. .transformer(transformer)
  5. // .query(...)

DataTransformer interface

  1. type DataTransformer = {
  2. serialize(object: any): any;
  3. deserialize(object: any): any;
  4. };
  5. type CombinedDataTransformer = {
  6. input: DataTransformer;
  7. output: DataTransformer;
  8. };