Route Metadata

Route metadata allows you to add an optional route specific meta property which will be available in all middleware function parameters.

Create router with typed metadata

  1. import * as trpc from '@trpc/server';
  2. // [...]
  3. interface Meta {
  4. hasAuth: boolean
  5. }
  6. export const appRouter = trpc.router<Context, Meta>();

Example with per route authentication settings

server.ts

  1. import * as trpc from '@trpc/server';
  2. // [...]
  3. interface Meta {
  4. hasAuth: boolean
  5. }
  6. export const appRouter = trpc
  7. .router<Context, Meta>()
  8. .middleware(async ({ meta, next, ctx }) => {
  9. // only check authorization if enabled
  10. if (meta?.hasAuth && !ctx.user) {
  11. throw new TRPCError({ code: "UNAUTHORIZED" });
  12. }
  13. return next()
  14. })
  15. .query('hello', {
  16. meta: {
  17. hasAuth: false
  18. },
  19. resolve({ ctx }) {
  20. return {
  21. greeting: `hello world`,
  22. };
  23. },
  24. })
  25. .query('protected-hello', {
  26. meta: {
  27. hasAuth: true
  28. },
  29. resolve({ ctx }) {
  30. return {
  31. greeting: `hello world`,
  32. };
  33. },
  34. });