Amazon Cognito Identity JavaScript SDK

6.3.16 · active · verified Sun Apr 19

The `amazon-cognito-identity-js` library is the dedicated JavaScript SDK for interacting directly with Amazon Cognito User Pools and Identity Pools. It enables client-side implementation of user registration, authentication, password management, and session handling without relying on a full backend. Currently at version 6.3.16, this library is actively maintained as part of the broader AWS Amplify monorepo, where its development is now integrated. While it provides low-level control over Cognito interactions, AWS encourages developers to consider the higher-level abstractions offered by AWS Amplify's `Auth` category (Amplify v6 and newer) for a more streamlined, tree-shakable, and modern developer experience. Updates are frequent, often bundled with Amplify releases. Its key differentiator is providing direct, granular access to Cognito's features for applications that require specific authentication flows or need to integrate with existing non-Amplify AWS SDK setups.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates a basic user signup and authentication flow using Cognito User Pools, including handling existing users and prompts for new passwords.

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

const poolData = {
  UserPoolId: process.env.COGNITO_USER_POOL_ID ?? 'us-east-1_xxxxxxxx',
  ClientId: process.env.COGNITO_CLIENT_ID ?? 'xxxxxxxxxxxxxxx',
};

const userPool = new CognitoUserPool(poolData);

async function signUpAndSignIn(username, password, email) {
  return new Promise((resolve, reject) => {
    userPool.signUp(username, password, [{ Name: 'email', Value: email }], null, (err, result) => {
      if (err) {
        if (err.code === 'UsernameExistsException') {
          console.log('User already exists, proceeding to sign-in...');
          // If user exists, try to sign in (or confirm if not yet confirmed)
          signIn(username, password).then(resolve).catch(reject);
        } else {
          console.error('Signup error:', err.message);
          reject(err);
        }
        return;
      }
      const cognitoUser = result.user;
      console.log('User signed up:', cognitoUser.getUsername());
      // Auto-confirm if not using verification codes for this example (in a real app, you'd confirm first)
      // For this example, we assume auto-confirmation or manual confirmation out-of-band.
      // A real app would typically require an explicit confirmation step.
      signIn(username, password).then(resolve).catch(reject);
    });
  });
}

async function signIn(username, password) {
  return new Promise((resolve, reject) => {
    const authenticationDetails = new AuthenticationDetails({
      Username: username,
      Password: password,
    });

    const cognitoUser = new CognitoUser({ Username: username, Pool: userPool });

    cognitoUser.authenticateUser(authenticationDetails, {
      onSuccess: function (session) {
        console.log('Authentication successful. Session:', session.getIdToken().getJwtToken());
        resolve(session);
      },
      onFailure: function (err) {
        console.error('Authentication failed:', err.message);
        reject(err);
      },
      newPasswordRequired: function (userAttributes, requiredAttributes) {
        // User needs to set a new password, e.g., on first login with temporary password
        console.log('New password required. User attributes:', userAttributes, 'Required attributes:', requiredAttributes);
        // In a real application, you would prompt the user for a new password here
        // and call cognitoUser.completeNewPasswordChallenge(newPassword, userAttributes);
        reject(new Error('New password required. Implement `newPasswordRequired` handler.'));
      },
      mfaRequired: function () {
        console.warn('MFA required. Implement `mfaRequired` handler.');
        reject(new Error('MFA required. Implement `mfaRequired` handler.'));
      }
    });
  });
}

// Example Usage (ensure environment variables are set or replace placeholders)
signUpAndSignIn('testuser' + Date.now(), 'MyStrongPassword1!', 'test' + Date.now() + '@example.com')
  .then(session => console.log('Final session obtained:', session.isValid()))
  .catch(error => console.error('Overall flow failed:', error.message));

view raw JSON →