You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Clerk getAuth()时getServerSideProps调用API返回userId:null

问题:Clerk getAuth()在getServerSideProps调用API时返回null

直接通过浏览器访问/api/example端点能正常返回用户userId,但在pages/profile.tsx的getServerSideProps中调用该API时,却返回{ userId: null }。

相关代码

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);
  return res.status(200).json({ userId: userId });
}

pages/profile.tsx

export async function getServerSideProps() {
    const res = await fetch(`http://localhost:3000/api/example`);
    const data = await res.json()

    console.log(data) // 输出: { 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. 浏览器直接访问API时,请求会自动携带Clerk的认证Cookie,getAuth(req)能从Cookie中解析出用户信息,因此返回正常的userId。
  2. getServerSideProps是在服务器端执行的,其中的fetch请求默认不会携带浏览器端的认证Cookie,导致API端点接收到的请求没有用户认证信息,getAuth(req)只能返回null。

解决方案

方案一:直接在getServerSideProps中使用getAuth(推荐)

既然getServerSideProps本身就在服务器端运行,无需绕路调用API,直接导入getAuth从请求上下文获取userId即可:

// pages/profile.tsx
import { getAuth } from "@clerk/nextjs/server";
import type { GetServerSidePropsContext } from "next";

export async function getServerSideProps(context: GetServerSidePropsContext) {
  const { userId } = getAuth(context.req);
  
  return {
    props: {
      properties: { userId },
    },
  };
}

方案二:若必须调用API,手动传递Cookie

如果业务逻辑需要通过API获取数据,在fetch时把当前请求的Cookie传递给API端点:

// pages/profile.tsx
import type { GetServerSidePropsContext } from "next";

export async function getServerSideProps(context: GetServerSidePropsContext) {
  const res = await fetch(`http://localhost:3000/api/example`, {
    headers: {
      Cookie: context.req.headers.cookie || "",
    },
  });
  const data = await res.json();

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

内容的提问来源于stack exchange,提问作者j roc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 16:18:28