Skip to content

feat(server): extending .output()s #5787

Open

Description

@martijnarts

Provide environment information

  System:
    OS: macOS 14.5
    CPU: (10) arm64 Apple M1 Max
    Memory: 56.36 MB / 32.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 20.11.1 - ~/.nvm/versions/node/v20.11.1/bin/node
    npm: 10.2.4 - ~/.nvm/versions/node/v20.11.1/bin/npm
    pnpm: 8.15.5 - ~/.nvm/versions/node/v20.11.1/bin/pnpm
    Watchman: 2024.05.06.00 - /opt/homebrew/bin/watchman
  Browsers:
    Safari: 17.5
  npmPackages:
    react: ^18.3.1 => 18.3.1
    typescript: 5.1.6 => 5.1.6

Describe the bug

I have a plugin that looks sort of like this:

const OutputData = z
  .object({
    some: z.string(),
  });

const pluginT = initTRPC.create();

const pluginProc = pluginT.procedure.output(OutputData).use(async (opts) =>
  opts.next({
    ctx: {
      additional: "context",
    },
  }),
);

Which I then use like this:

protectedUserProcedure
  .unstable_concat(pluginProc)
  .input(z.object({
    some: z.number(),
  }))
  .output(z.object({
    regular: z.literal("output"),
  }))
  .query(...)

