T
tRPC

calling trpc endpoints from vanilla nextJs api routes

calling trpc endpoints from vanilla nextJs api routes

TTkDodo ๐Ÿ”ฎ10/19/2022
I'm struggling to find what's the best way to call a trpc endpoint directly from the server. Basically, I have a nextjs api endpoint where I want to call another endpoin that lives in trpc. would I need to create a trpcProxyClient? If so, would it have access to the context? oh, would I want something like this? https://github.com/trpc/trpc/issues/1724 appRouter.createCaller ?
Jjulius10/19/2022
yes appRouter.createCaller is what you want https://trpc.io/docs/v10/server-side-calls
TTkDodo ๐Ÿ”ฎ10/20/2022
Yep, this works. Thanks a lot โค๏ธ related follow-up question @julius : when I make a server-side call, and it errors (e.g. because of a zod validation error), I get a TRPCError. That has a code, which is a string and it says BAD_REQUEST. Is there a way to translate this to a proper status code like 400 in this case? Right now, all these errors are sent as 500 errors to the frontend and this is kinda suboptimal imo. Thanks ๐Ÿ™
Jjulius10/20/2022
you might be able to by using a non-public function that grabs the code for you. not sure why we aren't exporting it publically ๐Ÿค” should we @alex / KATT?
import { TRPCError } from '@trpc/server';
import { getHTTPStatusCodeFromError } from '@trpc/server/src/http/internals/getHTTPStatusCode';
import { type NextApiRequest, type NextApiResponse } from 'next';
import { appRouter } from './trpc/[trpc]';

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const caller = appRouter.createCaller({});

try {
const result = await caller.greeting({ name: 2 });
res.status(200).json(result);
} catch (e) {
console.error(e);
const code = e instanceof TRPCError ? getHTTPStatusCodeFromError(e) : 500;
res.status(code).json({ error: e });
}
};

export default handler;
import { TRPCError } from '@trpc/server';
import { getHTTPStatusCodeFromError } from '@trpc/server/src/http/internals/getHTTPStatusCode';
import { type NextApiRequest, type NextApiResponse } from 'next';
import { appRouter } from './trpc/[trpc]';

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const caller = appRouter.createCaller({});

try {
const result = await caller.greeting({ name: 2 });
res.status(200).json(result);
} catch (e) {
console.error(e);
const code = e instanceof TRPCError ? getHTTPStatusCodeFromError(e) : 500;
res.status(code).json({ error: e });
}
};

export default handler;
TTkDodo ๐Ÿ”ฎ10/20/2022
getHTTPStatusCodeFromError would be sweet, I have now made my own mapping according to this table: https://trpc.io/docs/v9/error-handling#error-codes I don't really understand: why does TrpcClientError have a statusCode property, but TrpcError does not?
AKAlex / KATT ๐Ÿฑ10/20/2022
happy to expose that!
Jjulius10/20/2022
I was thinking, maybe calls made from createCaller should automatically return the status code? Given that its a server call youโ€™d likely want the statuscode either way?
AKAlex / KATT ๐Ÿฑ10/20/2022
the trpc error that is returns will have the error code i don't want the status codes b/c that is a HTTP-standard and trpc isn't tied to http
AKAlex / KATT ๐Ÿฑ10/20/2022
I have this copy-pasted in an /api-fn helper so i would definitely use this functionality myself
TTkDodo ๐Ÿ”ฎ10/20/2022
Fine by me, let's expose the helper then?
TTkDodo ๐Ÿ”ฎ10/20/2022
Thx for merging โค๏ธ
Jjulius10/20/2022
Needs a publish too, shรถuldnt take too long. tRPC moving fast โšก๏ธโ˜บ๏ธ
TTkDodo ๐Ÿ”ฎ10/21/2022
And breaks nothing ๐Ÿ˜‰
UUUnknown User10/21/2022
Message Not Public
Sign In & Join Server To View
TLTrader Launchpad5/11/2023
HI! I am wanting to do the same thing...call a trpc route from within a nextjs public api endpoint. I am using a fresh t3-turbo-with-clerk project which has trpc in packages/api (@acme/api) here is my apps/nextjs/src/pages/api/post.ts file
import { NextApiRequest, NextApiResponse } from "next";
import { appRouter } from "@acme/api";
import { getHTTPStatusCodeFromError } from "@trpc/server/http";
import { TRPCError } from "@trpc/server";

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const caller = appRouter.createCaller({});

