vasek
vasek

Reputation: 106

Don't get cookies in trpc context

So i have trpc set up with next.js and im trying to ssr where i fetch user before page load using trpc.useQuery hook, but i don't get the cookie with JWT token in trpc context

i have this code in [username].tsx page:

const UserPage: NextPage = () => {
  const router = useRouter();
  const username = router.query.username as string;

  const user = trpc.useQuery([
    "user.by-username",
    {
      username,
    },
  ]);

  return <Text>{user?.data?.id}</Text>;
};

export default UserPage;

and this code in trpc context, where i can't console.log the cookies:

export const createContext = (opts?: trpcNext.CreateNextContextOptions) => {
  const req = opts?.req;
  const res = opts?.res;

  console.log(req?.cookies) // i don't get cookies here

  const user = jwt.verify(req?.cookies.token as string, process.env.JWT_SECRET as string) as User

  return {
    req,
    res,
    prisma,
    user
  };
};

type Context = trpc.inferAsyncReturnType<typeof createContext>;

export const createRouter = () => trpc.router<Context>();

Upvotes: 5

Views: 6594

Answers (2)

Alex
Alex

Reputation: 1741

I think what you're missing is to forward the headers from the browser.

This is the magic you're looking for: https://github.com/trpc/examples-next-prisma-starter-websockets/blob/daf54ca6576f3e290aa4f36dc7d0ff1eb718b716/src/pages/_app.tsx#L79

We have an open issue to improve this :) https://github.com/trpc/trpc/issues/1811

Upvotes: 2

Jesse
Jesse

Reputation: 2198

Let me copy over the answer from github for progeny.

It's an SSR thing. Headers aren't copied over by default so you have to include the following snippet:

export default withTRPC<AppRouter>({
  // @typescript-eslint/no-unused-vars
  config({ ctx }) {
    /**
     * If you want to use SSR, you need to
     * use the server's full URL
     * @link https://trpc.io/docs/ssr
     */
    return {
      headers() {
        return {
          cookie: ctx?.req?.headers.cookie,
        };
      },
    }
  }
})

There is a PR open to improve the documentation on this.

Upvotes: 3

Related Questions