But this throws:

 ⨯ Error: Duplicate key output
    at mergeWithoutOverrides (webpack-internal:///(api)/../../node_modules/.pnpm/@[email protected]/node_modules/@trpc/server/dist/unstable-core-do-not-import/utils.mjs:19:23)
    at createNewBuilder (webpack-internal:///(api)/../../node_modules/.pnpm/@[email protected]/node_modules/@trpc/server/dist/unstable-core-do-not-import/procedureBuilder.mjs:18:77)
    at Object.output (webpack-internal:///(api)/../../node_modules/.pnpm/@[email protected]/node_modules/@trpc/server/dist/unstable-core-do-not-import/procedureBuilder.mjs:55:20)
    at eval (webpack-internal:///(api)/../../packages/backend/src/trpc/routes/myRoute.ts:60:9)

Link to reproduction

https://stackblitz.com/edit/github-svr83h

To reproduce

The starter repo is broken for me, but it should do the trick.

Additional information

No response

👨‍👧‍👦 Contributing

  • 🙋‍♂️ Yes, I'd be down to file a PR fixing this bug!

Activity

  1. changed the title [-]bug: Using `.output` in both procedures of an `unstabale_concat` causes `Error: Duplicate key output`[/-] [+]bug: Using `.output` in both procedures of an `unstable_concat` causes `Error: Duplicate key output`[/+] on Jun 12, 2024
  2. KATT commented on Jun 14, 2024

    @KATT
    Member

    We don't support extending outputs the way you can extend inputs, so this works as expected, but you're free to implement it.

    To help you if you wanna do this

    • Add tests in https://github.com/trpc/trpc/blob/next/packages/tests/server/outputParser.test.ts
    • Run tests with pnpm test-watch outputParser in the root folder
    • The code for this functionality for input parsers is in:
      • Ensuring that the input is ok to extend on a type level:
        input<$Parser extends Parser>(
        schema: TInputOut extends UnsetMarker
        ? $Parser
        : inferParser<$Parser>['out'] extends Record<string, unknown> | undefined
        ? TInputOut extends Record<string, unknown> | undefined
        ? undefined extends inferParser<$Parser>['out'] // if current is optional the previous must be too
        ? undefined extends TInputOut
        ? $Parser
        : TypeError<'Cannot chain an optional parser to a required parser'>
        : $Parser
        : TypeError<'All input parsers did not resolve to an object'>
        : TypeError<'All input parsers did not resolve to an object'>,
      • input is an array on the builder object which is added like this:
        input(input) {
        const parser = getParseFn(input as Parser);
        return createNewBuilder(_def, {
        inputs: [input as Parser],
        middlewares: [createInputMiddleware(parser)],
        });
        },
      • Combining result from each parser:
        export function createInputMiddleware<TInput>(parse: ParseFn<TInput>) {
        const inputMiddleware: AnyMiddlewareFunction =
        async function inputValidatorMiddleware(opts) {
        let parsedInput: ReturnType<typeof parse>;
        const rawInput = await opts.getRawInput();
        try {
        parsedInput = await parse(rawInput);
        } catch (cause) {
        throw new TRPCError({
        code: 'BAD_REQUEST',
        cause,
        });
        }
        // Multiple input parsers
        const combinedInput =
        isObject(opts.input) && isObject(parsedInput)
        ? {
        ...opts.input,
        ...parsedInput,
        }
        : parsedInput;
        return opts.next({ input: combinedInput });
        };
        inputMiddleware._type = 'input';
        return inputMiddleware;
        }

    If you do this, make sure to consolidate the code from input and output parsers so we don't have 2 almost-identical things.

  3. added
    ✅ accepted-PRs-welcome
    and removed on Jun 14, 2024
  4. changed the title [-]bug: Using `.output` in both procedures of an `unstable_concat` causes `Error: Duplicate key output`[/-] [+]feat(server): extending `.output()`s[/+] on Jun 14, 2024
  5. KATT commented on Jun 14, 2024

    @KATT
    Member

    Why I never implemented this is because I am not sure outputs should be extendable, so please specify the behavior in a PR with a failing test first.

  6. martijnarts commented on Jun 14, 2024

    @martijnarts
    Author

    Just to be sure, is there an argument against making outputs extendable?

    Basically the idea here is to have a middleware that adds a required property to the output, and some context required to compute that.

  7. KATT commented on Jun 14, 2024

    @KATT
    Member

    I'm fine with it - what you're describing would work exactly like our extendable input parsers work AFAICT

  8. KATT commented on Jun 14, 2024

    @KATT
    Member

    I realize now - the middleware for outputs would look a bit different since they're in the other direction, but I think you can figure that out

  9. KATT commented on Nov 3, 2026

    @KATT
    Member

    🤖 Still one output per procedure, in v11 and in v12, where a second .output() (including a plugin's) becomes a type error instead of the runtime "Duplicate key output". Merging outputs, so a plugin can require fields in every result, is still an open design question. A second .output() could mean either narrowing or extending the first, which is why merging is still undecided. Until then, a workaround: build the plugin without .output(), export its schema, and extend it in each procedure, e.g. .output(OutputData.extend({ regular: z.literal('output') })). v12 isn't released yet and there's no ETA.

  10. jiangyuer018 commented on Nov 4, 2026

    @jiangyuer018
    Contributor

    I'd like to take this issue. I will first add a failing output-parser extension test, then implement output schema composition alongside the existing input-parser path while preserving the current single-output behavior and type safety. I'll run the focused outputParser tests and the relevant package checks before opening a PR.

  11. jiangyuer018 commented on Nov 4, 2026

    @jiangyuer018
    Contributor

    Thanks for the detailed review. I understand why #7882 was closed, and I will not revive its runtime parser-composition approach.

    Before any further runtime change, I propose keeping one output parser per procedure. A reusable plugin can export its output schema separately and contribute middleware without calling .output(). The consuming procedure then composes that schema with its own fields using the schema library's native API and attaches one final .output() parser. This preserves the existing _def.output contract, parser ordering, and each validator's strict/strip/loose behavior without defining cross-parser key-conflict semantics.

    I plan to add a documentation example for this existing workaround under the .concat() plugin guide. The PR will be documentation-only and will not close this design issue. If the project wants runtime output composition instead, the merge-versus-narrowing and parser semantics should be agreed here before another implementation is proposed.

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

    @trpc/server✅ accepted-PRs-welcome

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions