sumatokenS
tRPC3y ago
5 replies
sumatoken

tRPC Express server with Next.js

As much as I hate this, I am required to use Express for back-end and Next.js for front-end.

I have two Node.js projects, an Express server and a Next.js client.

I did a minimal setup on the back-end side using the Express adapter and it is working fine when i try to hit an endpoint on the browser.

index.ts:
const t = initTRPC.context<Context>().create();

export const appRouter = t.router({
  hello: t.procedure.query((opts) => {
    return { message: "Hello World", ctx: opts.ctx.ex.message };
  }),
});

export type AppRouter = typeof appRouter;

app.use(
  "/trpc",
  trpcExpress.createExpressMiddleware({
    router: appRouter,
    createContext,
  })
);


Now when I try to use the trpc client on Next.js I get a  TypeError.

What I did once I created the Next.js client, is running npm link to be able to import my appRouter.

Here is my utils/trpc.ts:

```js
import { httpBatchLink } from "@trpc/client";
import { createTRPCNext } from "@trpc/next";
import { appRouter } from "trpc-express";
function getBaseUrl() {
  if (typeof window !== "undefined") return "";

  if (process.env.VERCEL_URL) return 
https://${process.env.VERCEL_URL}`;

if (process.env.RENDER_INTERNAL_HOSTNAME)
return
http://${process.env.RENDER_INTERNAL_HOSTNAME}:${process.env.PORT}
;

return
http://localhost:${process.env.PORT ?? 3000}
;
}

export const trpc = createTRPCNext<typeof appRouter>({
config(opts) {
return {
links: [
httpBatchLink({
url:
${getBaseUrl()}/api/trpc
,

async headers() {
return {};
},
}),
],
};
},

ssr: false,
});
````

If any one can provide me with insight regarding this issue, I'd appreciate it.
Screenshot_2023-09-14_at_16.15.07.png
Was this page helpful?