Amazon Cognito Identity JavaScript SDK provides comprehensive user authentication and management capabilities for AWS Cognito Identity Provider service. It offers complete authentication flows including user sign-up, sign-in, multi-factor authentication (MFA), password management, user attribute management, session handling, and device management. The SDK supports various authentication methods, automatic token refresh, and seamless integration across web applications, React Native apps, and Node.js environments.
npm install amazon-cognito-identity-jsimport {
CognitoUserPool,
CognitoUser,
AuthenticationDetails,
AuthenticationHelper,
CognitoUserSession,
CognitoAccessToken,
CognitoIdToken,
CognitoRefreshToken,
CognitoUserAttribute,
CookieStorage,
DateHelper,
WordArray,
appendToCognitoUserAgent
} from "amazon-cognito-identity-js";For CommonJS:
const {
CognitoUserPool,
CognitoUser,
AuthenticationDetails,
AuthenticationHelper,
CognitoUserSession,
CognitoAccessToken,
CognitoIdToken,
CognitoRefreshToken,
CognitoUserAttribute,
CookieStorage,
DateHelper,
WordArray,
appendToCognitoUserAgent
} = require("amazon-cognito-identity-js");import { CognitoUserPool, CognitoUser, AuthenticationDetails } from "amazon-cognito-identity-js";
// Initialize user pool
const userPool = new CognitoUserPool({
UserPoolId: "us-east-1_XXXXXXXXX",
ClientId: "your-client-id"
});
// Create user
const cognitoUser = new CognitoUser({
Username: "testuser",
Pool: userPool
});
// Sign in
const authDetails = new AuthenticationDetails({
Username: "testuser",
Password: "TempPassword123!"
});
cognitoUser.authenticateUser(authDetails, {
onSuccess: (session) => {
console.log("Authentication successful");
console.log("Access Token:", session.getAccessToken().getJwtToken());
},
onFailure: (err) => {
console.error("Authentication failed:", err);
}
});Amazon Cognito Identity JavaScript SDK is built around several key components:
CognitoUserPool handles user pool configuration and user creationCognitoUser provides all user-specific operations including authentication, attribute management, and device handlingCognitoUserSession manages JWT tokens with automatic refresh capabilitiesCore user pool operations including configuration, user registration, and pool-level management.
class CognitoUserPool {
constructor(data: ICognitoUserPoolData, wrapRefreshSessionCallback?: any);
getUserPoolId(): string;
getUserPoolName(): string;
getClientId(): string;
signUp(
username: string,
password: string,
userAttributes: CognitoUserAttribute[],
validationData: CognitoUserAttribute[],
callback: NodeCallback<Error, ISignUpResult>,
clientMetadata?: ClientMetadata
): void;
getCurrentUser(): CognitoUser | null;
}
interface ICognitoUserPoolData {
UserPoolId: string;
ClientId: string;
endpoint?: string;
Storage?: ICognitoStorage;
AdvancedSecurityDataCollectionFlag?: boolean;
}Complete authentication system supporting multiple flows including SRP, custom authentication, and MFA challenges.
class AuthenticationDetails {
constructor(data: IAuthenticationDetailsData);
getUsername(): string;
getPassword(): string;
getValidationData(): any[];
getClientMetadata(): object;
}
interface IAuthenticationDetailsData {
Username: string;
Password?: string;
ValidationData?: { [key: string]: any };
ClientMetadata?: ClientMetadata;
}
interface IAuthenticationCallback {
onSuccess: (session: CognitoUserSession, userConfirmationNecessary?: boolean) => void;
onFailure: (err: any) => void;
newPasswordRequired?: (userAttributes: any, requiredAttributes: any) => void;
mfaRequired?: (challengeName: ChallengeName, challengeParameters: any) => void;
totpRequired?: (challengeName: ChallengeName, challengeParameters: any) => void;
customChallenge?: (challengeParameters: any) => void;
mfaSetup?: (challengeName: ChallengeName, challengeParameters: any) => void;
selectMFAType?: (challengeName: ChallengeName, challengeParameters: any) => void;
}Comprehensive user operations including registration, password management, and account control.
// Key user management methods from CognitoUser class
confirmRegistration(
code: string,
forceAliasCreation: boolean,
callback: NodeCallback<any, any>,
clientMetadata?: ClientMetadata
): void;
changePassword(
oldPassword: string,
newPassword: string,
callback: NodeCallback<Error, 'SUCCESS'>,
clientMetadata?: ClientMetadata
): void;
forgotPassword(
callbacks: {
onSuccess: (data: any) => void;
onFailure: (err: Error) => void;
inputVerificationCode?: (data: any) => void;
},
clientMetadata?: ClientMetadata
): void;
deleteUser(callback: NodeCallback<Error, string>): void;Token handling, validation, and automatic refresh capabilities for maintaining authenticated sessions.
class CognitoUserSession {
constructor(data: ICognitoUserSessionData);
getIdToken(): CognitoIdToken;
getAccessToken(): CognitoAccessToken;
getRefreshToken(): CognitoRefreshToken;
isValid(): boolean;
}
interface ICognitoUserSessionData {
IdToken: CognitoIdToken;
AccessToken: CognitoAccessToken;
RefreshToken?: CognitoRefreshToken;
}
// Token classes
class CognitoAccessToken {
constructor(params: { AccessToken: string });
getJwtToken(): string;
getExpiration(): number;
getIssuedAt(): number;
decodePayload(): { [key: string]: any };
}
class CognitoIdToken {
constructor(params: { IdToken: string });
getJwtToken(): string;
getExpiration(): number;
getIssuedAt(): number;
decodePayload(): { [key: string]: any };
}User attribute management including CRUD operations, verification, and attribute-specific workflows.
class CognitoUserAttribute {
constructor(data: ICognitoUserAttributeData);
Name: string;
Value: string;
getValue(): string;
setValue(value: string): CognitoUserAttribute;
getName(): string;
setName(name: string): CognitoUserAttribute;
toString(): string;
toJSON(): object;
}
interface ICognitoUserAttributeData {
Name: string;
Value: string;
}
// Key attribute methods from CognitoUser class
getUserAttributes(callback: NodeCallback<Error, CognitoUserAttribute[]>): void;
updateAttributes(
attributes: (CognitoUserAttribute | ICognitoUserAttributeData)[],
callback: UpdateAttributesNodeCallback<Error, string, any>,
clientMetadata?: ClientMetadata
): void;
deleteAttributes(attributeList: string[], callback: NodeCallback<Error, string>): void;
verifyAttribute(
attributeName: string,
confirmationCode: string,
callbacks: {
onSuccess: (success: string) => void;
onFailure: (err: Error) => void;
}
): void;Complete MFA system supporting SMS and TOTP authentication methods with user preference management.
interface IMfaSettings {
PreferredMfa: boolean;
Enabled: boolean;
}
// Key MFA methods from CognitoUser class
setUserMfaPreference(
smsMfaSettings: IMfaSettings | null,
softwareTokenMfaSettings: IMfaSettings | null,
callback: NodeCallback<Error, string>
): void;
associateSoftwareToken(callbacks: {
associateSecretCode: (secretCode: string) => void;
onFailure: (err: any) => void;
}): void;
verifySoftwareToken(
totpCode: string,
friendlyDeviceName: string,
callbacks: {
onSuccess: (session: CognitoUserSession) => void;
onFailure: (err: Error) => void;
}
): void;
sendMFACode(
confirmationCode: string,
callbacks: {
onSuccess: (session: CognitoUserSession, userConfirmationNecessary?: boolean) => void;
onFailure: (err: any) => void;
},
mfaType?: string,
clientMetadata?: ClientMetadata
): void;Device tracking, remembering, and management for enhanced security and user experience.
// Key device methods from CognitoUser class
listDevices(
limit: number,
paginationToken: string | null,
callbacks: {
onSuccess: (data: any) => void;
onFailure: (err: Error) => void;
}
): void;
setDeviceStatusRemembered(callbacks: {
onSuccess: (success: string) => void;
onFailure: (err: any) => void;
}): void;
setDeviceStatusNotRemembered(callbacks: {
onSuccess: (success: string) => void;
onFailure: (err: any) => void;
}): void;
forgetDevice(callbacks: {
onSuccess: (success: string) => void;
onFailure: (err: Error) => void;
}): void;
forgetSpecificDevice(
deviceKey: string,
callbacks: {
onSuccess: (success: string) => void;
onFailure: (err: Error) => void;
}
): void;Additional utility classes and functions for specialized operations.
class DateHelper {
/** Returns current time formatted as "ddd MMM D HH:mm:ss UTC YYYY" */
getNowString(): string;
}
class WordArray {
constructor(words?: string[], sigBytes?: number);
/** Generates random word array */
random(nBytes: number): WordArray;
/** Returns hex string representation */
toString(): string;
}
/** Appends content to Cognito User Agent string */
function appendToCognitoUserAgent(content: string): void;Note: AuthenticationHelper is exported for advanced SRP authentication scenarios but is typically handled internally by the SDK.
Flexible storage abstractions supporting various persistence mechanisms for session and configuration data.
interface ICognitoStorage {
setItem(key: string, value: string): void;
getItem(key: string): string | null;
removeItem(key: string): void;
clear(): void;
}
class CookieStorage implements ICognitoStorage {
constructor(data?: ICookieStorageData);
setItem(key: string, value: string): void;
getItem(key: string): string;
removeItem(key: string): void;
clear(): void;
}
interface ICookieStorageData {
domain?: string;
path?: string;
expires?: number;
secure?: boolean;
sameSite?: 'strict' | 'lax' | 'none';
}type NodeCallback<E, T> = (err?: E, result?: T) => void;
type UpdateAttributesNodeCallback<E, T, K> = (err?: E, result?: T, details?: K) => void;
type ClientMetadata = { [key: string]: string } | undefined;
type ChallengeName =
| 'CUSTOM_CHALLENGE'
| 'MFA_SETUP'
| 'NEW_PASSWORD_REQUIRED'
| 'SELECT_MFA_TYPE'
| 'SMS_MFA'
| 'SOFTWARE_TOKEN_MFA';
interface CodeDeliveryDetails {
AttributeName: string;
DeliveryMedium: string;
Destination: string;
}
interface ISignUpResult {
user: CognitoUser;
userConfirmed: boolean;
userSub: string;
codeDeliveryDetails: CodeDeliveryDetails;
}
interface MFAOption {
DeliveryMedium: 'SMS' | 'EMAIL';
AttributeName: string;
}
interface UserData {
MFAOptions: MFAOption[];
PreferredMfaSetting: string;
UserAttributes: ICognitoUserAttributeData[];
UserMFASettingList: string[];
Username: string;
}
interface GetSessionOptions {
clientMetadata: Record<string, string>;
}