代码之家  ›  专栏  ›  技术社区  ›  j roc

api文件夹内的Clerk getAuth()helper返回:{userId:null}

  •  1
  • j roc  · 技术社区  · 2 年前

    完全被困在这里。。

    与职员一起工作,我想使用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
    

    当我看到浏览器中打印的userId时,它似乎正在工作:

    {"userId":"user_2Ze2xqQyKbZbsXaZi7cv1sXLf2S"}
    

    但是,当我尝试在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)(.*)'],
    };
    

    有人能发现问题吗?整天都被困在这个问题上。谢谢你的关注

    1 回复  |  直到 2 年前
        1
  •  1
  •   Phil    2 年前

    问题是从发出的请求 getServerSideProps() 将丢失任何标识头/cookie等。

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

    简单使用 getAuth() 在内部 getServerSideProps

    export function getServerSideProps({ req }) {
      const { userId } = getAuth(req);
    
      return {
        props: {
          properties: { userId },
        },
      };
    }
    
    推荐文章