Tamás SoósT
tRPC3y ago
8 replies
Tamás Soós

tRPC over WebSocket with Next.js and NextAuth

Hi. I'm trying to set up Next 13 with tRPC over a WebSocket and NextAuth. I got it mostly working with:
// route.ts
import { fetchRequestHandler } from '@trpc/server/adapters/fetch';
import { createContext } from '@/server/context';
import { appRouter } from '@/server/routers/app';

const handler = (req: Request) =>
  fetchRequestHandler({
    endpoint: '/api/trpc',
    req,
    router: appRouter,
    createContext,
    batching: {
      enabled: true,
    },
  });

export { handler as GET, handler as POST };


// context.ts
import * as trpc from '@trpc/server';
import * as trpcNext from '@trpc/server/adapters/fetch';
import { NodeHTTPCreateContextFnOptions } from '@trpc/server/adapters/node-http';
import { IncomingMessage } from 'node:http';
import ws from 'ws';
import { getSession } from 'next-auth/react';

export async function createContext(
  opts:
    | NodeHTTPCreateContextFnOptions<IncomingMessage, ws>
    | trpcNext.FetchCreateContextFnOptions
) {
  const req = opts?.req;

  const session = req && (await getSession({ req }));

  return {
    req,
    session,
  };
}

export type Context = trpc.inferAsyncReturnType<typeof createContext>;
Solution
My guess is that next-auth tries to use
import { headers } from 'next/headers';

but when you are not using Next, in the case of your ws server that import does nothing. You might want to take a look at examples-next-prisma-websocket-starter, if you are looking for a method to implement tRPC + Next + Next Auth + Websockets.

I opted to use LuciaJS, because it's a little bit more versatile and less restrictive, but it's a little bit more complex and requires more boilerplate code. https://github.com/BeBoRE/ei-noah-bot
GitHub
De officiële Discord Bot voor de Sweaty GG Chat. Contribute to BeBoRE/ei-noah-bot development by creating an account on GitHub.
GitHub - BeBoRE/ei-noah-bot: De officiële Discord Bot voor de Sweat...
Was this page helpful?