Use trpc on nextJS api route?

Rrovrav9/12/2023
Is there a way that you can use trpc on a nextJS api route?
Rrovrav9/13/2023
Wow, that's amazing Does this only work for the app router and not the pages router?
import { TRPCError } from '@trpc/server';
import { getHTTPStatusCodeFromError } from '@trpc/server/http';
import { appRouter } from '~/server/routers/_app';
import type { NextApiRequest, NextApiResponse } from 'next';
 
type ResponseData = {
data?: {
postTitle: string;
};
error?: {
message: string;
};
};
 
export default async (
req: NextApiRequest,
res: NextApiResponse<ResponseData>,
) => {
/** We want to simulate an error, so we pick a post ID that does not exist in the database. */
const postId = `this-id-does-not-exist-${Math.random()}`;
 
const caller = appRouter.createCaller({});
 
try {
// the server-side call
const postResult = await caller.post.byId({ id: postId });
 
res.status(200).json({ data: { postTitle: postResult.title } });
} catch (cause) {
// If this a tRPC error, we can extract additional information.
if (cause instanceof TRPCError) {
// We can get the specific HTTP status code coming from tRPC (e.g. 404 for `NOT_FOUND`).
const httpStatusCode = getHTTPStatusCodeFromError(cause);
 
res.status(httpStatusCode).json({ error: { message: cause.message } });
return;
}
 
// This is not a tRPC error, so we don't have specific information.
res.status(500).json({
error: { message: `Error while accessing post with ID ${postId}` },
});
}
};
import { TRPCError } from '@trpc/server';
import { getHTTPStatusCodeFromError } from '@trpc/server/http';
import { appRouter } from '~/server/routers/_app';
import type { NextApiRequest, NextApiResponse } from 'next';
 
type ResponseData = {
data?: {
postTitle: string;
};
error?: {
message: string;
};
};
 
export default async (
req: NextApiRequest,
res: NextApiResponse<ResponseData>,
) => {
/** We want to simulate an error, so we pick a post ID that does not exist in the database. */
const postId = `this-id-does-not-exist-${Math.random()}`;
 
const caller = appRouter.createCaller({});
 
try {
// the server-side call
const postResult = await caller.post.byId({ id: postId });
 
res.status(200).json({ data: { postTitle: postResult.title } });
} catch (cause) {
// If this a tRPC error, we can extract additional information.
if (cause instanceof TRPCError) {
// We can get the specific HTTP status code coming from tRPC (e.g. 404 for `NOT_FOUND`).
const httpStatusCode = getHTTPStatusCodeFromError(cause);
 
res.status(httpStatusCode).json({ error: { message: cause.message } });
return;
}
 
// This is not a tRPC error, so we don't have specific information.
res.status(500).json({
error: { message: `Error while accessing post with ID ${postId}` },
});
}
};
Hence the appRouter import
SSturlen9/13/2023
tRPC works fine on pages. the appRouter being imported here is a tRPC router, which is where you define your tRPC routes

Looking for more? Join the community!

Want results from more Discord servers?
Add your server
Recommended Posts
how to remove all current data from planetscale main branch?I made a breaking change and need to reset the main branch in order to deploy it, how to do it?Modern Desktop App FrameworkHey guys, I haven't made a desktop app in a really long time, and I was curious what your guys opinishadcn/ui DropdownMenu component not working with AstroI followed exactly the instructions from [this page](https://ui.shadcn.com/docs/installation/astro) How to validate the media url returned from clients when using uploadthing?Client uploads file(s), receives media url(s), sends them to the server , server stores them in dataGatsby Could Shutdown, what are best alternative.Hey everyone, as you probably know Gatsby Cloud is shutting down. At our company we have a couple oftrouble with Vercel deploy (no errors)### Summary Cant figure out why this is happening. The build is succeeding on local. then deploymenBun window tsconfigI have this error when using bun-types in the tsconfig.json as in https://bun.sh/docs/installation#tquestion about spread operator in reactCan someone explain why I need to use the spread (...) operator when giving each post to PostCard, bpaddle not working in next 13Hello everyone, I'm trying to add paddle to my next 13 app project but I'm getting weird errors, soEnum access questionIf I have ```typescript export enum Options { 'bool' = 'Boolean', 'num' = 'Number' 'str' = 'Clerk middleware public routesI have an ecommerce website with the / route being public, and I'm fetching categories from a publicNextjs middleware being ignoredHey, this is driving me crazy, using next, why I'm not being redirected to "/pending" by the middlewError: Invariant: headers() expects to have requestAsyncStorage, none available.Created a fresh create-t3-turbo and added my .env variables but getting the following error. - erT3 Tutorial - clerk errors out on a different machine?Strange.. So, I followed Theo's t3 tutorial, everything worked fine last Friday. Today I cloned the