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

NextJS 15 + AWS Amplify登录成功后isAuthenticated返回false求助

临时解决方案:NextJS 15 + AWS Amplify Cognito 登录状态同步问题

针对你遇到的signIn返回成功但自定义isAuthenticated()始终返回false的问题,以下是几个适配NextJS 15的临时解决思路:

方案一:手动同步登录状态到本地存储

由于Amplify暂未适配NextJS 15,可能存在登录凭据未正确写入本地存储的情况,可以在登录成功后手动存储会话信息:

// 登录成功后的处理逻辑
const handleSignIn = async (username, password) => {
  const user = await Auth.signIn(username, password);
  if (user.isSignedIn && user.nextStep.signInStep === 'DONE') {
    const session = await user.getSession();
    // 手动存储核心状态到localStorage
    localStorage.setItem('amplify_is_signed_in', 'true');
    localStorage.setItem('amplify_session_expires', session.expiresAt.toString());
  }
};

// 修改自定义isAuthenticated方法
export const isAuthenticated = () => {
  const isSignedIn = localStorage.getItem('amplify_is_signed_in') === 'true';
  const expiresAt = localStorage.getItem('amplify_session_expires');
  
  if (!isSignedIn || !expiresAt) return false;
  // 校验会话是否过期
  return Date.now() < parseInt(expiresAt) * 1000;
};

方案二:强制在客户端组件中维护Auth状态

NextJS 15的App Router中服务器组件无法访问浏览器存储,需确保Amplify初始化及状态监听都在客户端组件中完成:

// app/layout.tsx 标记为客户端组件
'use client';

import { Amplify } from 'aws-amplify';
import amplifyConfig from '../amplifyconfiguration.json';

Amplify.configure(amplifyConfig);

export default function RootLayout({ children }) {
  return (
    <html lang="zh-CN">
      <body>{children}</body>
    </html>
  );
}

然后用自定义Hook替代原isAuthenticated()方法:

'use client';

import { useState, useEffect } from 'react';
import { Auth } from 'aws-amplify';

export const useIsAuthenticated = () => {
  const [isAuth, setIsAuth] = useState(false);

  useEffect(() => {
    // 初始检查登录状态
    const checkAuth = async () => {
      try {
        await Auth.currentAuthenticatedUser();
        setIsAuth(true);
      } catch {
        setIsAuth(false);
      }
    };
    checkAuth();

    // 监听Auth状态变化
    const unsubscribe = Auth.subscribe({
      next: (data) => {
        setIsAuth(data.payload.event === 'signIn');
      }
    });

    return () => unsubscribe();
  }, []);

  return isAuth;
};

方案三:直接复用Amplify官方方法判断状态

放弃自定义方法,临时直接调用Amplify的currentAuthenticatedUser做状态校验:

export const isAuthenticated = async () => {
  try {
    // 绕过缓存强制拉取最新状态
    const user = await Auth.currentAuthenticatedUser({ bypassCache: true });
    return !!user;
  } catch (err) {
    return false;
  }
};

注意事项

  • 以上方案均为临时适配,待AWS Amplify正式支持NextJS 15后,建议切换回官方标准流程
  • 手动存储会话信息时需注意XSS风险,敏感场景建议使用sessionStorage替代localStorage
  • 服务器组件中需获取登录状态的话,可通过NextJS的headers()读取Cognito ID Token并手动校验

内容的提问来源于stack exchange,提问作者raw.nato

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 23:43:09