不要在 trpc 上下文中获取 cookie

vas*_*sek 5 cookies typescript next.js trpc.io

所以我用 next.js 设置了 trpc,我尝试在页面加载之前使用 trpc.useQuery 钩子获取用户的 ssr,但我没有在 trpc 上下文中获取带有 JWT 令牌的 cookie

我在 [用户名].tsx 页面中有此代码:

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;
Run Code Online (Sandbox Code Playgroud)

这段代码位于 trpc 上下文中,我无法在其中 console.log cookie:

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>();
Run Code Online (Sandbox Code Playgroud)

Jes*_*sse 3

让我复制github 上的答案给后代。

这是SSR的事情。默认情况下不会复制标头,因此您必须包含以下代码片段:

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,
        };
      },
    }
  }
})
Run Code Online (Sandbox Code Playgroud)

有一个PR 正在开放以改进这方面的文档。