【问题标题】:Don't get cookies in trpc contextDon\'t get cookies in trpc context
【发布时间】:2022-12-27 00:57:06
【问题描述】:

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>();

【问题讨论】:

  • Where is createContext being called from?

标签: typescript cookies next.js trpc.io


【解决方案1】:

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 sn-p:

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.

【讨论】:

    【解决方案2】:

    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

    【讨论】:

      【解决方案3】:

      I have the same issue. I've included the following piece of code in createTRPCNext / config, as recommmanded in previous answers. It does not work and does not even seem to get called :

            headers: () => {
              if (ctx?.req) {
                // on ssr, forward client's headers to the server
                return {
                  ...ctx.req.headers,
                  'x-ssr': '1',
                };
              }
      

      Does anyone have an idea about this ?

      【讨论】:

        猜你喜欢
        • 2022-12-02
        • 2022-12-02
        • 2022-12-02
        • 2014-12-03
        • 1970-01-01
        • 2022-08-16
        • 2022-12-02
        • 2022-12-02
        • 1970-01-01
        相关资源
        最近更新 更多