Skip to content

Add a way to access the ctx in the input parsers #1963

Open

Description

@jrmyio

I want to transform a slug or id before passing it to the resolve function. Currently you cannot access the router ctx inside the input function which has the downside that you have to do transformations inside the resolve function (if the transformation requires the ctx object).

For example: You have a user profile page (profile/{userId}) that uses trpc to get the profile data of a user. You pass this userId to trpc and want to convert the userId into a user object by utilizing some kind of UserRepository that is available on your ctx object. The UserRepository is an instance of a service, and cannot be accessed without the ctx object as you do not allow singletons.

By allowing the input to access the ctx we can utilize Zod's transform to convert a slug or id before it is passed to the resolve function. This way we can keep our resolve functions as clean as possible and keep any sort of input validation & transformation inside our input function.

According to the docs we can currently pass a Zod, Yup or superstruct object as input. I am not aware how this type is checked internally but if they all provide an object instead of a function we could allow a function as input with the ctx as an argument.

The end-result could look like:

.query('profile', {
  input: ({ ctx }) => 
      yup.object({
          user: yup.number().required(),
      })
      .transform((userId) => ctx.userRepository.findById(userId))
      .refine((user) => !!user, {
           message: 'User could not be found.',
       }),
      
  resolve({ input }) {
    return {
      username: input.user.username,
    };
  },
});

T-71

