Amazon Cognito Identity JavaScript SDK
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
-
UsernameExistsException: An account with the given email already exists.
cause Attempting to sign up a user with a username or email that is already registered in the Cognito User Pool.fixBefore `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.
cause The username or password provided during authentication does not match the records in Cognito, or the user is not confirmed.fixDouble-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
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.fixEnsure `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.
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.fixEnsure 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.
Warnings
- breaking 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.
- breaking 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.
- gotcha 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.
- gotcha 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.
- deprecated 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.
Install
-
npm install amazon-cognito-identity-js -
yarn add amazon-cognito-identity-js -
pnpm add amazon-cognito-identity-js
Imports
- CognitoUserPool
const CognitoUserPool = require('amazon-cognito-identity-js').CognitoUserPool;import { CognitoUserPool } from 'amazon-cognito-identity-js'; - CognitoUser
const CognitoUser = require('amazon-cognito-identity-js').CognitoUser;import { CognitoUser } from 'amazon-cognito-identity-js'; - AuthenticationDetails
const AuthenticationDetails = require('amazon-cognito-identity-js').AuthenticationDetails;import { AuthenticationDetails } from 'amazon-cognito-identity-js'; - CognitoUserSession
const CognitoUserSession = require('amazon-cognito-identity-js').CognitoUserSession;import { CognitoUserSession } from 'amazon-cognito-identity-js';
Quickstart
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));