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

Next.js搭配AWS Amplify实现SSR访问公开数据为何要求存在当前用户

问题根本原因

你遇到的no current user报错是因为AWS Amplify默认使用Amazon Cognito用户池作为API请求的认证模式,调用时会优先从当前上下文获取已登录用户的凭证,哪怕你数据配置了公开可读,只要没有显式指定公开的认证方式,Amplify还是会校验用户身份,未登录状态下就会抛出该错误。

解决步骤

步骤1:确认GraphQL模型权限配置

首先检查你的Amplify GraphQL schema中,User和Post模型的@auth规则已经添加了公开读权限,示例配置如下:

# 示例schema规则
type User @model @auth(rules: [
  { allow: owner }, # 所有者可编辑
  { allow: public, operations: [read] } # 所有访客可读
]) {
  id: ID!
  username: String!
}

type Post @model @auth(rules: [
  { allow: owner },
  { allow: public, operations: [read] }
]) {
  id: ID!
  content: String!
  username: String!
}

修改schema后记得执行amplify push更新云端配置。

步骤2:修改服务端GraphQL调用的认证模式

在getStaticPaths和getStaticProps的GraphQL调用中,显式指定authMode为公开认证模式(一般为API_KEY,如果你用IAM公开访问则替换为AWS_IAM),不需要读取当前用户身份,修改后的代码如下:

export async function getStaticPaths() {
  const SSR = withSSRContext();
  const { data } = await SSR.API.graphql({ 
    query: listUsers,
    // 显式指定使用公开API Key认证,不需要登录用户
    authMode: 'API_KEY'
  });
  const paths = data.listUsers.items.map((user) => ({
    params: { user: user.username },
  }));

  return {
    fallback: true,
    paths,
  };
}

export async function getStaticProps({ params }) {
  const SSR = withSSRContext();
  const { data } = await SSR.API.graphql({
    query: postsByUsername,
    variables: {
      username: params.username,
    },
    // 同样指定公开认证模式
    authMode: 'API_KEY'
  });

  return {
    props: {
      posts: data.postsByUsername.items,
    },
  };
}

步骤3:确认服务端配置正常

确保你的Next.js项目已经在服务端正确加载了Amplify配置,aws-exports.js中的aws_appsync_apiKey参数可被服务端读取,如果你用环境变量管理配置,确保API Key对应的变量已添加到.env.local文件中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 11:48:03