Next.js Project Encountering AWS Amplify Authentication Error: "UserPool not configured"

I am currently developing a project using NextJS and integrating AWS Amplify for authentication with Amazon Cognito. However, I am facing an issue where an error message saying "Auth UserPool not configured" pops up when attempting to log in or sign up. I have double-checked my configurations, and they appear to be correct. Additionally, I can manually create users through the AWS GUI. Below, you can find the relevant code snippet and configuration details.

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

This template.yaml file was executed using sam deploy --guided to establish the infrastructure

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

Answer №1

It seems like using NEXT_PUBLIC_ for your environmental variables could be the way to go in order to make them accessible to your browser environment. Check out more information on how to bundle environment variables for the browser at this link.

Your variables should look something like this:

Amplify.configure({
  Auth: {
   Cognito: {
    region: process.env.NEXT_PUBLIC_REGION,
    userPoolId: process.env.NEXT_PUBLIC_USER_POOL_ID,
    userPoolWebClientId: process.env.NEXT_PUBLIC_USER_POOL_APP_CLIENT_ID,
   }
  }
});

Don't forget to update the variable names in your .env file as well :)

Remember, according to the Amplify documentation, the userpool is configured inside the Cognito property of the Auth object.

Answer №2

It seems like the problem is originating from the configuration setup. In the latest version of AWS Amplify (version 6), there have been updates to the user pool configuration. Please make the necessary adjustments to your configuration as outlined below:

Amplify.configure({
  Auth: {
    Cognito: {
      userPoolClientId: 'abcdefghij1234567890',
      userPoolId: 'us-east-1_abcd1234',
      loginWith: { // Optional
        oauth: {
          domain: 'abcdefghij1234567890-29051e27.auth.us-east-1.amazoncognito.com',
          scopes: ['openid email phone profile aws.cognito.signin.user.admin '],
          redirectSignIn: ['http://localhost:3000/','https://example.com/'],
          redirectSignOut: ['http://localhost:3000/','https://example.com/'],
          responseType: 'code',
        }
        username: 'true',
        email: 'false', // Optional
        phone: 'false', // Optional
      }
    }
  }
});

To find more detailed information, you can refer to the official documentation here: AWS Amplify Documentation

I hope this solution helps in resolving your issue. If you have any more questions, please feel free to ask.

Answer №3

I encountered a similar issue, which was connected to the settings in the "aws-exports" configuration file. While the documentation may be a bit confusing, I managed to resolve it by using this configuration:

export const amplifyConfig = {
  Auth: {
    Cognito: {
      userPoolId: your_userPoolId,
      userPoolClientId: your_userPoolClientId,
      region: your_region,
      loginWith: {
        oauth: {
          domain: your_domain,
          scopes: [
            'phone',
            'email',
            'profile',
            'openid',
            'aws.cognito.signin.user.admin'
          ],
          redirectSignIn: [window.location.origin],
          redirectSignOut: [window.location.origin],
          responseType: "code",
        },
      },
    },
  },
};

Furthermore, ensure that you have a section like this in your index:

import { Amplify, ResourcesConfig } from "aws-amplify";
import { amplifyConfig } from './aws-exports';
Amplify.configure(amplifyConfig as ResourcesConfig);

I hope this solution resolves your issue.

Reference: https://github.com/aws-amplify/amplify-js/issues/12627#issuecomment-1848214340

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the Difference Between Functions in Server Actions and Server Components in NextJS

What are the benefits and distinctions between declaring an async function directly in the server component, using it inside the SC, or defining it within a server action? ...

There was a glitch encountered while constructing (Verifying type validity) with Prisma

There was an issue in the node_modules/@prisma/client/runtime/library.d.ts file on line 1161, specifically error TS1005 where a '?' was expected. 1161 | select: infer S extends object; | ^ 1162 | } & R ...

What functionality does the --use-npm flag serve in the create-next-app command?

When starting a new NextJS project using the CLI, there's an option to use --use-npm when running the command npx create-next-app. If you run the command without any arguments (in interactive mode), this choice isn't provided. In the documentati ...

Advancement of server-side actions in NextJs 13 or 14 can now be tracked in

Is there a method to notify the client of status updates during server actions in NextJs 13 or 14? For example, if you have a server action that involves processing 1000 database records, how can you display the progress of this activity to the client? ...

