在这里完全被难住了.

我正在与办事员一起工作,我希望使用getAuth()帮助器访问当前用户的userid.

此处的文档数量:https://clerk.com/docs/references/nextjs/get-auth

pages/api/example.ts

import { getAuth } from "@clerk/nextjs/server";
import type { NextApiRequest, NextApiResponse } from "next";
 
export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const { userId } = getAuth(req);
  // Load any data your application needs for the API route
  return res.status(200).json({ userId: userId });

现在,当我在浏览器中访问此终结点时:

http://localhost:3000/api/example

它似乎起作用了,因为我在浏览器中看到了打印的用户ID:

{"userId":"user_2Ze2xqQyKbZbsXaZi7cv1sXLf2S"}

但是,当我try 在getServerSideProps函数中调用此API端点时,我收到:{ userId: null }

pages/profile.tsx

export async function getServerSideProps() {

    const res = await fetch(`http://localhost:3000/api/example`);
    const data = await res.json()

    console.log(data) // this logs: { userId: null } 

    return {
        props: {
            properties: data,
        },
    };
}

我的中间件文件:

middleware.ts

import { authMiddleware } from "@clerk/nextjs";
 
export default authMiddleware({
  publicRoutes: ["/api/example", "/profile"],
});
 
export const config = {
  matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)'],
};

有人能找出问题所在吗?我一整天都被困在这上面了.感谢您的关注

推荐答案

问题是,从getServerSideProps()发出的请求将缺少任何标识标头/cookie/等.

由于API路由处理程序和getServerSideProps()都在相同的服务器端上下文中运行,因此您不需要发出额外的内部请求.

只需在getServerSideProps内使用getAuth()

export function getServerSideProps({ req }) {
  const { userId } = getAuth(req);

  return {
    props: {
      properties: { userId },
    },
  };
}

Typescript相关问答推荐

Typescript:将内部函数参数推断为子对象键的类型

React Hook中基于动态收件箱定义和断言回报类型

如何防止TypeScript允许重新分配NTFS?

泛型函数类型验证

角形标题大小写所有单词除外

HttpClient中的文本响应类型选项使用什么编码?''

泛型函数即使没有提供类型

为什么TypeScript假设文档对象始终可用?

为什么在回调函数的参数中不使用类型保护?

如何使我的函数专门针对联合标记?

类型TTextKey不能用于索引类型 ;TOption

以Angular 执行其他组件的函数

正交摄影机正在将渲染的场景切成两半

对有效枚举值的常量字符串进行常规判断

编剧- Select 下拉框

使用强制转换编写打字函数的惯用方法

如何使用警告实现`RecursiveReadonly<;T>;`,如果`T`是原语,则返回`T`而不是`RecursiveReadonly<;T>;`

我可以使用对象属性的名称作为对象中的字符串值吗?

如何向我的自定义样式组件声明 custom.d.ts ?

使用嵌套属性和动态执行时,Typescript 给出交集而不是并集