Skip to content
Welcome to the new, Chris Portfolio! đź‘‹
Projects
Cognito Sign Up

AWS Cognito Sign Up with Node.js

AWS Cognito Sign Up

Hope you have already set up the Node.JS environment on your system and exist Express.js project (opens in a new tab) and the AWS Cognito on AWS side, if didn't set up the AWS Cognito, then use the following tutorial to AWS Cognito setup. Also, you can download the full codebase (opens in a new tab) here if you are interested in this AWS Cognito Sign Up.

Set Cognito environment variables

Then we will use these environment variables in the Node project.

example.env
  AWS_COGNITO_REGION=
  AWS_COGNITO_USER_POOL_ID=
  AWS_COGNITO_CLIENT_ID=
  AWS_COGNITO_IDENTITY_POOL_ID=
.env
  AWS_COGNITO_REGION=ca-central-1
  AWS_COGNITO_USER_POOL_ID=ca-central-1_oOXMEFtX3
  AWS_COGNITO_CLIENT_ID=54ado14mc8n0cmnm5s70vsis63
  AWS_COGNITO_IDENTITY_POOL_ID=ca-central-1:18ec2ec3-9e0a-474c-9d82-eb811b028e83

Add a Sign Up Route in the Node.js Project

auth.routes.js
import controller from '../controllers/auth.controller';
import validateSignupRequest from '../middleware/validateSignupRequest';
 
export default (app) => {
  app.post('/api/auth/signup', validateSignupRequest, controller.signup);
};

Add a Sign Up Function in the auth controller.

auth.controller.js
// User Signup
import CognitoIdentity from '../services/cognito';
 
const CognitoIdentityService = CognitoIdentity();
 
const signup = async (req, res) => {
  // Signup logic here
  // ...
 
  const { email, password, givenname, familyname } = req.body;
 
  const cognitoParams = {
    username: email,
    password,
    givenname,
    familyname,
  };
 
  try {
    const cognitoUser = await new Promise((resolve, reject) => {
      CognitoIdentityService.signup(cognitoParams, (err, user) => {
        if (err) {
          reject(err);
        } else {
          resolve(user);
        }
      });
    });
 
    res.status(200).send({
      success: true,
      message: 'User registered successfully',
      user: cognitoUser,
    });
  } catch (error) {
    res.status(400).send({ success: false, message: error.message, error });
  }
};
 
export default {
  signup,
};

Add a Sign Up in the services.

And then we need to add the AWS Cognito user authentication service to the services folder. I will use the amazon-cognito-identity-js for the service. If you don't understand how to work the service, please check the service folder structure on my git repository (opens in a new tab).

signup.js
import {
  CognitoUserPool,
  CognitoUserAttribute,
} from 'amazon-cognito-identity-js';
 
const attributes = (key, value) => ({
  Name: key,
  Value: value,
});
 
/**
 * Signup user
 *
 * @param {poolData} poolData
 * @param {{ username: string, password: string, givenname: string, familyname: string, }} body
 * @param {*} callback
 */
 
const signup = (poolData, body, callback) => {
  const userPool = new CognitoUserPool(poolData);
 
  const { username, password, givenname, familyname } = body;
  const attributesList = [
    attributes('email', username),
    attributes('given_name', givenname),
    attributes('family_name', familyname),
  ];
 
  const cognitoAttributeList = attributesList.map(
    (element) => new CognitoUserAttribute(element),
  );
 
  userPool.signUp(
    username,
    password,
    cognitoAttributeList,
    null,
    (err, res) => {
      if (err) {
        callback(err);
        return;
      }
 
      const data = {
        user_id: res.userSub,
        email: res.username,
        user_confirmed: res.userConfirmed,
      };
 
      callback(null, data);
    },
  );
};
 
export default signup;

The Result in the Postman

Cognito email verification


6 Digit OTP For Email Verification.

Then you will receive the 6 Digit OTP for email verification as shown below in the screenshot.

Cognito email verification

If you want you can customize your email messages. So when a user sign ups he will get an email to confirm his account. You can customize that message.

This is it for the signup scope now. We will take a look at signup email verification in the next article.

References

https://github.com/itwebtiger/express-amazon-cognito/tree/cognito-signup (opens in a new tab) https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-social-idp.html#cognito-user-pools-social-idp-step-1 (opens in a new tab)