Encountering npm installation errors with react-messenger-customer-chat

Is anyone facing issues with the installation of react-messenger-customer-chat? [Next.js, tailwind] Check out the GitHub repository here: https://github.com/Yoctol/react-messenger-customer-chat package.json { "name": "with-tailwindcss&quo ...

I am looking for guidance on how to seamlessly link a Wix blog with a Next.js website. Can anyone provide me

I'm currently in the process of building a website for my friend using next.js. She already has a blog on Wix and now wants to integrate it into her new website. Should I build a new blog from scratch with next.js or attempt to connect her existing Wi ...

Tips for creating a hover effect on an icon within a CSS grid

I've just started learning to code and wanted to create a component for previewing/displaying a project I'm working on. I've been attempting to add a hover effect to my links such as the GitHubIcon and LaunchIcon, but so far, it's not w ...

Unable to generate webpage source code

Having some trouble with my Next.js project as I'm using getStaticProps and getStaticPath to build a page, but unfortunately, the HTML is not being generated in the page source. This issue is causing problems with SEO, and I haven't implemented r ...

The type of the object is classified as 'unknown' (2571) while utilizing the map() function with an array containing objects

After researching this error extensively on Google and reading multiple posts, I am still unable to find a solution. I am trying to fetch data from an external API call that has the following signature: const properties: { [x: string]: unknown;} | { [x: s ...

Encountering a 404 error while trying to access dynamic routes in Next.js

I created a dynamic route named [results].js import { useRouter } from 'next/router' const Post = () => { const router = useRouter(); const { results } = router.query; return <p>Post: {results}</p> } export default P ...

Is it necessary for me to utilize Parallel Routes in Nextjs 13?

Hello everyone, I've recently delved into the world of Next.js version 13 and I have a question that's been boggling my mind. According to the documentation, Next.js is used for displaying one or more pages within the same layout. But can't ...

What could be causing the react route to malfunction in Next.js?

The following is the content found in pages/index.js: import { BrowserRouter as Router,History, Switch, Route } from 'react-router-dom'; import TestSocket from '../components/testSocket/TestSocket'; export default function Index(){ ...

Issues with Paypal react and Next JS buttons failing to reflect changes in shopping cart quantities

There seems to be an issue with the React PayPal Buttons integration. Despite updating the quantity of products in the cart, the changes are not being reflected in certain components like createOrder and onApprove within the PaypalButtons props. As a resul ...

What could be causing the malfunction of my token rotation feature in nextAuth?

I am developing a web application that involves working with an external API alongside my team member. We are making API requests using Next.js. I have implemented nextAuth for authentication, but I am facing issues with token rotation. After successful lo ...

Employ the next-intl library in a non-react component scenario

Is there a way to utilize next-intl outside of a React component? Currently, I am obtaining the t by utilizing the hook useTranslations, and then passing its instance to my function: function formatFoo(t, foo) { if .... t('bar'); } ...

Access Firestore documents within the NextJS 13 framework

As a newcomer to React/NextJS, I am working on fetching a list of documents from a Firestore Collection using NextJS 13 in a SSR Page so that I can display them below. Although I have successfully retrieved the documents within my function, the challenge ...

What is the best way to deactivate minutes and seconds in Mui Date and Time Picker?

Currently, I am experimenting with the Mui date and time picker in an attempt to disable minutes and seconds. By using minuteStep={60}, I have successfully disabled the minute selection. However, there is no option to disable the seconds and as a result, t ...

cleaner urls using nextjs routing

Currently working on developing a fresh marketing platform for my company utilizing next.js, and encountering some hurdles with URLs. Essentially, I've created a custom API route to retrieve data from our internal database using Prisma: getAllDealers ...

Tips for utilizing a confidential key to trigger on-demand revalidation for ISR (Next.js) on the client side while keeping it secure from exposure

The documentation suggests using a SECRET_TOKEN to secure access to your revalidate API route, as shown here: https://<your-site.com>/api/revalidate?secret=<token> However, the challenge lies in maintaining secrecy of the token when calling t ...

Understanding how to incorporate Google reCaptcha into Jest unit tests for NextJS API

I have a NextJS API endpoint set up and I am looking to implement unit tests for it. The endpoint is using Google reCAPTCHA to protect the site from bot spamming. While the endpoint seems to be working fine, the method I used to enable unit testing feels s ...