Registry / aws / amazon-cognito-identity-js

amazon-cognito-identity-js

JSON →
library6.3.16jsnpmunverified

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.

npm install amazon-cognito-identity-js
INSTALL
IMPORT
SIG · AMAZON-COGNITO-IDE
A
amazon-cognito-identity-js
awsjavascriptv6.3.16
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

CognitoUserPool
import { CognitoUserPool } from 'amazon-cognito-identity-js';
const CognitoUserPool = require('amazon-cognito-identity-js').CognitoUserPool;
Primary class for configuring and interacting with a Cognito User Pool.
CognitoUser
import { CognitoUser } from 'amazon-cognito-identity-js';
const CognitoUser = require('amazon-cognito-identity-js').CognitoUser;
Represents a user in a Cognito User Pool, used for operations like authentication and attribute management.
AuthenticationDetails
import { AuthenticationDetails } from 'amazon-cognito-identity-js';
const AuthenticationDetails = require('amazon-cognito-identity-js').AuthenticationDetails;
Required to pass user credentials (username, password) during the authentication process.
CognitoUserSession
import { CognitoUserSession } from 'amazon-cognito-identity-js';
const CognitoUserSession = require('amazon-cognito-identity-js').CognitoUserSession;
Represents the session details, including ID, access, and refresh tokens, received after successful authentication.

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));
Debug
Known issues
breakingFor 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.
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.
affects: >=6.0.0
breakingFor 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.
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.
affects: >=6.0.0
gotchaWhen 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.
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.
affects: >=1.0.0
gotchaFor 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.
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.
affects: >=6.0.0
deprecatedThe 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.
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.
affects: All versions
Errors
Common errors & fixes
UsernameExistsException: An account with the given email already exists.
Attempting to sign up a user with a username or email that is already registered in the Cognito User Pool.
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`).
NotAuthorizedException: Incorrect username or password.
The username or password provided during authentication does not match the records in Cognito, or the user is not confirmed.
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.
TypeError: (0, _getRandomBase.default) is not a function
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.
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.
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.
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.
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.
Upgrade
Version history
6.3.16latest on npm
Audit
Dependencies
@aws-amplify/corerequiredProvides core utilities and configuration common to Amplify-related libraries.
Agent activity
48 hits · last 30 days
node
38
Amazon
1
Perplexity
1
OpenAI (training)
1
Resources