React/Next.js配置Amplify+Cognito时遇loginWith未定义错误
解决Amplify v6 + Next.js 13中"Cannot read properties of undefined (reading 'loginWith')"错误
核心原因
Amplify v6对Auth配置结构、初始化逻辑做了调整,同时Next.js的SSR环境需要额外适配,你遇到的错误大概率是配置项名称不兼容或SSR未适配导致Auth模块初始化不完整,进而触发OAuth相关逻辑报错。
解决方案
1. 修正Auth配置项(适配Amplify v6)
Amplify v6中将userPoolWebClientId更名为userPoolClientId,同时如果不需要OAuth登录流,需要显式配置空的OAuth参数避免默认触发:
// aws-exports.js const awsconfig = { Auth: { region: 'AWS_REGION', userPoolId: 'USER_POOL_ID', userPoolClientId: 'USER_POOL_WEB_CLIENT_ID', // 替换为原userPoolWebClientId的值 authenticationFlowType: 'USER_PASSWORD_AUTH', // 显式禁用OAuth(如果不需要的话) oauth: { domain: '', redirectSignIn: '', redirectSignOut: '', responseType: '' } } }; export default awsconfig;
2. 适配Next.js SSR环境初始化Amplify
在Next.js中,需要启用Amplify的SSR支持,并确保在客户端环境初始化(避免服务器端初始化异常):
// _app.tsx import { useEffect } from 'react'; import { Amplify } from 'aws-amplify'; import awsconfig from '../aws-exports'; import type { AppProps } from 'next/app'; function MyApp({ Component, pageProps }: AppProps) { useEffect(() => { // 添加ssr: true适配Next.js服务端渲染 Amplify.configure({ ...awsconfig, ssr: true }); }, []); return <Component {...pageProps} />; } export default MyApp;
如果你使用Next.js 13+ App Router,可以在根layout.tsx的客户端组件中执行初始化逻辑。
3. 检查UI组件使用方式
使用@aws-amplify/ui-react的Authenticator组件时,确保遵循v6的用法,且没有手动调用未初始化的Auth方法:
import { Authenticator } from '@aws-amplify/ui-react'; import '@aws-amplify/ui-react/styles.css'; export default function Home() { return ( <Authenticator> {({ signOut, user }) => ( <div> <h2>欢迎,{user?.username}</h2> <button onClick={signOut}>退出登录</button> </div> )} </Authenticator> ); }
4. 清理依赖缓存重新安装
如果以上步骤无效,可能是依赖缓存或版本兼容问题,执行以下命令重置依赖:
rm -rf node_modules package-lock.json npm install
内容的提问来源于stack exchange,提问作者Anroche
相关产品推荐
相关产品推荐

