AWS Cognito Sign Up Confirm with Node.js
Tags: aws, signup, cognito, node
Published: 2023-06-09 09:42:53

Let's add AWS Cognito Sign Up Confirm function to the Node project today.
I suppose your project already add AWS Cognito Sign Up to your project.

If not, please take a look at my provious articles:

| Article                                                           | Codebase                                                                 |
| ----------------------------------------------------------------- | ------------------------------------------------------------------------ |
| [ES6 Node-Express Boilerplate](https://dev.to/itwebtiger/express-es6-boilerplate-2pd5) | https://github.com/itwebtiger/express-amazon-cognito/tree/init-expressjs |
| [AWS Cognito Setup](https://dev.to/itwebtiger/aws-cognito-setup-for-user-authentication-2c2)               | ----                                                                     |
| [AWS Cognito Sign Up with Node.js](https://dev.to/itwebtiger/aws-cognito-sign-up-with-nodejs-4202) | https://github.com/itwebtiger/express-amazon-cognito/tree/cognito-signup |

Also, you can download the [full codebase](https://github.com/itwebtiger/express-amazon-cognito/tree/cognito-signupconfirm) here if you are interested in this _AWS Cognito Sign Up Email Confirm_.

<br />

## Add a AWS Cognito Sign Up Email Confirm route

- Add [/api/auth/email/verify](https://github.com/itwebtiger/express-amazon-cognito/blob/3b9d84108bf4eb3c55cc154be0347292e9016f07/routes/auth.routes.js#L9) route in existing your node.js project, if don't use [validateSignupRequest](https://github.com/itwebtiger/express-amazon-cognito/blob/3b9d84108bf4eb3c55cc154be0347292e9016f07/middleware/validateSignupConfirmRequest.js) middleware, then you can remove the `validateSignupRequest` middleware.

```
import controller from '../controllers/auth.controller';
import {
  validateSignupRequest,
  validateSignupConfirmRequest,
} from '../middleware';

export default (app) => {
  app.post('/api/auth/signup', validateSignupRequest, controller.signup);
  app.post(
    '/api/auth/email/verify',
    validateSignupConfirmRequest,
    controller.signupConfirm,
  );
};
```

<br />

## Add a Sign Up Email Confirm Function in the auth controller.

- Add a [Sign Up Email Confirm Function](https://github.com/itwebtiger/express-amazon-cognito/blob/3b9d84108bf4eb3c55cc154be0347292e9016f07/controllers/auth.controller.js#L39) in the controller.

```
// 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 });
  }
};

const signupConfirm = async (req, res) => {
  const { email, code } = req.body;
  const cognitoParams = {
    username: email,
    confirmationCode: code,
  };

  try {
    await new Promise((resolve, reject) => {
      CognitoIdentityService.signupConfirm(cognitoParams, (err, user) => {
        if (err) {
          reject(err);
        } else {
          resolve(user);
        }
      });
    });

    // DB logic here
    // ...

    res.status(200).send({
      success: true,
      message: 'User email confirmed successfully',
      user: {
        user_confirmed: true,
      },
    });
  } catch (error) {
    res.status(400).send({ success: false, message: error.message, error });
  }
};

export default {
  signup,
  signupConfirm,
};
```

<br />

## Add a Sign Up Email Confirm 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](https://github.com/itwebtiger/express-amazon-cognito/blob/cognito-signupconfirm/services/cognito/methods/signupConfirm.js).

```
services/
  └──cognito/
        ├── index.js
        └── methods/
              ├── index.js
              ├── signup.js
              └── signupConfirm.js

```

This is a signupConfirm file, please add it.

```
import { CognitoUserPool, CognitoUser } from 'amazon-cognito-identity-js';

/**
 * Confirm the signup action
 * @param {*} poolData
 * @param {{username, confirmationCode}} body
 * @param {*} callback
 */

const signupConfirm = (poolData, body, callback) => {
  const userPool = new CognitoUserPool(poolData);

  const { username, confirmationCode } = body;

  const userData = {
    Username: username,
    Pool: userPool,
  };

  const cognitoUser = new CognitoUser(userData);

  cognitoUser.confirmRegistration(confirmationCode, true, (err, res) =>
    callback(err, res),
  );
};

export default signupConfirm;
```

## The Result in the Postman

![Cognito email verification](https://chrisw.vercel.app/_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fauthsignupverify.54bb3cb6.png&w=1920&q=75)

<br />

We will take a look at AWS Cognito login in the next article.
If you like this type of content you can give me a star on my [GitHub repository](https://github.com/itwebtiger/express-amazon-cognito/tree/cognito-signupconfirm) for the latest updates.

## References

https://github.com/itwebtiger/express-amazon-cognito/tree/cognito-signupconfirm
https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-social-idp.html#cognito-user-pools-social-idp-step-1