alexA
tRPC2y ago
2 replies
alex

nodeHTTPHandler with Nitro

I'm trying to setup trpc with nitro.unjs.io using the
node-http
adapter.

import { nodeHTTPRequestHandler } from "@trpc/server/adapters/node-http";
import { appRouter } from "~/lib/trpc/router";

export default defineEventHandler(async (event) => {
    console.log('trpc route handler');
    const res = await nodeHTTPRequestHandler({
        req: event.node.req,
        res: event.node.res,
        router: appRouter,
        path: '/api/trpc',
    });
    console.log(res) // returns undefined
});


Frontend setup:
    const [queryClient] = useState(() => new QueryClient());
    const [trpcClient] = useState(() => trpc.createClient({
        links: [
            httpBatchLink({
                url: 'http://localhost:3000/api/trpc',
            }),
        ],
    }));


const { data, isLoading } = trpc.formList.useQuery();


There are no TS errors anywhere so the router setup should be correct.

However the nodeHTTPRequestHandler function always returns
undefined
.

I've also tried the
trpc-nuxt
package because apparently that's supposed to work with Nitro but I couldn't get it to work because I'm using trpc v11.
Solution
Nvm, it seems to work like this.
Have to return the correct response of course (which revealed another error with the path).
export default defineEventHandler(async (event) => {
    console.log('trpc route handler');
    const res = await nodeHTTPRequestHandler({
        req: event.node.req,
        res: event.node.res,
        router: appRouter,
        path: getRequestURL(event).pathname.replace('/api/trpc/', ''),
    });
    return event.node.res;
});

No need for
trpc-nuxt
:POGGIES:
Was this page helpful?