Next.js Discord

Discord Forum

trpc route handler

Answered
astro posted this in #help-forum
Open in Discord
im trying to create an api using trpc, but the route doesnt seem to return anything

trpc.ts
import { initTRPC } from "@trpc/server";

const t = initTRPC.create();

export const router = t.router;
export const publicProcedure = t.procedure;


index.ts
import { publicProcedure, router } from "./trpc";

export const appRouter = router({
  getTodos: publicProcedure.query(async () => {
    return [10, 20, 30];
  }),
});

export type AppRouter = typeof appRouter;


/api/trpc/[trpc]/route.ts
import { fetchRequestHandler } from "@trpc/server/adapters/fetch";
import { appRouter } from "@/server";

function handler(req: Request) {
  fetchRequestHandler({
    endpoint: "/api/trpc",
    req,
    router: appRouter,
    createContext: () => ({}),
  });
}

export { handler as GET, handler as POST };
Answered by joulev
try
import { fetchRequestHandler } from "@trpc/server/adapters/fetch";
import { appRouter } from "@/server";

function handler(req: Request) {
  return fetchRequestHandler({
    endpoint: "/api/trpc",
    req,
    router: appRouter,
    createContext: () => ({}),
  });
}

export { handler as GET, handler as POST };
View full answer

26 Replies

Cape May Warbler
Facing the same issue, have you resolved this?
Cape May Warbler
"next": "14.3.0-canary.28",
"@trpc/next": "^10.43.1",
"@trpc/react-query": "^10.43.1",
"@trpc/server": "^10.43.1",
Asian black bear
its a tricky one
Answer
Cape May Warbler
Sadly it's literally what I have
Previously when I was facing this issue I had to delete node modules and reinstall but now it doesn't work
Cape May Warbler
Oh, I forgot to return the fetchRequestHandler, my bad
Thanks a lot
it's like
function add(a, b) {
  return a + b;
}

function get1Plus1() {
  add(1, 1); // doesn't work
  return add(1, 1); // works
}
well... im the dude who wrote the error "No response is returned from route handler" so i know full well why it happens lol
:hugkon:
keep up the good work
ur oss work is inspiring
thank you!