Registry /
aws / amazon-cognito-identity-js
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
muslnode 18–226 runs
build_error
glibcnode 18–226 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));
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.
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.
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
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.
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.
Audit
Dependencies
@aws-amplify/corerequiredProvides core utilities and configuration common to Amplify-related libraries.