LaunchThat.AppL
tRPC3y ago
27 replies
LaunchThat.App

[HOW TO?] Call trpc endpoints from vanilla nextJs api routes

Spinoff from an og thread here:
https://discordapp.com/channels/867764511159091230/1032301198990135347

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;
Was this page helpful?