Activity

  1. jlalmes commented on Jun 7, 2022

    @jlalmes
    Contributor

    Hi @jrmyio.

    The input validation should only be used for parsing request input (e.g. check that userId is defined and is a number). Any data fetching or additional logic should be placed inside your resolve function, which has access to ctx.

    .query('profile', {
      input: z.object({ userId: z.number() }),
      resolve: async ({ ctx, input }) => {
        const user = await ctx.userRepository.findById(input.userId);
        
        if (!user) {
          throw new TRPCError({ 
            code: 'NOT_FOUND',
            message: 'User could not be found.'
          })
        }
        
        return {
          username: user.username
        }
      }
    )

    Hope this makes sense!

  2. jrmyio commented on Jun 7, 2022

    @jrmyio
    Author

    Imo, a user Id that doesn't exist in the database can be considered bad input just like a non-number userId is.

    Yes, in my example I am using z.transform() but there are other use-cases like using z.enum(). Let's say my trpc calls supports a locale parameter. The available locales can be accessed from my ctx. For example:
    ctx.locales = ['en', 'de', 'fr'];

    In order to validate the input I need to check the ctx.locales so I can use z.enum(ctx.locales). This should clearly be a use-case where you do not want this check to be inside your resolve function.

    So my questions would be:

    • Is there a reason why you think limiting the input to only check things that don't require context?
    • Are there technical limitations that prevent us from supporting ctx inside input?
    • Why would you want to clutter the resolve function with more input validation?
  3. jlalmes commented on Jun 7, 2022

    @jlalmes
    Contributor

    Hi @jrmyio.

    It looks like the use-case you mentioned above is best suited to the .middleware(...) utility. You can read more about it here: https://trpc.io/docs/middlewares#raw-input.

    Let me know what you think!

  4. jrmyio commented on Jun 7, 2022

    @jrmyio
    Author

    I suspect middleware not to be on a per-route level. For a parameter called locale I can see how that would always be the same as this could be a reserved parameter for your application.

    But let's say I want a messaging system. The message mutation would have a parameter called receiver, not user. There is no way you would catch all use-cases into a top level middleware nor would that be good practice.

    But this also highlights another reason why it's so useful to have smart ctx aware inputs. One could create a UserInput similar to my original-post and then reuse that in the message mutation for the receiver.

    I love the abstraction trpc is doing where there is clearly a separation between input and resolve, and I would love to keep it that way. I want my resolve functions not to deal with additional checks or transformations (note how many MVC frameworks also support input transformation before it hits the 'code' of the controller, example Symfony).

    Zod seems to have the support for transformations, the types even change when using .transform(). This is really powerful, especially for the use-cases mentioned above.

  5. reopened this on Jun 7, 2022
  6. KATT commented on Jun 8, 2022

    @KATT
    Member

    I am tentatively positive to this suggestion, but we should not consider it until we have an alpha of the next major.

    The next major's design would probably allow for creating a custom input parser that allowed this as the inputs will just be an abstraction on top of middlewares...

    queries: TQueries;
    mutations: TMutations;
    subscriptions: TSubscriptions;

  7. moved this to 🤔 Maybe / Nice to have in Roadmap and prioritieson Jun 8, 2022
  8. changed the title [-][Feature Request] Add a way to access the 'ctx' in the 'input' definition[/-] [+]Add a way to access the `ctx` in the `input` parsers[/+] on Jun 8, 2022
  9. KATT commented on Jul 10, 2022

    @KATT
    Member

    With the new major we could potentially add a new method called .inputCallback or similar that could take whatever input takes but as a callback instead. 🤔

  10. jrmyio commented on Jul 11, 2022

    @jrmyio
    Author

    With the new major we could potentially add a new method called .inputCallback or similar that could take whatever input takes but as a callback instead. 🤔

    Is the input expecting a function in its default behavior? If not, wouldn't it be possible to overload input by allowing a function as the first parameter?

  11. KATT commented on Jul 11, 2022

    @KATT
    Member

    @sachinraja - a penny for your thoughts; do you think there's a way to support both?

    We could change the default behavior of the parser callback from inputParser( input: unknown ) { } to input( opts: { rawInput: unknown; ctx: Context }) maybe?

  12. 27 remaining items

  13. ochicf commented on Jan 5, 2024

    @ochicf

    @lxia1220 +1 for option 2. Signature is consistent with resolver/middlewares, and also is the most flexible because it covers parser, parser creator and validator usages.

  14. KATT commented on Jan 6, 2024

    @KATT
    Member

    I'm fine with option 2 but it'll break a bunch of adapters that work thanks to ParserCustomValidatorEsque - you'll notice it when running pnpm vitest validators.

    IIRC, effect, runtimes, and others will break which isn't ideal, so it'd need a good story on how to work with those

  15. ironexdev commented on Aug 30, 2024

    @ironexdev

    I also have the use-case where I need to access context (specifically locale) in Input definition. This is my solution since experimental_standaloneMiddleware was deprecated.

    src/trpc/routers/verification-tokens.ts

    const vtCreateSchema = (locale: LocaleType) =>
      z.object({
        email: z.string().email(t_invalidEmail(locale)),
      })
    
    export const verificationTokensRouter = createTRPCRouter({
      create: publicProcedure
        .input(
          (input: unknown) => input as z.infer<ReturnType<typeof vtCreateSchema>>,
        )
        .use(ctxInput(({ locale }) => vtCreateSchema(locale)))
        .mutation(async ({ ctx }) => {
        ...
    

    src/trpc/trpc.ts

    • needs to have "t" (const t = initTRPC...) available
    export const ctxInput = <T extends z.ZodType>(
      getZodType: (ctx: ContextType) => T,
    ) =>
      t.middleware(async ({ ctx, input, next }) => {
        try {
          const ctxInput = (await getZodType(ctx).parseAsync(input)) as z.infer<T>
          return next({
            ctx: {
              ...ctx,
              ctxInput,
            },
          })
        } catch (cause) {
          if (cause instanceof TRPCError) {
            throw cause
          } else {
            throw new TRPCError({
              code: "BAD_REQUEST",
              cause,
            })
          }
        }
      })
    
  16. L-Mario564 commented on Oct 24, 2024

    @L-Mario564

    What's the current status of this issue? I've encountered a use-case in one of my projects where this feature would be great. I use the mutation/query callback to do additional validation with runtime values but it would be great to have this feature to separate validation logic from what the procedure is actually supposed to do.

    I may add that I'm also down to contribute with a PR if necessary.

  17. michaelbrusegard commented on Jan 14, 2025

    @michaelbrusegard

    I also would like something like this to access the current locale from the context for localised validation error messages

  18. michaelbrusegard commented on Jan 14, 2025

    @michaelbrusegard

    So one work around for translations, maybe not the cleanest solution. You can apply the translation function in the errorformatter, and instead just return the translation keys as error messages in the validation methods. Hopefully this helps if anybody has the same situation

  19. KATT commented on Jan 26, 2025

    @KATT
    Member

    So one work around for translations, maybe not the cleanest solution. You can apply the translation function in the errorformatter, and instead just return the translation keys as error messages in the validation methods. Hopefully this helps if anybody has the same situation

    @michaelbrusegard you could likely use async local storage for this, see this test for inspo

  20. michaelbrusegard commented on Jan 26, 2025

    @michaelbrusegard

    So one work around for translations, maybe not the cleanest solution. You can apply the translation function in the errorformatter, and instead just return the translation keys as error messages in the validation methods. Hopefully this helps if anybody has the same situation

    @michaelbrusegard you could likely use async local storage for this, see this test for inspo

    That seems like a much cleaner solution to what I am currently doing. Thank you!

  21. KATT commented on Jan 26, 2025

    @KATT
    Member

    But thinking about it - now that there's a standard schema, I think we can drop the use of callback functions and add support for this for real 👀

    Looking at doing it now

  22. michaelbrusegard commented on Jan 26, 2025

    @michaelbrusegard

    But thinking about it - now that there's a standard schema, I think we can drop the use of callback functions and add support for this for real 👀

    Looking at doing it now

    That would be amazing! How long would you suspect it to take to implement? I am considering if it is worth implementing it with asyncLocalStorage in the meanwhile. Thank you for this amazing RPC solution!

  23. KATT commented on Jan 26, 2025

    @KATT
    Member

    That would be amazing! How long would you suspect it to take to implement? I am considering if it is worth implementing it with asyncLocalStorage in the meanwhile. Thank you for this amazing RPC solution!

    Pulled the plug on it, it was a bit too involved, might pick it up later or when/if people sponsor this issue 🙃

  24. michaelbrusegard commented on Jan 26, 2025

    @michaelbrusegard

    That is understandable, thanks for the heads up!

  25. KATT commented on Nov 2, 2026

    @KATT
    Member

    🤖 In v12, .input() also takes a callback that gets ctx and returns the schema, e.g. t.procedure.input(({ ctx }) => z.object({ locale: z.enum(ctx.locales) })), so context-aware validation and transforms run in the input step, and invalid input is the procedure's typed BAD_REQUEST. The callback runs per call, so build what you can outside it. https://github.com/trpc/trpc/blob/v12/next/.agent-docs/decisions/validation.md. v12 isn't released yet and there's no ETA.

  26. added
    next-major/definite
    and removed
    next-major/maybe
    on Nov 2, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    next-major/definite🙋‍♂️ help wanted

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions