NextJS 13.4集成AWS Amplify认证报错:Amplify未正确配置
从CRA迁移到NextJS时AWS Amplify认证配置错误问题
问题现象
从CRA迁移到NextJS后,AWS Amplify登录表单能正常显示,但点击登录时触发配置错误,提示Amplify缺少必要的认证属性配置。
错误详情
[ERROR] 40:38.8 AuthError -
Error: Amplify has not been configured correctly.
The configuration object is missing required auth properties.
This error is typically caused by one of the following scenarios:
- Did you run
amplify pushafter adding auth viaamplify add auth?- This could also be caused by multiple conflicting versions of amplify packages.
相关代码
src/app/layout.tsx
import './globals.css' import { Inter } from 'next/font/google' import '@aws-amplify/ui-react/styles.css'; import { Amplify } from "aws-amplify"; import awsExports from "../aws-exports"; Amplify.configure({ ...awsExports, ssr: true }); const inter = Inter({ subsets: ['latin'] }) export const metadata = { title: 'Create Next App', description: 'Generated by create next app', } export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( <html lang="en"> <body className={inter.className}>{children}</body> </html> ) }
src/app/page.tsx
"use client" import { withAuthenticator } from "@aws-amplify/ui-react"; function Home() { return ( <div> <h1>Home</h1> </div> ) } export default withAuthenticator(Home);
已尝试操作
- 重新安装NextJS
- 执行
amplify pull命令
解决方案
- 调整Amplify配置时机
NextJS App Router中layout.tsx是服务端组件,直接在这里配置Amplify会导致客户端组件无法正确获取配置。需要用客户端组件包裹初始化逻辑:
创建src/components/AmplifyProvider.tsx:
"use client"; import { Amplify } from "aws-amplify"; import awsExports from "../aws-exports"; import { useEffect } from "react"; export default function AmplifyProvider({ children }: { children: React.ReactNode }) { useEffect(() => { Amplify.configure({ ...awsExports, ssr: true }); }, []); return <>{children}</>; }
修改layout.tsx引入该组件:
// src/app/layout.tsx import './globals.css' import { Inter } from 'next/font/google' import '@aws-amplify/ui-react/styles.css'; import AmplifyProvider from './components/AmplifyProvider'; const inter = Inter({ subsets: ['latin'] }) export const metadata = { title: 'Create Next App', description: 'Generated by create next app', } export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( <html lang="en"> <body className={inter.className}> <AmplifyProvider>{children}</AmplifyProvider> </body> </html> ) }
- 统一依赖版本
确保所有Amplify相关包版本一致,避免冲突:
npm install aws-amplify@latest @aws-amplify/ui-react@latest
验证配置文件
检查aws-exports.js是否包含完整的认证配置项(如aws_user_pools_id、aws_user_pools_web_client_id),若缺失重新执行amplify pull拉取最新配置。确认项目部署状态
执行amplify status检查认证模块是否已部署,若未部署则执行amplify push完成部署。
内容的提问来源于stack exchange,提问作者Jesper
相关产品推荐
相关产品推荐

