Next.js项目中AWS Amplify认证报错:Auth UserPool未配置
问题:NextJS + AWS Amplify + Cognito 认证报错 "Auth UserPool not configured"
我正在开发一个NextJS项目,使用AWS Amplify结合Amazon Cognito实现认证功能,但登录/注册时收到错误提示**"Auth UserPool not configured"**。我确认配置信息无误,且能通过AWS控制台手动创建用户。以下是相关代码和配置详情:
Index.js
import React, { useState, useEffect } from 'react' import { Amplify } from 'aws-amplify' import { Authenticator } from '@aws-amplify/ui-react' import '@aws-amplify/ui-react/styles.css' import { Auth } from 'aws-amplify' Amplify.configure({ Auth: { region: process.env.REGION, userPoolId: process.env.USER_POOL_ID, userPoolWebClientId: process.env.USER_POOL_APP_CLIENT_ID, }, }) function Home() { const [jwtToken, setJwtToken] = useState('') useEffect(() => { fetchJwtToken() }, []) const fetchJwtToken = async () => { try { const session = await Auth.currentSession() const token = session.getIdToken().getJwtToken() setJwtToken(token) } catch (error) { console.log('Error fetching JWT token:', error) } } return ( <Authenticator initialState='signIn' components={{ SignUp: { FormFields() { return ( <> <Authenticator.SignUp.FormFields /> {/* Custom fields for given_name and family_name */} <div> <label>First name</label> </div> <input type='text' name='given_name' placeholder='Please enter your first name' /> <div> <label>Last name</label> </div> <input type='text' name='family_name' placeholder='Please enter your last name' /> <div> <label>Email</label> </div> <input type='text' name='email' placeholder='Please enter a valid email' /> </> ) }, }, }} services={{ async validateCustomSignUp(formData) { if (!formData.given_name) { return { given_name: 'First Name is required', } } if (!formData.family_name) { return { family_name: 'Last Name is required', } } if (!formData.email) { return { email: 'Email is required', } } }, }} > {({ signOut, user }) => ( <div> Welcome {user.username} <button onClick={signOut}>Sign out</button> <h4>Your JWT token:</h4> {jwtToken} </div> )} </Authenticator> ) } export default Home
基础设施部署模板 template.yaml
AWSTemplateFormatVersion: 2010-09-09 Description: >- template for creating the Cognito User Pool Transform: - AWS::Serverless-2016-10-31 Parameters: Env: Type: String Default: dev S3BucketName: Type: String Default: pibot-nextjs-website CognitoUserPoolName: Type: String Default: pibot-users-v2 CognitoWebClientName: Type: String Default: cognito-webclient Resources: CloudFrontOriginAccessIdentity: Type: 'AWS::CloudFront::CloudFrontOriginAccessIdentity' Properties: CloudFrontOriginAccessIdentityConfig: Comment: 'Origin Access Identity' CloudfrontDistribution: Type: 'AWS::CloudFront::Distribution' Properties: DistributionConfig: Comment: 'Cloudfront distribution for the static website' DefaultRootObject: 'index.html' Enabled: true HttpVersion: http2 Origins: - Id: s3-website DomainName: !GetAtt S3Bucket.DomainName S3OriginConfig: OriginAccessIdentity: Fn::Sub: 'origin-access-identity/cloudfront/${CloudFrontOriginAccessIdentity}' DefaultCacheBehavior: Compress: 'true' AllowedMethods: - GET - HEAD - OPTIONS ForwardedValues: QueryString: false TargetOriginId: s3-website ViewerProtocolPolicy: redirect-to-https S3Bucket: Type: AWS::S3::Bucket Properties: BucketName: !Sub '${Env}-${S3BucketName}' S3BucketPolicy: Type: AWS::S3::BucketPolicy Properties: Bucket: !Ref S3Bucket PolicyDocument: Statement: - Effect: Allow Action: 's3:GetObject' Resource: - !Sub 'arn:aws:s3:::${S3Bucket}/*' Principal: AWS: !Sub 'arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${CloudFrontOriginAccessIdentity}' CognitoUserPool: Type: AWS::Cognito::UserPool Properties: UserPoolName: !Sub '${Env}-${CognitoUserPoolName}' AliasAttributes: - email UsernameConfiguration: CaseSensitive: false AutoVerifiedAttributes: - email Policies: PasswordPolicy: MinimumLength: 8 RequireLowercase: true RequireNumbers: true RequireUppercase: true RequireSymbols: true Schema: - AttributeDataType: String Mutable: true Name: given_name Required: true StringAttributeConstraints: MinLength: '1' - AttributeDataType: String Mutable: true Name: family_name Required: true StringAttributeConstraints: MinLength: '1' - AttributeDataType: String Mutable: true Name: email Required: true StringAttributeConstraints: MinLength: '1' WebCognitoUserPoolClient: Type: AWS::Cognito::UserPoolClient Properties: ClientName: !Sub '${Env}-${CognitoWebClientName}' UserPoolId: !Ref CognitoUserPool ExplicitAuthFlows: - ALLOW_USER_SRP_AUTH - ALLOW_REFRESH_TOKEN_AUTH PreventUserExistenceErrors: ENABLED
解决方案
1. 修正环境变量命名规则
NextJS中,客户端代码可访问的环境变量必须以NEXT_PUBLIC_为前缀。将你的环境变量名修改为:
NEXT_PUBLIC_REGIONNEXT_PUBLIC_USER_POOL_IDNEXT_PUBLIC_USER_POOL_APP_CLIENT_ID
修改后重启开发服务器,或确保部署时这些变量被正确注入到构建环境中。
2. 提前Amplify配置时机
将Amplify配置移到应用入口文件(Pages Router为_app.js,App Router为layout.js),确保在Authenticator组件初始化前完成配置:
Pages Router _app.js 示例
import { Amplify } from 'aws-amplify'; import '@aws-amplify/ui-react/styles.css'; Amplify.configure({ Auth: { region: process.env.NEXT_PUBLIC_REGION, userPoolId: process.env.NEXT_PUBLIC_USER_POOL_ID, userPoolWebClientId: process.env.NEXT_PUBLIC_USER_POOL_APP_CLIENT_ID, }, }); export default function App({ Component, pageProps }) { return <Component {...pageProps} />; }
3. 验证Cognito客户端配置
检查WebCognitoUserPoolClient资源:
- 确认已启用
ALLOW_USER_SRP_AUTH和ALLOW_REFRESH_TOKEN_AUTH认证流(你的模板已配置,此步可跳过) - 若无需OAuth功能,确保未设置
AllowedOAuthFlowsUserPoolClient属性(你的模板符合要求)
4. 对齐Amplify依赖版本
确保aws-amplify与@aws-amplify/ui-react版本兼容,执行以下命令升级到最新兼容版本:
npm update aws-amplify @aws-amplify/ui-react
5. 调试环境变量加载情况
在客户端代码中添加日志,确认环境变量是否正确获取:
console.log('Region:', process.env.NEXT_PUBLIC_REGION); console.log('User Pool ID:', process.env.NEXT_PUBLIC_USER_POOL_ID); console.log('Client ID:', process.env.NEXT_PUBLIC_USER_POOL_APP_CLIENT_ID);
若日志显示undefined,说明环境变量未正确加载,需检查.env.local文件或部署时的变量配置。
内容的提问来源于stack exchange,提问作者Hatprob
相关产品推荐
相关产品推荐

