welpW
tRPC3y ago
4 replies
welp

Initial websockets getToken() returns null: next-auth + websockets :)

Hello!

So the way I am trying to authenticate websockets is like this:

import { getToken } from "next-auth/jwt";

type Incoming = IncomingMessage & {
  cookies: Partial<{ [key: string]: string }>;
};

export const createTRPCContext = async (
  opts:
    | CreateNextContextOptions
    | NodeHTTPCreateContextFnOptions<IncomingMessage, ws>
) => {
  const { req } = opts;
  const token = await getToken({ req: req as Incoming });

  if (token) {
    return { session: { user: token } };
  }

  return { session: null };
};


And it works except for the initial requests. I wouldn't mind this (maybe I would since needless errors), but my problem is trying to use subscriptions: it just will prompt an error on the initial request and I can't think of a way to retry (retrying works for everything else). I would like to solve this initial null JWT token request problem as that would make everything work very nicely but I wouldn't mind making the subscriptions work either.

The way I am subscribing in my react component:

api.messages.whoIsTyping.useSubscription(
    {
      slug,
    },
    {
      onData(data) {
        setCurrentlyTyping(data);
      },
      onError(err) {
        console.error("Subscription error:", err);
      },
    }
  );


I would really appreciate some commentary/insight! Thank you for your time.
Was this page helpful?