Output Validation

tRPC gives you automatic type-safety of outputs without the need of adding a validator; however, it can be useful at times to strictly define the output type in order to prevent sensitive data of being leaked.

Similarily to input:, an output: validation to the query() and mutation() router methods. The output validator is invoked with the payload returned by the resolve() function.

When an output validator is defined, its inferred type is expected as the return type of the resolve() function.

info
  • This is entirely optional and only if you want to ensure you don’t accidentally leak anything e
  • If output validation fails, the server will respond with a INTERNAL_SERVER_ERROR.

Examples

tRPC works out-of-the-box with yup/superstruct/zod/myzod/custom validators/[..] - see test suite

With Zod

  1. import * as trpc from '@trpc/server';
  2. import { z } from 'zod';
  3. // [...]
  4. export const appRouter = trpc.router<Context>().query('hello', {
  5. output: z.object({
  6. greeting: z.string(),
  7. }),
  8. // expects return type of { greeting: string }
  9. resolve() {
  10. return {
  11. greeting: 'hello!',
  12. };
  13. },
  14. });
  15. export type AppRouter = typeof appRouter;

With Yup

  1. import * as trpc from '@trpc/server';
  2. import * as yup from 'yup';
  3. // [...]
  4. export const appRouter = trpc.router<Context>().query('hello', {
  5. output: yup.object({
  6. greeting: yup.string().required(),
  7. }),
  8. resolve() {
  9. return { greeting: 'hello!' };
  10. },
  11. });
  12. export type AppRouter = typeof appRouter;

With Superstruct

  1. import * as trpc from '@trpc/server';
  2. import * as t from 'superstruct';
  3. // [...]
  4. export const appRouter = trpc.router<Context>().query('hello', {
  5. input: t.string(),
  6. output: t.object({
  7. greeting: t.string(),
  8. }),
  9. resolve({ input }) {
  10. return { greeting: input };
  11. },
  12. });
  13. export type AppRouter = typeof appRouter;

With custom validator

  1. import * as trpc from '@trpc/server';
  2. import * as t from 'superstruct';
  3. // [...]
  4. export const appRouter = trpc.router<Context>().query('hello', {
  5. output: (value: any) => {
  6. if (value && typeof value.greeting === 'string') {
  7. return { greeting: value.greeting };
  8. }
  9. throw new Error('Greeting not found');
  10. },
  11. // expects return type of { greeting: string }
  12. resolve() {
  13. return { greeting: 'hello!' };
  14. },
  15. });
  16. export type AppRouter = typeof appRouter;