try {
const result = await caller.post.all();
res.status(200).json(result);
} catch (e) {
console.error(e);
const code = e instanceof TRPCError ? getHTTPStatusCodeFromError(e) : 500;
res.status(code).json({ error: e });
}
};

export default handler;
import { NextApiRequest, NextApiResponse } from "next";
import { appRouter } from "@acme/api";
import { getHTTPStatusCodeFromError } from "@trpc/server/http";
import { TRPCError } from "@trpc/server";

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const caller = appRouter.createCaller({});

try {
const result = await caller.post.all();
res.status(200).json(result);
} catch (e) {
console.error(e);
const code = e instanceof TRPCError ? getHTTPStatusCodeFromError(e) : 500;
res.status(code).json({ error: e });
}
};

export default handler;
i am getting a type error on
const caller = appRouter.createCaller({});
const caller = appRouter.createCaller({});
Argument of type '{}' is not assignable to parameter of type '{ auth: SignedInAuthObject | SignedOutAuthObject; prisma: PrismaClient<Prisma.PrismaClientOptions, never, Prisma.RejectOnNotFound | Prisma.RejectPerOperation | undefined>; }'.
Argument of type '{}' is not assignable to parameter of type '{ auth: SignedInAuthObject | SignedOutAuthObject; prisma: PrismaClient<Prisma.PrismaClientOptions, never, Prisma.RejectOnNotFound | Prisma.RejectPerOperation | undefined>; }'.
and when i load the page i get a json error:
{"error":{"code":"INTERNAL_SERVER_ERROR","name":"TRPCError"}}
{"error":{"code":"INTERNAL_SERVER_ERROR","name":"TRPCError"}}
Can someone assist me with the issue? I know I could use https://github.com/jlalmes/trpc-openapi to expose routes, I just wanted to get a basic example working first and then look into that. I am only exposing routes atm for testing purposes
Nnlucas5/11/2023
@Trader Launchpad this is an ancient thread, please could you start a new one? ๐Ÿ™‚

Looking for more? Join the community!

T
tRPC

calling trpc endpoints from vanilla nextJs api routes

Join Server
Recommended Posts
Mutation type issueI'm trying to mutate something like this with tRPC and Prisma ```const updateColumn = trpc.project.uCan I redirect the user from inside my router?I have a query protectedProcedure, which returns an object from my prisma planetscale db What's theInfer the type of ctx for a specific procedureLet's say I had a helper function that I wanted to pass the context to, I can't use the default ContCORS in standalone serverHi, I'm trying to get CORS working in standalone server. Attempted this solution but unfortunatelyQueries break when in production on Vercel; work on localhostThe query is called like this: ```javascript const { data } = api.useQuery(["user.!getCount"], { Can't get client to workHi, I can't get my client to work I'm using Next.js but I have also tried the React method from the Request context inside middleware?Hi, Is it possible to get the request context inside a middleware somehow? I'm trying to migrate data becomes never[] when destructuring with a fallback valueCurrently it doesn't seem possible to set a fallback value on a destructured `data` property, for exSyntaxError Unexpected token u in JSON at position 0 with mutationsI'm trying to use trpc client to await a mutation and just keep getting this error. everything worksLosing the type between the client and serverHello everyone, I am new to tRPC and the magic of types in typescript so I am looking for ideas as tMobile app with tRPCWhat's the suggested way of working with tRPC when it comes to mobile apps? How do you ensure that yHow to use trpc react hooks from an external data sourceHi, I have a monorepo, nextjs and keystone cms. The cms has trpc running, and I managed to get it coNextJS & Keystone CMS, issues when connecting both in a monorepoHello everyone, so I have a monorepo with NextJS and keystone cms, both are running trpc v10beta.15Best practices for implementing an offline applicationHey there! I'm building a full stack react-native app with Expo and a tRPC backend. I'd like for thisomehow when move typed function out of the router files, frontend infer type to be any ?this is inferred corrected since they are in the same file. ``` getX: t.procedure.query(() => { retBig companies that use tRPC?Some of my fellow colleagues were wondering if there are any big companies that use tRPC and how matMigrating to V10 from V9If someone has some ideas on what I might have screwed up when trying to bump tRPC for this public sAuthentication broke after bump to v10 from v9Anyone that has any suggestions on what might have caused this? I get the following error when tryiShow a spinner when any mutation is loading?Looking to show an activity spinner in the header of our application whenever a mutation is in flighSharing schemas between server and clientIn a typical nextJs setup, what is the idiomatic way to share zod schemas between frontend and backe