Now let’s look into setting up Cognito User Pool through the serverless.yml. It should be noted that due to a limitation CloudFormation, the setup here is going to differ a little from the one we did by hand in the Create a Cognito user pool chapter.

Create the Resource

Add the following to resources/cognito-user-pool.yml.

    Type: AWS::Cognito::UserPool
      # Generate a name based on the stage
      UserPoolName: ${self:custom.stage}-user-pool
      # Set email as an alias
        - email
        - email

    Type: AWS::Cognito::UserPoolClient
      # Generate an app client name based on the stage
      ClientName: ${self:custom.stage}-user-pool-client
        Ref: CognitoUserPool
      GenerateSecret: false

# Print out the Id of the User Pool that is created
      Ref: CognitoUserPool

      Ref: CognitoUserPoolClient

Let’s quickly go over what we are doing here:

  • We are naming our User Pool (and the User Pool app client) based on the stage by using the custom variable ${self:custom.stage}.

  • We are setting the user’s email as an alias. This means that the user can log in with either their username or their email. This is different from the Create a Cognito user pool chapter, where we explicitly use a setting that allows users to login with their email. The reason we are using the alias is because CloudFormation does not currently support this. You can read a bit more about it here. This change also means that we have to tweak our frontend a little bit.

  • Just like our S3 bucket, we want CloudFormation to tell us the User Pool Id and the User Pool Client Id that is generated. We do this in the Outputs: block at the end.

Add the Resource

Let’s reference the resource in our serverless.yml. Replace your resources: block with the following.

# Create our resources with separate CloudFormation templates
  # DynamoDB
  - ${file(resources/dynamodb-table.yml)}
  # S3
  - ${file(resources/s3-bucket.yml)}
  # Cognito
  - ${file(resources/cognito-user-pool.yml)}

Commit Your Code

Let’s commit the changes we’ve made so far.

$ git add .
$ git commit -m "Adding our Cognito User Pool resource"

And next let’s tie all of this together by configuring our Cognito Identity Pool.