{"id":10495,"library":"amazon-cognito-identity-js","title":"Amazon Cognito Identity JavaScript SDK","description":"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.","status":"active","version":"6.3.16","language":"javascript","source_language":"en","source_url":"https://github.com/aws-amplify/amplify-js","tags":["javascript","amazon","aws","cognito","identity","react-native","reactnative","typescript"],"install":[{"cmd":"npm install amazon-cognito-identity-js","lang":"bash","label":"npm"},{"cmd":"yarn add amazon-cognito-identity-js","lang":"bash","label":"yarn"},{"cmd":"pnpm add amazon-cognito-identity-js","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Provides core utilities and configuration common to Amplify-related libraries.","package":"@aws-amplify/core","optional":false}],"imports":[{"note":"Primary class for configuring and interacting with a Cognito User Pool.","wrong":"const CognitoUserPool = require('amazon-cognito-identity-js').CognitoUserPool;","symbol":"CognitoUserPool","correct":"import { CognitoUserPool } from 'amazon-cognito-identity-js';"},{"note":"Represents a user in a Cognito User Pool, used for operations like authentication and attribute management.","wrong":"const CognitoUser = require('amazon-cognito-identity-js').CognitoUser;","symbol":"CognitoUser","correct":"import { CognitoUser } from 'amazon-cognito-identity-js';"},{"note":"Required to pass user credentials (username, password) during the authentication process.","wrong":"const AuthenticationDetails = require('amazon-cognito-identity-js').AuthenticationDetails;","symbol":"AuthenticationDetails","correct":"import { AuthenticationDetails } from 'amazon-cognito-identity-js';"},{"note":"Represents the session details, including ID, access, and refresh tokens, received after successful authentication.","wrong":"const CognitoUserSession = require('amazon-cognito-identity-js').CognitoUserSession;","symbol":"CognitoUserSession","correct":"import { CognitoUserSession } from 'amazon-cognito-identity-js';"}],"quickstart":{"code":"import { CognitoUserPool, CognitoUser, AuthenticationDetails } from 'amazon-cognito-identity-js';\n\nconst poolData = {\n  UserPoolId: process.env.COGNITO_USER_POOL_ID ?? 'us-east-1_xxxxxxxx',\n  ClientId: process.env.COGNITO_CLIENT_ID ?? 'xxxxxxxxxxxxxxx',\n};\n\nconst userPool = new CognitoUserPool(poolData);\n\nasync function signUpAndSignIn(username, password, email) {\n  return new Promise((resolve, reject) => {\n    userPool.signUp(username, password, [{ Name: 'email', Value: email }], null, (err, result) => {\n      if (err) {\n        if (err.code === 'UsernameExistsException') {\n          console.log('User already exists, proceeding to sign-in...');\n          // If user exists, try to sign in (or confirm if not yet confirmed)\n          signIn(username, password).then(resolve).catch(reject);\n        } else {\n          console.error('Signup error:', err.message);\n          reject(err);\n        }\n        return;\n      }\n      const cognitoUser = result.user;\n      console.log('User signed up:', cognitoUser.getUsername());\n      // Auto-confirm if not using verification codes for this example (in a real app, you'd confirm first)\n      // For this example, we assume auto-confirmation or manual confirmation out-of-band.\n      // A real app would typically require an explicit confirmation step.\n      signIn(username, password).then(resolve).catch(reject);\n    });\n  });\n}\n\nasync function signIn(username, password) {\n  return new Promise((resolve, reject) => {\n    const authenticationDetails = new AuthenticationDetails({\n      Username: username,\n      Password: password,\n    });\n\n    const cognitoUser = new CognitoUser({ Username: username, Pool: userPool });\n\n    cognitoUser.authenticateUser(authenticationDetails, {\n      onSuccess: function (session) {\n        console.log('Authentication successful. Session:', session.getIdToken().getJwtToken());\n        resolve(session);\n      },\n      onFailure: function (err) {\n        console.error('Authentication failed:', err.message);\n        reject(err);\n      },\n      newPasswordRequired: function (userAttributes, requiredAttributes) {\n        // User needs to set a new password, e.g., on first login with temporary password\n        console.log('New password required. User attributes:', userAttributes, 'Required attributes:', requiredAttributes);\n        // In a real application, you would prompt the user for a new password here\n        // and call cognitoUser.completeNewPasswordChallenge(newPassword, userAttributes);\n        reject(new Error('New password required. Implement `newPasswordRequired` handler.'));\n      },\n      mfaRequired: function () {\n        console.warn('MFA required. Implement `mfaRequired` handler.');\n        reject(new Error('MFA required. Implement `mfaRequired` handler.'));\n      }\n    });\n  });\n}\n\n// Example Usage (ensure environment variables are set or replace placeholders)\nsignUpAndSignIn('testuser' + Date.now(), 'MyStrongPassword1!', 'test' + Date.now() + '@example.com')\n  .then(session => console.log('Final session obtained:', session.isValid()))\n  .catch(error => console.error('Overall flow failed:', error.message));\n","lang":"typescript","description":"Demonstrates a basic user signup and authentication flow using Cognito User Pools, including handling existing users and prompts for new passwords."},"warnings":[{"fix":"Review the AWS Amplify v6 migration guide for 'Auth' category changes. For direct `amazon-cognito-identity-js` usage, ensure your code aligns with its specific API, or consider migrating to Amplify's `Auth` functions for new development.","message":"For projects migrating from AWS Amplify JavaScript v5 to v6, the approach for authentication has significantly changed. Amplify v6 moves from a class-based to a function-based API, utilizing named parameters and requiring imports from subpaths (e.g., `aws-amplify/auth`) instead of the main `aws-amplify` package. While `amazon-cognito-identity-js` remains functional, direct usage is often superseded by Amplify's `Auth` category in v6.","severity":"breaking","affected_versions":">=6.0.0"},{"fix":"Uninstall `amazon-cognito-identity-js` and install `@aws-amplify/react-native`. Adapt your code to use the new package's functionalities as per the Amplify v6 React Native migration guide.","message":"For React Native projects, `amazon-cognito-identity-js` is deprecated in favor of `@aws-amplify/react-native` starting with Amplify v6. Migrating React Native projects should remove this package and install the new `@aws-amplify/react-native` package.","severity":"breaking","affected_versions":">=6.0.0"},{"fix":"In the AWS Cognito console, for your User Pool App Client settings, ensure 'Generate client secret' is NOT checked. If you have an existing client with a secret, create a new one without it.","message":"When creating an App Client for your Cognito User Pool, you *must* ensure that the 'Generate client secret' option is unchecked. The JavaScript SDK (and `amazon-cognito-identity-js`) does not support app clients configured with a client secret.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"If configuring Amplify, update your `Auth` configuration: replace `mandatorySignIn: false` with `allowGuestAccess: true`. If using `amazon-cognito-identity-js` directly with an Identity Pool, ensure your credentials provider logic correctly handles unauthenticated identities.","message":"For unauthenticated access to Identity Pools (e.g., for accessing other AWS services like API Gateway) when using Amplify v6, the `mandatorySignIn` configuration key has been replaced by `allowGuestAccess`. Direct usage of `amazon-cognito-identity-js` for identity pool interactions might also be impacted by underlying Amplify configurations.","severity":"gotcha","affected_versions":">=6.0.0"},{"fix":"While the package is still active, direct contributions or issue reporting should be done via the AWS Amplify GitHub repository. Users should generally consider using Amplify's higher-level Auth module if possible.","message":"The GitHub repository `amazon-archives/amazon-cognito-identity-js` states that direct development on this specific repository has been discontinued. Future development and issue tracking now occur within the main `aws-amplify/amplify-js` monorepo.","severity":"deprecated","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Before `signUp`, check if the user exists using `userPool.getCurrentUser()` or by attempting a sign-in. If the user exists and is unconfirmed, initiate a confirmation flow (`resendConfirmationCode`, `confirmRegistration`).","cause":"Attempting to sign up a user with a username or email that is already registered in the Cognito User Pool.","error":"UsernameExistsException: An account with the given email already exists."},{"fix":"Double-check credentials. If it's a new user, ensure they have confirmed their registration (via email/SMS code) before attempting to sign in. Implement error handling for `newPasswordRequired` and `mfaRequired` callbacks if applicable.","cause":"The username or password provided during authentication does not match the records in Cognito, or the user is not confirmed.","error":"NotAuthorizedException: Incorrect username or password."},{"fix":"Ensure `amazon-cognito-identity-js` is correctly installed via `npm i amazon-cognito-identity-js`. For React Native, consider migrating to `@aws-amplify/react-native` as it handles necessary polyfills automatically. For web, ensure your bundler includes required Node.js polyfills if running in a non-Node environment.","cause":"This error often occurs in React Native environments or certain build setups when dependencies are not correctly linked or polyfills are missing, specifically related to cryptographic functions.","error":"TypeError: (0, _getRandomBase.default) is not a function"},{"fix":"Ensure your Cognito User Pool domain is correctly configured in your application. If interacting with other AWS services (e.g., API Gateway), verify their CORS settings. For local development, some development servers (like Webpack Dev Server) can proxy requests to avoid CORS issues.","cause":"Cross-Origin Resource Sharing (CORS) issues typically arise when a browser-based application tries to access the Cognito API from a different origin (domain, protocol, port) than what is allowed by the server. While Cognito itself generally handles CORS well for its standard endpoints, misconfigurations in API Gateway or other AWS services interacting with Cognito can lead to this.","error":"Access to fetch at 'https://cognito-idp.us-east-1.amazonaws.com/...' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."}],"ecosystem":"npm"}